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.
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
Markdown
[](/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
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)
- {
- "name": "alfred-dev",
- "description": "Marketplace no oficial de Alfred Dev para Claude Code.",
- "owner": {
- "name": "686f6c61"
- },
- "plugins": [
- {
- "name": "alfred-dev",
- "displayName": "Alfred Dev",
- "description": "Plugin de ingeniería de software: 10 agentes, 11 skills planas, memoria persistente y flujos con quality gates.",
- "source": "./",
- "author": {
- "name": "686f6c61"
- },
- "category": "development",
- "homepage": "https://alfred-dev.com/"
- }
- ]
- }
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)
- ```text
- █████╗ ██╗ ███████╗██████╗ ███████╗██████╗ ██████╗ ███████╗██╗ ██╗
- ██╔══██╗██║ ██╔════╝██╔══██╗██╔════╝██╔══██╗ ██╔══██╗██╔════╝██║ ██║
- ███████║██║ █████╗ ██████╔╝█████╗ ██║ ██║ ██║ ██║█████╗ ██║ ██║
- ██╔══██║██║ ██╔══╝ ██╔══██╗██╔══╝ ██║ ██║ ██║ ██║██╔══╝ ╚██╗ ██╔╝
- ██║ ██║███████╗██║ ██║ ██║███████╗██████╔╝ ██████╔╝███████╗ ╚████╔╝
- ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚══════╝ ╚═══╝
- ```
- **Plugin de ingeniería de software automatizada para [Claude Code](https://code.claude.com/docs/en/overview).**
- 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.
- [Documentación completa](https://alfred-dev.com/) -- [Instalar](#instalación) -- [Equipo](#el-equipo) -- [Comandos](#comandos) -- [Arquitectura](#arquitectura)
- ---
- ## Qué es Alfred Dev
- 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.
- 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.
- 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.
- ## El equipo
- 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.
- 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.
- Tres principios de diseño:
- - **Responsabilidad única.** El Artesano escribe código; El Paranoico audita seguridad. Ninguno invade el territorio del otro.
- - **Herramientas restringidas.** No todos los agentes necesitan el sistema de ficheros o la terminal. Limitar herramientas reduce la superficie de error.
- - **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).
- Frontera del núcleo:
- - **`product-owner`** decide **qué** problema se resuelve y **por qué**.
- - **`architect`** decide **cómo** se implementa técnicamente.
- - **`alfred`** decide **cuándo** interviene cada uno, en qué orden y con qué gate.
- Si esas tres responsabilidades se mezclan, el flujo deja de ser previsible. Alfred coordina; no redefine alcance ni diseño por su cuenta.
- ### Flujo feature: cronología de fases
- 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.
- ```mermaid
- timeline
- title Flujo feature - fases y agentes
- producto
- : product-owner
- : Análisis de requisitos
- : Gate - aprobación del usuario
- estilo visual
- : selina
- : Dirección de estilo visual (solo con frontend)
- : Gate - elección del usuario
- arquitectura
- : architect + security-officer
- : Diseño técnico y threat model
- : Gate - aprobación del usuario
- desarrollo
- : senior-dev
- : Implementación TDD
- : Gate - tests verdes (automático)
- calidad
- : qa-engineer + security-officer
- : Tests y auditoría de seguridad
- : Gate - automático + seguridad
- documentación
- : tech-writer
- : Documentación técnica y de usuario
- : Gate - libre (sin bloqueo)
- entrega
- : devops-engineer + security-officer
- : Changelog y validación final
- : Gate - usuario + seguridad
- ```
- 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.
- ## Instalación
- Una sola línea. El script verifica el entorno, registra en Claude Code una
- fuente GitHub global para Alfred Dev e instala el plugin con la CLI nativa de Claude Code.
- No pisa `~/.claude/skills` ni crea `~/.claude/skills/alfred/SKILL.md` ni
- `~/.claude/commands/alfred.md`. La entrada es `/alfred-dev:alfred`.
- Parchea hooks y `.mcp.json` si el `python3` por defecto no es compatible.
- Antes de instalar, limpia el checkout local del marketplace
- (`~/.claude/plugins/marketplaces/alfred-dev`) y lo vuelve a registrar, para no
- materializar una caché antigua. La instalación soportada es siempre global de
- usuario: si existían rastros `local` o `project` del propio Alfred Dev, el
- instalador los normaliza y reinstala con `--scope user`. No usa un marketplace
- oficial de Anthropic: usa la CLI nativa para registrar una fuente propia no oficial.
- ```bash
- 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
- ```
- Si ya tienes este repo clonado localmente, también puedes invocarlo así:
- ```bash
- bash ./install.sh
- ```
- Después de instalar, en una sesión abierta ejecuta `/reload-plugins` para cargar
- Alfred Dev sin reiniciar. Si Claude Code avisa por coste/caché de MCP o el
- plugin no aparece, reinicia Claude Code. Verifica con:
- ```bash
- /alfred-dev:alfred
- ```
- En Windows (PowerShell):
- ```powershell
- irm https://raw.githubusercontent.com/686f6c61/alfred-dev/main/install.ps1 | iex
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 121 on GitHub
- ```
- Requisitos:
- - [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.
- - Python 3.10+ (para hooks, core y MCP en macOS, Linux y Windows).
- Para desinstalar:
- ```bash
- # macOS / Linux
- 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
- ```
- ```bash
- # macOS / Linux, desde el repo clonado
- bash ./uninstall.sh
- ```
- ```powershell
- # Windows
- irm https://raw.githubusercontent.com/686f6c61/alfred-dev/main/uninstall.ps1 | iex
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 143 on GitHub
- ```
- El desinstalador retira el plugin y la fuente del marketplace en scope `user`.
- Si queda un alias global `/alfred` de instalaciones 0.6, también lo limpia.
- No borra `.claude/` del proyecto (config, memoria SQLite, handoff).
- `/alfred-dev:update` compara la versión instalada con el último GitHub Release
- y guía la actualización. Añadir el marketplace `686f6c61/alfred-dev` instala
- lo que haya en la rama por defecto `main`.
- ## Inicio rápido
- Una vez instalado, habla en castellano. No hace falta memorizar slash commands.
- ```text
- sigue donde lo dejé
- el login peta con eñes
- cambia el texto del botón
- ```
- El hook `prompt-route.py` sugiere la ruta si el texto no trae slash. `/alfred-dev:alfred`
- decide si toca mapear, discutir, retomar, abrir UAT o arrancar un flujo.
- Si quieres el flujo largo:
- ```text
- /alfred-dev:feature sistema de login con email y password
- ```
- `/alfred-dev:ajustes` cambia autonomía y Lucius. `/alfred-dev:feature` recorre
- hasta 7 fases (producto, estilo visual, arquitectura, desarrollo, calidad,
- documentación, entrega). Autopilot solo resuelve gates de usuario configuradas;
- no salta tests, seguridad, evidencia ni confirmación humana de despliegue.
- La fase de estilo visual se activa solo si hay interfaz.
- ## Novedades en v0.7.0
- 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).
- ## Comandos
- 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`.
- ### Core
- | Comando | Descripción |
- |---------|-------------|
- | `/alfred-dev:alfred` | Entrada contextual: decide si toca mapear, discutir, retomar, abrir UAT o arrancar un flujo multiagente. |
- | `/alfred-dev:feature <desc>` | Ciclo completo de hasta 7 fases. Alfred pregunta desde qué fase arrancar. |
- | `/alfred-dev:quick <desc>` | Flujo ligero para cambios pequeños con menos ceremonia que `feature`. |
- | `/alfred-dev:fix <desc>` | Corrección de bugs en 3 fases: diagnóstico, corrección TDD, validación. |
- | `/alfred-dev:spike <tema>` | Investigación técnica sin compromiso: prototipos, benchmarks, hallazgos. |
- | `/alfred-dev:discuss <desc>` | Refina una idea o fase y deja `docs/project/discovery.md` antes de abrir `feature`. |
- | `/alfred-dev:map-codebase` | Analiza un repo existente y deja `docs/project/codebase-map.md` y `docs/project/current.md`. |
- | `/alfred-dev:progress` | Resume kanban, bloqueos, trazabilidad, UAT y estado operativo. |
- | `/alfred-dev:uat` | Crea o cierra la validación humana, separada de los tests automáticos. |
- | `/alfred-dev:audit` | Auditoría con 4 agentes en paralelo: calidad, seguridad, arquitectura, documentación. |
- | `/alfred-dev:ship` | Release: auditoría final, changelog, versionado semántico, despliegue. |
- | `/alfred-dev:memory-ui` | Abre o cierra la UI local de la memoria SQLite. |
- | `/alfred-dev:ajustes` | Configurar autonomía, stack, Lucius, memoria y personalidad. |
- ### Operativos
- | Comando | Descripción |
- |---------|-------------|
- | `/alfred-dev:retomar` | Retoma una sesión pausada usando el handoff y el estado guardado. |
- | `/alfred-dev:pause` | Pausa el trabajo en curso y genera handoff persistente. |
- | `/alfred-dev:sync-github [owner/repo]` | Refleja el tablero local en GitHub Issues usando `gh`. |
- | `/alfred-dev:lucius [dir] [--scope X]` | Segunda opinión técnica vía Codex CLI. |
- | `/alfred-dev:update` | Comprueba si hay versión nueva (GitHub Releases) y actualiza el plugin. |
- ### Ejemplo de uso
- ```
- > /alfred-dev:feature sistema de autenticación con OAuth2
- Alfred activa el flujo de hasta 7 fases:
- 1. Producto -- PRD con historias de usuario y criterios de aceptación
- 2. Estilo visual -- Tres propuestas en navegador (solo si hay UI)
- 3. Arquitectura -- Diseño de componentes, ADRs, threat model en paralelo
- 4. Desarrollo -- Implementación TDD (rojo-verde-refactor)
- 5. Calidad -- Code review + OWASP + compliance + SBOM
- 6. Documentación -- API docs, guía de usuario, changelog
- 7. Entrega -- Pipeline CI/CD, Docker, deploy
- Cada transición entre fases requiere superar la quality gate correspondiente.
- ```
- Los 6 flujos del orquestador son `feature` (hasta 7 fases), `fix` (3), `spike` (2),
- `ship` (4), `audit` (1) y `quick` (2).
- ## Arquitectura
- ### Agentes de núcleo (8 + Selina)
- 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.
- | Agente | Rol | Modelo | Responsabilidad |
- |--------|-----|--------|-----------------|
- | **Alfred** | Orquestador | inherit | Coordina flujos, activa agentes, evalúa gates entre fases |
- | **El Buscador de Problemas** | Product Owner | inherit | PRDs, historias de usuario, criterios de aceptación, análisis competitivo |
- | **Selina** | Dirección visual | inherit | Tres propuestas en navegador, artefacto `docs/style-direction.md`, gate de estilo |
- | **El Dibujante de Cajas** | Arquitecto | inherit | Diseño de sistemas, ADRs, diagramas Mermaid, matrices de decisión |
- | **El Artesano** | Senior Dev | inherit | Implementación TDD, refactoring, commits atómicos |
- | **El Paranoico** | Security Officer | inherit | OWASP Top 10, threat modeling STRIDE, SBOM, compliance RGPD/NIS2/CRA |
- | **El Rompe-cosas** | QA Engineer | inherit | Test plans, code review, exploratorio, integración, E2E, regresión |
- | **El Fontanero** | DevOps Engineer | inherit | Docker multi-stage, CI/CD, deploy, monitoring, observabilidad |
- | **El Escriba** | Tech Writer | inherit | Sync corto por fase (cabeceras, docstrings, `docs/project/`); en documentación: API docs, arquitectura, guías, changelogs |
- 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.
- ### Agente opcional (Lucius)
- 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).
- ### Skills (11)
- Cada skill es una habilidad plana en `skills/*/SKILL.md`. El catálogo publicado es:
- ```
- skills/
- compliance-check/
- evaluate-dependency/
- incident-response/
- memory/
- pr-workflow/
- sbom-generate/
- sonarqube/
- style-direction/
- sync-project-docs/
- threat-model/
- write-adr/
- ```
- Los skills con side effects (`style-direction`, `sonarqube`, `incident-response`, `pr-workflow`) declaran `disable-model-invocation: true`.
- ### Hooks (10)
- 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.
- | Hook | Evento | Función |
- |------|--------|---------|
- | `session-bootstrap.sh` | `SessionStart` | Bootstrap síncrono: config local, memoria, permisos y wrapper de continuidad |
- | `session-start.sh` | `SessionStart` | Briefing de sesión, protocolo de hablar sin slash y contexto de continuidad |
- | `session-end.py` | `SessionEnd` | Detiene Memory UI y escribe el cierre de sesión (fail-open) |
- | `prompt-route.py` | `UserPromptSubmit` | Si el texto no trae slash, sugiere fix/quick/retomar según la petición |
- | `secret-guard.py` | `PreToolUse` (Write/Edit/Bash/MCP) | Bloquea escritura de secretos |
- | `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
- | `sensitive-read-guard.py` | `PreToolUse` (Read) | Avisa al leer ficheros sensibles (claves privadas, `.env`, credenciales) |
- | `quality-gate.py` | `PostToolUse` (Bash) | Avisa cuando un runner de tests falla, usando salida y exit code |
- | `evidence-guard.py` | `PostToolUse` (Bash) | Registra evidencia de ejecución de tests para verificación de gates |
- | `activity-capture.py` | `PostToolUse` + `UserPromptSubmit` | Captura automática de actividad, commits e iteraciones |
- ### Templates (8)
- Plantillas que los agentes usan para generar artefactos con estructura estable:
- - `prd.md` -- Product Requirements Document
- - `adr.md` -- Architecture Decision Record
- - `test-plan.md` -- Plan de testing por riesgo
- - `threat-model.md` -- Modelado de amenazas STRIDE
- - `sbom.md` -- Software Bill of Materials
- - `changelog-entry.md` -- Entrada de changelog (Keep a Changelog)
- - `release-notes.md` -- Notas de release con resumen ejecutivo
- - `compliance.md` -- Checklist de cumplimiento del proyecto
- ### Core Python
- El núcleo del plugin está implementado en Python con tests unitarios. Los
- módulos se agrupan por responsabilidad para no prometer un contador fijo
- que quede obsoleto cuando crece el runtime:
- | Familia | Módulos principales | Función |
- |---------|---------------------|---------|
- | Orquestación | `orchestrator.py` | Máquina de estados de 6 flujos, sesiones, gates, autopilot, loop iterativo |
- | Personalidad | `personality.py` | Frases, tono, anuncios y formato de veredicto |
- | 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 |
- | Continuidad | `continuity.py`, `session_report.py`, `session_brief.py`, `hygiene.py` | Helpers, pausa/reanudación, briefing, higiene de ship y UAT |
- | Docs vivas | `project_docs.py` | Esqueleto y comprobación de `docs/project/` y `docs/adr/` |
- | Enrutado | `prompt_route.py` | Clasifica prompts sin slash (fix, quick, retomar, map-codebase) |
- | Memoria | `memory.py`, `memory_config.py`, `memory_sync.py`, `memory_ui_server.py` | SQLite local, sync Markdown y UI local GET |
- | Seguridad | `secrets.py` | Sanitización y detección de secretos reutilizada por memoria, empaquetado y guards |
- | Selina visual | `selina_visual.py`, `selina_style_*.py` | Dirección visual condicional, catálogo, opciones y selector |
- ```bash
- # Ejecutar tests
- python3 -m pytest tests/ -v
- ```
- ## Quality gates
- 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.
- El orquestador define 5 tipos: `libre`, `usuario`, `automatico`, `usuario+seguridad` y `automatico+seguridad`.
- | Gate | Condición |
- |------|-----------|
- | PRD aprobado | El usuario valida el PRD antes de pasar a arquitectura |
- | Diseño aprobado | El usuario aprueba el diseño Y el security officer lo valida |
- | Tests en verde | Todos los tests pasan antes de pasar a calidad |
- | Evidencia verificada | Las afirmaciones de tests deben estar respaldadas por salida real registrada por `evidence-guard.py` |
- | Loop iterativo | Si una gate falla, se reintenta hasta 5 veces con feedback antes de escalar al usuario |
- | QA + seguridad | El QA engineer y el security officer aprueban en paralelo |
- | Documentación completa | Todos los artefactos están documentados con checklist/evidencia revisable |
- | Pipeline verde | CI/CD verde, sin usuario root en contenedor, sin secretos en imagen |
- Cada gate produce un veredicto formal: **APROBADO**, **APROBADO CON CONDICIONES** o **RECHAZADO**, con hallazgos bloqueantes y próxima acción recomendada.
- ## Compliance
- El plugin integra verificaciones de compliance europeo en el flujo de desarrollo:
- - **RGPD** -- Protección de datos desde el diseño. Verificación de base legal, minimización de datos, derechos de los interesados.
- - **NIS2** -- Directiva de ciberseguridad para operadores esenciales. Gestión de riesgos, notificación de incidentes, cadena de suministro.
- - **CRA** -- Cyber Resilience Act. Requisitos de ciber-resiliencia para productos digitales con componentes conectados.
- - **OWASP Top 10** -- Verificación sistemática de las 10 vulnerabilidades más explotadas en cada revisión de seguridad.
- - **SBOM** -- Generación automática del Software Bill of Materials con inventario de dependencias, licencias y CVEs conocidos.
- ## Detección de stack
- `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.
- | Lenguaje | Señales | Qué detecta además |
- |----------|---------|-------------------|
- | 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. |
- | Python | `pyproject.toml`, `setup.py`, `requirements.txt` | FastAPI, Django, Flask, Starlette, Litestar, Sanic, Tornado, aiohttp. ORM y runner si aparecen en manifiestos. |
- | Rust | `Cargo.toml` | Runtime y lenguaje. No infiere framework. |
- | Go | `go.mod` | Runtime y lenguaje. No infiere framework. |
- | Ruby | `Gemfile` | Runtime y lenguaje. No infiere framework. |
- | Elixir | `mix.exs` | Runtime y lenguaje. No infiere framework. |
- | Java / Kotlin | `pom.xml`, `build.gradle`, `build.gradle.kts` | Spring Boot, Quarkus, Micronaut. Kotlin si hay `.kt` o Gradle Kotlin. |
- | PHP | `composer.json` | Laravel, Symfony, Slim. |
- | C# / .NET | `*.csproj`, `*.sln` | ASP.NET o Blazor. |
- | Swift | `Package.swift` | Vapor si aparece en el manifiesto. |
- Selina solo entra si el framework detectado está en el conjunto frontend (Next, Nuxt, Astro, Remix, Gatsby, Svelte, Solid, Qwik, Vue, React, Angular).
- ## Memoria persistente
- 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.
- `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.
- 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.
- Funcionalidades principales:
- - **Trazabilidad**: problema, decisión, commit y validación enlazados con IDs.
- - **Búsqueda**: texto completo con FTS5, filtros `since`/`until`, etiquetas y estado (`active`/`superseded`/`deprecated`).
- - **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.
- - **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.
- - **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.
- - **Contexto de sesión**: `session-start.sh` inyecta un briefing de estado, última decisión y ADRs aceptados.
- - **Exportación**: `memory_export` escribe decisiones a Markdown con formato ADR.
- - **Seguridad**: sanitización de secretos con los mismos patrones que `secret-guard.py`, permisos `0600` en la base de datos.
- - **Migración**: el esquema se actualiza con backup previo al abrir bases antiguas.
- ## Estructura del proyecto
- ```
- alfred-dev/
- .claude-plugin/
- plugin.json # Manifiesto del plugin (version, 18 comandos)
- marketplace.json # Metadatos de la fuente no oficial
- .mcp.json # Servidor MCP alfred-memory (stdio)
- agents/ # 10 agentes (8 de núcleo + Selina + Lucius)
- commands/ # 18 comandos publicados + helpers internos
- skills/ # Catálogo publicado de 11 skills planas
- hooks/ # 10 scripts + hooks.json
- core/ # Motor de orquestación, memoria e informes (Python)
- mcp/ # Servidor MCP stdio (memoria persistente)
- templates/ # 8 plantillas de artefactos
- visual/ # Companion local de Selina (servidor y HTML)
- tests/ # Tests y contratos de release (pytest)
- docs/ # Documentación técnica del plugin
- scripts/ # Auditoría de release y smokes
- install.sh / install.ps1
- uninstall.sh / uninstall.ps1
- ```
- 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.
- ## Configuracion
- 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:
- ```yaml
- ---
- autonomia:
- producto: autonomo
- arquitectura: autonomo
- desarrollo: autonomo
- calidad: autonomo
- documentacion: autonomo
- entrega: autonomo
- agentes_opcionales:
- lucius: false
- memoria:
- enabled: true
- sync_to_native: true
- sync_commits_limit: 10
- capture_decisions: true
- capture_commits: true
- retention_days: 365
- personalidad:
- nivel_sarcasmo: 3
- verbosidad: normal
- idioma: es
- celebrar_victorias: true
- insultar_malas_practicas: true
- ---
- Notas adicionales del proyecto que Alfred debe tener en cuenta.
- ```
- 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.
- ## Descargo de responsabilidad
- **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**.
- 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.
- 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.
- 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.
- ## Licencia
- MIT
- ---
- [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
- #!/usr/bin/env python3
- """
- Hook PreToolUse para Bash: guardia de comandos peligrosos.
- Intercepta las ejecuciones de Bash y analiza el comando en busca de patrones
- potencialmente destructivos (borrado catastrofico, force push, destruccion de
- datos, fork bombs, etc.). Si detecta un patron peligroso, bloquea la operacion
- (exit 2) con un aviso explicativo.
- Politica de seguridad: fail-closed. Si no se puede parsear la entrada del hook
- o se produce cualquier error inesperado, se bloquea la operacion (exit 2).
- Un hook de seguridad que permite la operacion cuando falla equivale a
- desactivar la proteccion justo cuando mas se necesita. Esta politica es
- coherente con secret-guard.sh, que tambien es fail-closed.
- Patrones vigilados:
- - 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
- - git push --force a main/master: perdida de historial en ramas protegidas.
- - DROP DATABASE / DROP TABLE: destruccion de datos en base de datos.
- - docker system prune -af: eliminacion de volumenes y datos de contenedores.
- - chmod -R 777: permisos inseguros en todo un arbol de directorios.
- - fork bombs: denegacion de servicio local.
- - mkfs / dd sobre dispositivos: destruccion de disco.
- - Escritura directa a dispositivos de bloque.
- """
- import json
- import os
- import re
- import shlex
- import sys
- # --- Patrones peligrosos ---------------------------------------------------
- # Cada tupla contiene (patron_compilado, descripcion_del_riesgo).
- # Los patrones se evaluan en orden; la primera coincidencia bloquea.
- _DANGEROUS_PATTERNS = [
- # Borrado catastrofico: rm -rf aplicado a raiz, home o rutas de sistema.
- # Cubre: flags juntas (-rf, -fr), separadas (-r -f), con sudo, y flags largas.
- (
- re.compile(
- r"(?:sudo\s+)?rm\s+"
- r"(?:-[a-zA-Z]*\s+)*"
- r"(?:--\w[\w-]*\s+)*"
- r"(?=-[a-zA-Z]*r)(?=.*-[a-zA-Z]*f)"
- r".*\s+(/\s|/\*|/$|~\s|~$|~\/|\$HOME|\$\{HOME\}|/usr|/etc|/var|/boot|/System)"
- ),
- "Borrado catastrofico: rm -rf sobre directorio raiz o de sistema",
- ),
- # Force push a ramas protegidas
- (
- re.compile(
- r"git\s+push\s+.*"
- r"(--force\b|-f\b)"
- r".*\b(main|master)\b"
- ),
- "Force push a rama protegida (main/master): riesgo de perdida de historial",
- ),
- # Variante: force push sin rama explicita (se asume rama actual)
- (
- re.compile(
- r"git\s+push\s+--force-with-lease\s*$"
- r"|git\s+push\s+-f\s*$"
- r"|git\s+push\s+--force\s*$"
- ),
- "Force push sin rama explicita: verifica que no estas en main/master",
- ),
- # Destruccion de base de datos
- (
- re.compile(r"DROP\s+(DATABASE|TABLE|SCHEMA)\s", re.IGNORECASE),
- "Destruccion de datos: DROP DATABASE/TABLE/SCHEMA",
- ),
- # Docker prune agresivo (cubre -af, -fa, -a -f, -f -a y combinaciones con otros flags)
- (
- re.compile(
- r"docker\s+system\s+prune\s+.*(-af|-fa)\b"
- r"|docker\s+system\s+prune\s+.*-a\b.*-f\b"
- r"|docker\s+system\s+prune\s+.*-f\b.*-a\b"
- ),
- "Docker system prune con -af: elimina todos los datos de contenedores",
- ),
- # Permisos inseguros
- (
- re.compile(r"chmod\s+(-R\s+)?777\s+/"),
- "Permisos inseguros: chmod 777 recursivo sobre directorio raiz",
- ),
- # Fork bomb (variantes comunes en bash)
- (
- re.compile(r":\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;?\s*:"),
- "Fork bomb: denegacion de servicio local",
- ),
- # Formateo de disco
- (
- re.compile(r"mkfs\.\w+\s+/dev/"),
- "Formateo de disco: mkfs sobre dispositivo de bloque",
- ),
- # dd sobre dispositivo de bloque
- (
- re.compile(r"dd\s+.*of=/dev/(sd|hd|nvme|vd|xvd)"),
- "Escritura directa a dispositivo de bloque con dd",
- ),
- # Escritura a dispositivo via redireccion
- (
- re.compile(r">\s*/dev/(sd|hd|nvme|vd|xvd)"),
- "Redireccion de salida a dispositivo de bloque",
- ),
- # git reset --hard a remote (destructivo en combinacion con push)
- (
- re.compile(r"git\s+reset\s+--hard\s+origin/(main|master)"),
- "git reset --hard a origin/main: descarta todos los cambios locales",
- ),
- ]
- _SAFE_ALFRED_HELPER_SUBCOMMANDS = frozenset({
- "allow-stop-once",
- "blocked",
- "consume-prefetch",
- "discuss",
- "in-progress",
- "map-codebase",
- "memory-ui",
- "next",
- "pause",
- "progress",
- "quick",
- "resume",
- "search",
- "standup",
- "validate",
- "verify",
- })
- _SHELL_CONTROL_TOKENS = frozenset({
- ";",
- "&&",
- "||",
- "|",
- ">",
- ">>",
- "<",
- "<<",
- "2>",
- "&>",
- "&>>",
- })
- _SHELL_CONTROL_SUBSTRINGS = (
- "$(",
- "`",
- )
- _SAFE_CAPTURE_SUFFIXES = (
- "2>&1",
- "2>/dev/null",
- "2>/dev/null 2>&1",
- )
- _DROP_SQL_REGEX = re.compile(r"\bDROP\s+(DATABASE|TABLE|SCHEMA)\b", re.IGNORECASE)
- _DEVICE_REDIRECT_REGEX = re.compile(r">\s*/dev/(sd|hd|nvme|vd|xvd)\w*", re.IGNORECASE)
- _SHELL_WRAPPERS = frozenset({"sh", "bash", "zsh"})
- _SQL_CLIENTS = frozenset({"psql", "mysql", "mariadb", "sqlite3", "duckdb"})
- def _command_basename(token: str) -> str:
- return os.path.basename(token or "")
- def _strip_leading_wrappers(tokens):
- """Elimina wrappers neutros al principio: sudo, env y variables inline."""
- idx = 0
- while idx < len(tokens):
- token = tokens[idx]
- base = _command_basename(token)
- if base == "sudo":
- idx += 1
- while idx < len(tokens) and tokens[idx].startswith("-"):
- idx += 1
- continue
- if base == "env":
- idx += 1
- while idx < len(tokens) and "=" in tokens[idx] and not tokens[idx].startswith("-"):
- idx += 1
- continue
- if "=" in token and not token.startswith("-"):
- name, _value = token.split("=", 1)
- if name.replace("_", "").isalnum():
- idx += 1
- continue
- break
- return tokens[idx:]
- def _strip_quoted_content(command: str) -> str:
- """Reemplaza el contenido entre comillas por espacios preservando operadores."""
- result = []
- in_single = False
- in_double = False
- escaped = False
- for char in command:
- if escaped:
- result.append(" " if (in_single or in_double) else char)
- escaped = False
- continue
- if char == "\\":
- escaped = True
- result.append(" " if (in_single or in_double) else char)
- continue
- if char == "'" and not in_double:
- in_single = not in_single
- result.append(" ")
- continue
- if char == '"' and not in_single:
- in_double = not in_double
- result.append(" ")
- continue
- result.append(" " if (in_single or in_double) else char)
- return "".join(result)
- def _has_shell_controls_outside_quotes(command: str) -> bool:
- """Detecta operadores de shell reales ignorando texto dentro de comillas.
- Permitimos helpers con argumentos quoted como:
- `--raw "login | signup"` o `--raw "funnel A > B"`.
- Lo que seguimos bloqueando es el uso real de operadores fuera de quotes,
- como `;`, `&&`, `||`, pipes y redirecciones.
- """
- in_single = False
- in_double = False
- escaped = False
- idx = 0
- while idx < len(command):
- char = command[idx]
- if escaped:
- escaped = False
- idx += 1
- continue
- if char == "\\":
- escaped = True
- idx += 1
- continue
- if char == "'" and not in_double:
- in_single = not in_single
- idx += 1
- continue
- if char == '"' and not in_single:
- in_double = not in_double
- idx += 1
- continue
- if in_single or in_double:
- idx += 1
- continue
- next_two = command[idx : idx + 2]
- if next_two in {"&&", "||", ">>", "<<"}:
- return True
- if char in {";", "|", ">", "<"}:
- return True
- idx += 1
- return False
- def _extract_shell_c_command(tokens):
- """Extrae el comando embebido en shell wrappers tipo sh -c / bash -lc."""
- core_tokens = _strip_leading_wrappers(tokens)
- if not core_tokens:
- return None
- base = _command_basename(core_tokens[0])
- if base not in _SHELL_WRAPPERS:
- return None
- idx = 1
- while idx < len(core_tokens):
- token = core_tokens[idx]
- if token == "-c" and idx + 1 < len(core_tokens):
- return core_tokens[idx + 1]
- if token.startswith("-") and "c" in token and idx + 1 < len(core_tokens):
- return core_tokens[idx + 1]
- idx += 1
- return None
- def _is_recursive_force_rm(tokens):
- has_recursive = False
- has_force = False
- for token in tokens:
- if token == "--recursive":
- has_recursive = True
- elif token == "--force":
- has_force = True
- elif token.startswith("-") and token != "-":
- flags = token[1:]
- has_recursive = has_recursive or ("r" in flags)
- has_force = has_force or ("f" in flags)
- return has_recursive and has_force
- def _is_sensitive_rm_target(target: str) -> bool:
- sensitive_roots = ("/", "/etc", "/usr", "/var", "/boot", "/System")
- home_markers = {"~", "~/", "$HOME", "${HOME}"}
- if target in home_markers or target.startswith("~/"):
- return True
- if target in {"/*", "~/*"}:
- return True
- if target in {"$HOME/*", "${HOME}/*"}:
- return True
- for root in sensitive_roots:
- if target == root or target == f"{root}/*":
- return True
- if root != "/" and target.startswith(root + "/"):
- return True
- return False
- def _is_absolute_permission_target(target: str) -> bool:
- return target == "/" or target.startswith("/")
- def _detect_rm(tokens):
- core_tokens = _strip_leading_wrappers(tokens)
- if not core_tokens or _command_basename(core_tokens[0]) != "rm":
- return None
- if not _is_recursive_force_rm(core_tokens[1:]):
- return None
- targets = [token for token in core_tokens[1:] if not token.startswith("-")]
- if any(_is_sensitive_rm_target(target) for target in targets):
- return "Borrado catastrofico: rm -rf sobre directorio raiz o de sistema"
- return None
- def _detect_git_push(tokens):
- core_tokens = _strip_leading_wrappers(tokens)
- if len(core_tokens) < 2:
- return None
- if _command_basename(core_tokens[0]) != "git" or core_tokens[1] != "push":
- return None
- force = any(
- token in {"--force", "--force-with-lease", "-f"}
- or (token.startswith("-") and "f" in token[1:])
- for token in core_tokens[2:]
- )
- if not force:
- return None
- protected_refs = {"main", "master", "origin/main", "origin/master", "refs/heads/main", "refs/heads/master"}
- if any(token in protected_refs for token in core_tokens[2:] if not token.startswith("-")):
- return "Force push a rama protegida (main/master): riesgo de perdida de historial"
- return "Force push sin rama explicita: verifica que no estas en main/master"
- def _detect_sql_drop(tokens):
- core_tokens = _strip_leading_wrappers(tokens)
- if not core_tokens:
- return None
- first = _command_basename(core_tokens[0]).lower()
- if first == "drop":
- if len(core_tokens) > 1 and core_tokens[1].upper() in {"DATABASE", "TABLE", "SCHEMA"}:
- return "Destruccion de datos: DROP DATABASE/TABLE/SCHEMA"
- return None
- if _command_basename(core_tokens[0]) not in _SQL_CLIENTS:
- return None
- if any(_DROP_SQL_REGEX.search(token) for token in core_tokens[1:]):
- return "Destruccion de datos: DROP DATABASE/TABLE/SCHEMA"
- return None
- def _detect_docker_prune(tokens):
- core_tokens = _strip_leading_wrappers(tokens)
- if len(core_tokens) < 3:
- return None
- if (
- _command_basename(core_tokens[0]) != "docker"
- or core_tokens[1] != "system"
- or core_tokens[2] != "prune"
- ):
- return None
- has_all = any(
- token in {"-a", "--all"} or (token.startswith("-") and "a" in token[1:])
- for token in core_tokens[3:]
- )
- has_force = any(
- token in {"-f", "--force"} or (token.startswith("-") and "f" in token[1:])
- for token in core_tokens[3:]
- )
- if has_all and has_force:
- return "Docker system prune con -af: elimina todos los datos de contenedores"
- return None
- def _detect_chmod(tokens):
- core_tokens = _strip_leading_wrappers(tokens)
- if len(core_tokens) < 3 or _command_basename(core_tokens[0]) != "chmod":
- return None
- mode_tokens = [token for token in core_tokens[1:] if not token.startswith("-")]
- if not mode_tokens or mode_tokens[0] != "777":
- return None
- targets = mode_tokens[1:]
- if any(_is_absolute_permission_target(target) for target in targets):
- return "Permisos inseguros: chmod 777 recursivo sobre directorio raiz"
- return None
- def _detect_fork_bomb(tokens):
- core_tokens = _strip_leading_wrappers(tokens)
- if core_tokens[:3] == [":(){", ":|:&", "};:"]:
- return "Fork bomb: denegacion de servicio local"
- return None
- def _detect_mkfs(tokens):
- core_tokens = _strip_leading_wrappers(tokens)
- if len(core_tokens) < 2:
- return None
- if not _command_basename(core_tokens[0]).startswith("mkfs."):
- return None
- if any(token.startswith("/dev/") for token in core_tokens[1:]):
- return "Formateo de disco: mkfs sobre dispositivo de bloque"
- return None
- def _detect_dd(tokens):
- core_tokens = _strip_leading_wrappers(tokens)
- if not core_tokens or _command_basename(core_tokens[0]) != "dd":
- return None
- if any(re.match(r"of=/dev/(sd|hd|nvme|vd|xvd)\w*", token) for token in core_tokens[1:]):
- return "Escritura directa a dispositivo de bloque con dd"
- return None
- def _detect_redirection_to_device(command: str):
- stripped = _strip_quoted_content(command)
- if _DEVICE_REDIRECT_REGEX.search(stripped):
- return "Redireccion de salida a dispositivo de bloque"
- return None
- def _detect_git_reset(tokens):
- core_tokens = _strip_leading_wrappers(tokens)
- if len(core_tokens) < 4:
- return None
- if _command_basename(core_tokens[0]) != "git" or core_tokens[1] != "reset":
- return None
- if "--hard" in core_tokens[2:] and any(
- token in {"origin/main", "origin/master"} for token in core_tokens[2:]
- ):
- return "git reset --hard a origin/main: descarta todos los cambios locales"
- return None
- def _find_dangerous_reason(command: str):
- """Devuelve la razon de bloqueo si el comando es realmente peligroso."""
- try:
- tokens = shlex.split(command)
- except ValueError:
- tokens = []
- embedded = _extract_shell_c_command(tokens) if tokens else None
- if embedded:
- return _find_dangerous_reason(embedded)
- detectors = (
- _detect_rm,
- _detect_git_push,
- _detect_sql_drop,
- _detect_docker_prune,
- _detect_chmod,
- _detect_fork_bomb,
- _detect_mkfs,
- _detect_dd,
- _detect_git_reset,
- )
- for detector in detectors:
- reason = detector(tokens)
- if reason:
- return reason
- return _detect_redirection_to_device(command)
- def _is_safe_alfred_helper_command(command: str) -> bool:
- """Reconoce helpers deterministas locales que Alfred puede autoaprobar.
- El objetivo es destrabar la primera ejecución headless de Claude Code para
- los comandos operativos helper-first. La allowlist es estrecha:
- - `python3`
- - wrapper local `.claude/alfred-continuity.py`
- - solo subcomandos deterministas y operativos
- - sin operadores de control de shell
- """
- normalized = command.strip()
- for suffix in _SAFE_CAPTURE_SUFFIXES:
- if normalized.endswith(suffix):
- normalized = normalized[: -len(suffix)].rstrip()
- break
- if any(marker in normalized for marker in _SHELL_CONTROL_SUBSTRINGS):
- return False
- if _has_shell_controls_outside_quotes(normalized):
- return False
- try:
- tokens = shlex.split(normalized)
- except ValueError:
- return False
- if len(tokens) < 3:
- return False
- if tokens[0] != "python3":
- return False
- if tokens[1] != ".claude/alfred-continuity.py":
- return False
- if tokens[2] not in _SAFE_ALFRED_HELPER_SUBCOMMANDS:
- return False
- if any(token in _SHELL_CONTROL_TOKENS for token in tokens):
- return False
- return True
- def main():
- """Punto de entrada del hook.
- Lee el JSON de stdin proporcionado por PreToolUse, extrae el comando
- de ``tool_input.command`` y lo compara contra la lista de patrones
- peligrosos. Si alguno coincide, bloquea la operacion con exit 2.
- """
- try:
- data = json.load(sys.stdin)
- except (ValueError, json.JSONDecodeError) as e:
- # Fail-closed: si no podemos parsear, bloquear por precaucion.
- # Un guard de seguridad que falla en abierto equivale a no tenerlo.
- print(
- f"[Alfred Dev] BLOQUEADO: no se pudo parsear la entrada del hook: {e}. "
- f"La guardia de comandos peligrosos bloquea por precaucion.",
- file=sys.stderr,
- )
- sys.exit(2)
- tool_input = data.get("tool_input", {})
- command = tool_input.get("command", "")
- if not command:
- sys.exit(0)
- if _is_safe_alfred_helper_command(command):
- json.dump(
- {
- "hookSpecificOutput": {
- "hookEventName": "PreToolUse",
- "permissionDecision": "allow",
- }
- },
- sys.stdout,
- )
- sys.exit(0)
- description = _find_dangerous_reason(command)
- if description:
- # Bloquear con aviso explicativo
- print(
- f"\n[Alfred Dev] COMANDO PELIGROSO BLOQUEADO\n\n"
- f" Comando: {command[:200]}\n"
- f" Riesgo: {description}\n\n"
- f" Si realmente necesitas ejecutar este comando, pidele\n"
- f" al usuario que lo ejecute manualmente en su terminal.\n",
- file=sys.stderr,
- )
- sys.exit(2)
- # Comando seguro, permitir
- sys.exit(0)
- if __name__ == "__main__":
- main()
install.ps1 · Bundled script · 441 lines · 1 finding marked
- # ---------------------------------------------------------------------------
- # Alfred Dev -- script de instalacion para Claude Code (Windows)
- #
- # Uso:
- # 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
- #
- # Que hace:
- # 1. Verifica que Claude Code esta instalado
- # 2. Registra globalmente en Claude Code la fuente GitHub del plugin
- # 3. Instala el plugin con claude plugin install
- # 4. No pisa ~/.claude/skills ni instala alias global /alfred
- # 5. Listo para usar: /alfred-dev:alfred
- #
- # El script delega toda la gestion en la CLI nativa de Claude Code
- # (claude plugin marketplace / claude plugin install) para registrar una
- # fuente GitHub personalizada, no oficial, y mantener compatibilidad futura.
- # ---------------------------------------------------------------------------
- $ErrorActionPreference = 'Stop'
- $Repo = "686f6c61/alfred-dev"
- $PluginName = "alfred-dev"
- $Version = "0.7.0"
- # -- Funciones auxiliares ---------------------------------------------------
- function Write-Info { param([string]$Msg) Write-Host ">" $Msg -ForegroundColor Blue }
- function Write-Ok { param([string]$Msg) Write-Host "+" $Msg -ForegroundColor Green }
- function Write-Err { param([string]$Msg) Write-Host "x" $Msg -ForegroundColor Red }
- function Get-CompatiblePython {
- $candidates = @(
- @{ Display = "py -3.13"; Command = "py"; LauncherArg = "-3.13" },
- @{ Display = "py -3.12"; Command = "py"; LauncherArg = "-3.12" },
- @{ Display = "py -3.11"; Command = "py"; LauncherArg = "-3.11" },
- @{ Display = "py -3.10"; Command = "py"; LauncherArg = "-3.10" },
- @{ Display = "python3"; Command = "python3" },
- @{ Display = "python"; Command = "python" }
- )
- foreach ($candidate in $candidates) {
- if (-not (Get-Command $candidate.Command -ErrorAction SilentlyContinue)) {
- continue
- }
- try {
- $args = @()
- if ($candidate.ContainsKey("LauncherArg")) {
- $args += $candidate.LauncherArg
- }
- $args += @(
- "-c",
- 'import sys; print(sys.executable); print("{}.{}".format(sys.version_info.major, sys.version_info.minor))'
- )
- $output = & $candidate.Command @args 2>$null
- if ($LASTEXITCODE -ne 0 -or $null -eq $output -or $output.Count -lt 2) {
- continue
- }
- $pythonPath = "$($output[0])".Trim()
- $version = "$($output[1])".Trim()
- $parts = $version -split '\.'
- if ($parts.Count -lt 2) {
- continue
- }
- $major = [int]$parts[0]
- $minor = [int]$parts[1]
- if ($major -gt 3 -or ($major -eq 3 -and $minor -ge 10)) {
- return @{
- DisplayCommand = $candidate.Display
- ExecutablePath = $pythonPath
- Version = $version
- }
- }
- }
- catch {
- continue
- }
- }
- return $null
- }
- function Write-TextFileAtomic {
- param([string]$Path, [string]$Content)
- $targetDir = Split-Path $Path -Parent
- $tmpFile = Join-Path $targetDir ".tmp-$([System.IO.Path]::GetRandomFileName())"
- try {
- [System.IO.File]::WriteAllText($tmpFile, $Content, [System.Text.Encoding]::UTF8)
- Move-Item -Path $tmpFile -Destination $Path -Force
- }
- catch {
- if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
- throw
- }
- }
- function Get-InstalledPluginRoot {
- param(
- [string]$ClaudeDir,
- [string]$PluginName,
- [string]$Version
- )
- $cacheDir = Join-Path $ClaudeDir "plugins/cache/$PluginName"
- $exact = Join-Path $cacheDir "$PluginName/$Version"
- $legacy = Join-Path $cacheDir $Version
- if (Test-Path $exact -PathType Container) { return $exact }
- if (Test-Path $legacy -PathType Container) { return $legacy }
- if (-not (Test-Path $cacheDir -PathType Container)) { return $null }
- $candidates = Get-ChildItem -Path $cacheDir -Filter plugin.json -Recurse -ErrorAction SilentlyContinue |
- Where-Object { $_.FullName -like "*\.claude-plugin\*" } |
- Sort-Object LastWriteTimeUtc -Descending
- foreach ($candidate in $candidates) {
- try {
- $data = (Get-Content $candidate.FullName -Raw -Encoding UTF8) | ConvertFrom-Json
- }
- catch {
- continue
- }
- if ($data.version -ne $Version) {
- continue
- }
- return Split-Path (Split-Path $candidate.FullName -Parent) -Parent
- }
- return $null
- }
- function Test-GlobalSourceRegistration {
- param(
- [string]$ClaudeDir,
- [string]$PluginName,
- [string]$Repo
- )
- $knownMarketplaces = Join-Path $ClaudeDir "plugins/known_marketplaces.json"
- if (-not (Test-Path $knownMarketplaces -PathType Leaf)) {
- return $false
- }
- try {
- $data = (Get-Content $knownMarketplaces -Raw -Encoding UTF8) | ConvertFrom-Json
- }
- catch {
- return $false
- }
- if (-not $data.PSObject.Properties.Name.Contains($PluginName)) {
- return $false
- }
- $entry = $data.$PluginName
- return $entry.source.source -eq "github" -and $entry.source.repo -eq $Repo
- }
- function Normalize-ToUserScopeInstallation {
- param(
- [string]$PluginName,
- [string]$PluginKey
- )
- # Alfred Dev solo soporta instalacion global de usuario. Si alguien lo
- # instalo antes en local/project, limpiamos ese rastro en el contexto actual
- # antes de reinstalar con --scope user.
- & claude plugin uninstall $PluginKey --scope local 2>&1 | Out-Null
- & claude plugin uninstall $PluginKey --scope project 2>&1 | Out-Null
- & claude plugin marketplace remove $PluginName --scope local 2>&1 | Out-Null
- & claude plugin marketplace remove $PluginName --scope project 2>&1 | Out-Null
- Write-Ok "Scopes local/project normalizados; Alfred se instalara como usuario global"
- }
- function Remove-StaleUserMarketplaceCheckout {
- param(
- [string]$ClaudeDir,
- [string]$PluginName
- )
- $marketplaceDir = Join-Path $ClaudeDir "plugins/marketplaces/$PluginName"
- if (Test-Path $marketplaceDir -PathType Container) {
- Remove-Item -Path $marketplaceDir -Recurse -Force
- Write-Ok "Checkout local del marketplace limpiado para evitar cache obsoleta"
- }
- }
- function Update-UserMarketplace {
- param([string]$PluginName)
- $updateResult = & claude plugin marketplace update $PluginName 2>&1
- if ($LASTEXITCODE -eq 0) {
- Write-Ok "Marketplace local actualizado"
- }
- else {
- Write-Info "No se pudo ejecutar 'claude plugin marketplace update'; continuo con el checkout recien registrado"
- }
- }
- function Assert-UserScopeInstallation {
- param([string]$PluginKey)
- $pluginListJson = & claude plugin list --json 2>$null
- if ($LASTEXITCODE -ne 0) {
- Write-Err "No se pudo confirmar el scope global con 'claude plugin list --json'"
- Write-Err "Alfred Dev debe quedar instalado como scope user."
- exit 1
- }
- try {
- $entries = @(($pluginListJson | Out-String) | ConvertFrom-Json)
- }
- catch {
- Write-Err "JSON invalido en claude plugin list --json: $_"
- exit 1
- }
- $matches = @($entries | Where-Object { $_.id -eq $PluginKey })
- if ($matches.Count -eq 0) {
- Write-Err "No aparece $PluginKey en claude plugin list --json"
- exit 1
- }
- $activeNonUser = @($matches | Where-Object { $_.enabled -eq $true -and $_.scope -ne "user" })
- if ($activeNonUser.Count -gt 0) {
- $details = @($activeNonUser | ForEach-Object {
- "scope=$($_.scope) projectPath=$($_.projectPath)"
- }) -join ", "
- Write-Err "Hay instalaciones activas no globales de ${PluginKey}: $details"
- exit 1
- }
- $enabledUser = @($matches | Where-Object { $_.enabled -eq $true -and $_.scope -eq "user" })
- if ($enabledUser.Count -eq 0) {
- $scopes = @($matches | ForEach-Object { "$($_.scope)" }) -join ", "
- Write-Err "$PluginKey existe, pero no hay entrada enabled con scope user. Scopes vistos: $scopes"
- exit 1
- }
- $staleNonUser = @($matches | Where-Object { $_.enabled -ne $true -and $_.scope -ne "user" })
- if ($staleNonUser.Count -gt 0) {
- $details = @($staleNonUser | ForEach-Object {
- "scope=$($_.scope) projectPath=$($_.projectPath)"
- }) -join ", "
- Write-Info "AVISO: quedan entradas antiguas no activas de ${PluginKey}: $details"
- }
- Write-Ok "Instalacion global de usuario confirmada (--scope user)"
- }
- # -- Verificaciones ---------------------------------------------------------
- $Python = Get-CompatiblePython
- if ($null -eq $Python) {
- Write-Err "No se encontro Python 3.10 o superior"
- Write-Err "Se buscaron: py -3.13, py -3.12, py -3.11, py -3.10, python3, python"
- Write-Err "Alfred Dev necesita Python para hooks, core y MCP tambien en Windows"
- exit 1
- }
- Write-Ok "Python $($Python.Version) detectado ($($Python.DisplayCommand))"
- if (-not $env:USERPROFILE -or -not (Test-Path $env:USERPROFILE -PathType Container)) {
- Write-Err "USERPROFILE no esta definido o no apunta a un directorio valido"
- exit 1
- }
- $ClaudeDir = Join-Path $env:USERPROFILE ".claude"
- if (-not (Test-Path $ClaudeDir)) {
- Write-Err "No se encontro el directorio $ClaudeDir"
- Write-Err "Asegurate de tener Claude Code instalado: https://code.claude.com/docs/en/setup"
- exit 1
- }
- if (-not (Get-Command claude -ErrorAction SilentlyContinue)) {
- Write-Err "El comando 'claude' no esta disponible en el PATH"
- Write-Err "Asegurate de tener Claude Code instalado y accesible desde la terminal"
- exit 1
- }
- # -- Instalacion ------------------------------------------------------------
- Write-Host ""
- Write-Host "Alfred Dev" -ForegroundColor White -NoNewline
- Write-Host " v$Version" -ForegroundColor DarkGray
- Write-Host "Plugin de ingenieria de software automatizada" -ForegroundColor DarkGray
- Write-Host ""
- # -- 1. Registrar fuente global en Claude Code ------------------------------
- Write-Info "Registrando fuente GitHub global en Claude Code..."
- $pluginKey = "$PluginName@$PluginName"
- Normalize-ToUserScopeInstallation -PluginName $PluginName -PluginKey $pluginKey
- $pluginList = & claude plugin list 2>&1
- if ($pluginList -match [regex]::Escape($pluginKey)) {
- & claude plugin uninstall $pluginKey --scope user 2>&1 | Out-Null
- }
- $marketplaceList = & claude plugin marketplace list 2>&1
- if ($marketplaceList -match $PluginName) {
- & claude plugin marketplace remove $PluginName --scope user 2>&1 | Out-Null
- }
- Remove-StaleUserMarketplaceCheckout -ClaudeDir $ClaudeDir -PluginName $PluginName
- $marketplaceResult = & claude plugin marketplace add $Repo --scope user 2>&1
- if ($LASTEXITCODE -eq 0) {
- Write-Ok "Fuente GitHub declarada"
- }
- else {
- Write-Err "No se pudo registrar la fuente GitHub"
- Write-Err "Verifica tu conexion a internet y que el repositorio sea accesible:"
- Write-Err " https://github.com/$Repo"
- exit 1
- }
- if (Test-GlobalSourceRegistration -ClaudeDir $ClaudeDir -PluginName $PluginName -Repo $Repo) {
- Write-Ok "Fuente GitHub registrada globalmente"
- }
- else {
- Write-Info "La CLI respondio OK, pero la fuente no quedo registrada; reintentando..."
- & claude plugin marketplace remove $PluginName --scope user 2>&1 | Out-Null
- $marketplaceResult = & claude plugin marketplace add $Repo --scope user 2>&1
- if ($LASTEXITCODE -eq 0 -and (Test-GlobalSourceRegistration -ClaudeDir $ClaudeDir -PluginName $PluginName -Repo $Repo)) {
- Write-Ok "Fuente GitHub registrada globalmente tras reintento"
- }
- else {
- Write-Err "Claude Code no dejo registrada la fuente global del plugin"
- Write-Err "Fichero esperado: $(Join-Path $ClaudeDir 'plugins/known_marketplaces.json')"
- Write-Err "Prueba a ejecutar manualmente:"
- Write-Err " claude plugin marketplace remove $PluginName --scope user"
- Write-Err " claude plugin marketplace add $Repo --scope user"
- exit 1
- }
- }
- Update-UserMarketplace -PluginName $PluginName
- # -- 2. Instalar plugin -----------------------------------------------------
- Write-Info "Instalando plugin..."
- $installResult = & claude plugin install $pluginKey --scope user 2>&1
- if ($LASTEXITCODE -eq 0) {
- Write-Ok "Plugin instalado y habilitado"
- }
- else {
- Write-Err "No se pudo instalar el plugin"
- Write-Err "Puedes intentar instalarlo manualmente:"
- Write-Err " claude plugin marketplace add $Repo --scope user"
- Write-Err " claude plugin install $pluginKey --scope user"
- exit 1
- }
- # -- 3. Parchear hooks y MCP con el Python detectado -----------------------
- $PluginRoot = Get-InstalledPluginRoot -ClaudeDir $ClaudeDir -PluginName $PluginName -Version $Version
- $hooksJson = $null
- $mcpJson = $null
- Write-Info "Usa /alfred-dev:alfred o /alfred-dev:feature. No se pisa ~/.claude/skills."
- Assert-UserScopeInstallation -PluginKey $pluginKey
- if ($PluginRoot) {
- $hooksPath = Join-Path $PluginRoot "hooks/hooks.json"
- $mcpPath = Join-Path $PluginRoot ".mcp.json"
- if (Test-Path $hooksPath -PathType Leaf) {
- $hooksJson = Get-Item $hooksPath
- }
- if (Test-Path $mcpPath -PathType Leaf) {
- $mcpJson = Get-Item $mcpPath
- }
- }
- if ($hooksJson) {
- $hooksData = (Get-Content $hooksJson.FullName -Raw -Encoding UTF8) | ConvertFrom-Json
- $patchedHooks = $false
- $quotedPython = '"' + $Python.ExecutablePath + '" ${CLAUDE_PLUGIN_ROOT}'
- foreach ($eventGroup in $hooksData.hooks.PSObject.Properties) {
- foreach ($matcher in $eventGroup.Value) {
- if (-not $matcher.hooks) { continue }
- foreach ($hook in $matcher.hooks) {
- if ($hook.type -ne 'command' -or -not $hook.command) { continue }
- if ($hook.command -eq 'python3') {
- $hook.command = $Python.ExecutablePath
- $patchedHooks = $true
- continue
- }
- if ($hook.command -match 'python3 \$\{CLAUDE_PLUGIN_ROOT\}') {
- $hook.command = $hook.command -replace 'python3 \$\{CLAUDE_PLUGIN_ROOT\}', $quotedPython
- $patchedHooks = $true
- }
- }
- }
- }
- if ($patchedHooks) {
- Write-TextFileAtomic $hooksJson.FullName ($hooksData | ConvertTo-Json -Depth 20)
- Write-Ok "hooks.json parcheado para usar $($Python.ExecutablePath)"
- }
- }
- else {
- Write-Info "Aviso: no se encontro hooks.json en la instalacion activa para parchear Python"
- }
- if ($mcpJson) {
- $mcpData = (Get-Content $mcpJson.FullName -Raw -Encoding UTF8) | ConvertFrom-Json
- $mcpServers = $mcpData
- if ($mcpData.PSObject.Properties.Name.Contains("mcpServers")) {
- $mcpServers = $mcpData.mcpServers
- }
- if ($mcpServers.'alfred-memory'.command -ne $Python.ExecutablePath) {
- $mcpServers.'alfred-memory'.command = $Python.ExecutablePath
- Write-TextFileAtomic $mcpJson.FullName ($mcpData | ConvertTo-Json -Depth 20)
- Write-Ok ".mcp.json parcheado para usar $($Python.ExecutablePath)"
- }
- }
- else {
- Write-Info "Aviso: no se encontro .mcp.json en la instalacion activa para parchear Python"
- }
- # -- Resultado --------------------------------------------------------------
- Write-Host ""
- Write-Host "Instalacion completada" -ForegroundColor Green
- Write-Host ""
- Write-Host " En Claude Code, ejecuta /reload-plugins y despues:"
- Write-Host " /alfred-dev:alfred" -ForegroundColor White
- Write-Host " Estado: /alfred-dev:progress · retomar: /alfred-dev:retomar" -ForegroundColor DarkGray
- Write-Host ""
- Write-Host " Si /reload-plugins avisa por MCP/coste de cache o no aparece el plugin, reinicia Claude Code." -ForegroundColor DarkGray
- Write-Host " Repositorio: https://github.com/$Repo" -ForegroundColor DarkGray
- Write-Host " Documentacion: https://alfred-dev.com" -ForegroundColor DarkGray
- Write-Host ""
install.sh · Bundled script · 522 lines · 1 finding marked
- #!/usr/bin/env bash
- # ---------------------------------------------------------------------------
- # Alfred Dev -- script de instalacion para Claude Code
- #
- # Uso:
- # 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
- # bash ./install.sh
- #
- # Que hace:
- # 1. Verifica que Claude Code esta instalado
- # 2. Registra globalmente en Claude Code la fuente GitHub del plugin
- # 3. Instala el plugin con claude plugin install
- # 4. No pisa ~/.claude/skills ni instala alias global /alfred
- # 5. Listo para usar: /alfred-dev:alfred
- #
- # El script delega toda la gestion en la CLI nativa de Claude Code
- # (claude plugin marketplace / claude plugin install) para registrar una
- # fuente GitHub personalizada, no oficial, y mantener compatibilidad futura.
- # ---------------------------------------------------------------------------
- set -euo pipefail
- REPO="686f6c61/alfred-dev"
- PLUGIN_NAME="alfred-dev"
- VERSION="0.7.0"
- # -- Colores ----------------------------------------------------------------
- RED='\033[0;31m'
- GREEN='\033[0;32m'
- BLUE='\033[0;34m'
- DIM='\033[2m'
- BOLD='\033[1m'
- NC='\033[0m'
- info() { printf "${BLUE}>${NC} %s\n" "$1"; }
- ok() { printf "${GREEN}+${NC} %s\n" "$1"; }
- error() { printf "${RED}x${NC} %s\n" "$1" >&2; }
- resolve_installed_plugin_root() {
- local cache_dir="${HOME}/.claude/plugins/cache/${PLUGIN_NAME}"
- local exact="${cache_dir}/${PLUGIN_NAME}/${VERSION}"
- local legacy="${cache_dir}/${VERSION}"
- if [[ -d "${exact}" ]]; then
- printf '%s\n' "${exact}"
- return 0
- fi
- if [[ -d "${legacy}" ]]; then
- printf '%s\n' "${legacy}"
- return 0
- fi
- "${PYTHON_CMD}" - "${cache_dir}" "${VERSION}" <<'PYEOF'
- import json
- import os
- import sys
- cache_dir, target_version = sys.argv[1:3]
- candidates = []
- for root, _dirs, files in os.walk(cache_dir):
- if "plugin.json" not in files or ".claude-plugin" not in root:
- continue
- plugin_json = os.path.join(root, "plugin.json")
- try:
- with open(plugin_json, "r", encoding="utf-8") as fh:
- version = json.load(fh).get("version")
- except (OSError, json.JSONDecodeError):
- continue
- if version != target_version:
- continue
- plugin_root = os.path.dirname(root)
- try:
- mtime = os.path.getmtime(plugin_json)
- except OSError:
- mtime = 0
- candidates.append((mtime, plugin_root))
- if not candidates:
- sys.exit(1)
- candidates.sort(key=lambda item: item[0], reverse=True)
- print(candidates[0][1])
- PYEOF
- }
- is_global_source_registered() {
- local known_marketplaces_file="${HOME}/.claude/plugins/known_marketplaces.json"
- [[ -f "${known_marketplaces_file}" ]] || return 1
- "${PYTHON_CMD}" - "${known_marketplaces_file}" "${PLUGIN_NAME}" "${REPO}" <<'PYEOF'
- import json
- import sys
- path, plugin_name, repo = sys.argv[1:4]
- try:
- with open(path, "r", encoding="utf-8") as fh:
- data = json.load(fh)
- except (OSError, json.JSONDecodeError):
- sys.exit(1)
- entry = data.get(plugin_name)
- source = entry.get("source", {}) if isinstance(entry, dict) else {}
- if source.get("source") == "github" and source.get("repo") == repo:
- sys.exit(0)
- sys.exit(1)
- PYEOF
- }
- normalize_to_user_scope_installation() {
- # Alfred Dev solo soporta instalacion global de usuario. Si alguien lo
- # instalo antes en local/project, limpiamos ese rastro en el contexto actual
- # antes de reinstalar con --scope user.
- claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope local >/dev/null 2>&1 || true
- claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope project >/dev/null 2>&1 || true
- claude plugin marketplace remove "${PLUGIN_NAME}" --scope local >/dev/null 2>&1 || true
- claude plugin marketplace remove "${PLUGIN_NAME}" --scope project >/dev/null 2>&1 || true
- ok "Scopes local/project normalizados; Alfred se instalara como usuario global"
- }
- remove_stale_user_marketplace_checkout() {
- local marketplace_dir="${HOME}/.claude/plugins/marketplaces/${PLUGIN_NAME}"
- if [[ -d "${marketplace_dir}" ]]; then
- rm -rf "${marketplace_dir}"
- ok "Checkout local del marketplace limpiado para evitar cache obsoleta"
- fi
- }
- refresh_user_marketplace() {
- # Claude Code puede conservar un clon local obsoleto del marketplace aunque
- # 'plugin install' termine correctamente. Forzamos refresh antes de instalar
- # para que cache/alfred-dev materialice la version publicada actual.
- if claude plugin marketplace update "${PLUGIN_NAME}" 2>&1; then
- ok "Marketplace local actualizado"
- else
- info "No se pudo ejecutar 'claude plugin marketplace update'; continuo con el checkout recien registrado"
- fi
- }
- verify_user_scope_installation() {
- local plugin_key="${PLUGIN_NAME}@${PLUGIN_NAME}"
- local list_json
- local verify_output
- if ! list_json=$(claude plugin list --json 2>/dev/null); then
- error "No se pudo confirmar el scope global con 'claude plugin list --json'"
- error "Alfred Dev debe quedar instalado como scope user."
- return 1
- fi
- if verify_output=$(
- CLAUDE_PLUGIN_LIST_JSON="${list_json}" "${PYTHON_CMD}" - "${plugin_key}" <<'PYEOF'
- import json
- import os
- import sys
- plugin_key = sys.argv[1]
- try:
- entries = json.loads(os.environ.get("CLAUDE_PLUGIN_LIST_JSON", ""))
- except json.JSONDecodeError as exc:
- print(f"JSON invalido en claude plugin list --json: {exc}", file=sys.stderr)
- sys.exit(1)
- if not isinstance(entries, list):
- print("claude plugin list --json no devolvio una lista", file=sys.stderr)
- sys.exit(1)
- matches = [entry for entry in entries if isinstance(entry, dict) and entry.get("id") == plugin_key]
- if not matches:
- print(f"No aparece {plugin_key} en claude plugin list --json", file=sys.stderr)
- sys.exit(1)
- active_non_user = [
- entry for entry in matches
- if entry.get("enabled") is True and entry.get("scope") != "user"
- ]
- if active_non_user:
- details = ", ".join(
- f"scope={entry.get('scope', 'desconocido')} projectPath={entry.get('projectPath', '')}"
- for entry in active_non_user
- )
- print(f"Hay instalaciones activas no globales de {plugin_key}: {details}", file=sys.stderr)
- sys.exit(1)
- enabled_user = [
- entry for entry in matches
- if entry.get("enabled") is True and entry.get("scope") == "user"
- ]
- if not enabled_user:
- scopes = ", ".join(str(entry.get("scope", "desconocido")) for entry in matches)
- print(f"{plugin_key} existe, pero no hay entrada enabled con scope user. Scopes vistos: {scopes}", file=sys.stderr)
- sys.exit(1)
- stale_non_user = [
- entry for entry in matches
- if entry.get("enabled") is not True and entry.get("scope") != "user"
- ]
- if stale_non_user:
- details = ", ".join(
- f"scope={entry.get('scope', 'desconocido')} projectPath={entry.get('projectPath', '')}"
- for entry in stale_non_user
- )
- print(f"AVISO: quedan entradas antiguas no activas de {plugin_key}: {details}")
- PYEOF
- ); then
- if [[ -n "${verify_output}" ]]; then
- info "${verify_output}"
- fi
- ok "Instalacion global de usuario confirmada (--scope user)"
- return 0
- fi
- error "${verify_output}"
- return 1
- }
- # -- Verificaciones ---------------------------------------------------------
- # Python 3.10+ es necesario para los hooks y el core del plugin.
- # En macOS, /usr/bin/python3 suele ser 3.9 (Apple). Los usuarios pueden
- # tener 3.10+ via Homebrew, pyenv o instalador oficial como python3.13,
- # python3.12, etc. Buscamos la mejor version disponible.
- PYTHON_CMD=""
- PYTHON_VERSION=""
- # Buscar entre los candidatos mas comunes en orden descendente
- for candidate in python3 python3.13 python3.12 python3.11 python3.10; do
- if command -v "$candidate" &>/dev/null; then
- ver=$("$candidate" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
- major=$(echo "$ver" | cut -d. -f1)
- minor=$(echo "$ver" | cut -d. -f2)
- if [[ "$major" -ge 3 ]] && [[ "$minor" -ge 10 ]]; then
- PYTHON_CMD="$candidate"
- PYTHON_VERSION="$ver"
- break
- fi
- fi
- done
- if [[ -z "$PYTHON_CMD" ]]; then
- # Ultimo intento: Homebrew en las rutas habituales de macOS
- for brew_path in /opt/homebrew/bin /usr/local/bin; do
- for candidate in python3.13 python3.12 python3.11 python3.10 python3; do
- full="${brew_path}/${candidate}"
- if [[ -x "$full" ]]; then
- ver=$("$full" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
- major=$(echo "$ver" | cut -d. -f1)
- minor=$(echo "$ver" | cut -d. -f2)
- if [[ "$major" -ge 3 ]] && [[ "$minor" -ge 10 ]]; then
- PYTHON_CMD="$full"
- PYTHON_VERSION="$ver"
- break 2
- fi
- fi
- done
- done
- fi
- if [[ -z "$PYTHON_CMD" ]]; then
- error "No se encontro Python 3.10 o superior"
- error "Se buscaron: python3, python3.13, python3.12, python3.11, python3.10"
- error "Tambien en /opt/homebrew/bin y /usr/local/bin"
- error ""
- error "Instala Python desde https://www.python.org/downloads/"
- error "o con Homebrew: brew install python@3.12"
- exit 1
- fi
- ok "Python $PYTHON_VERSION detectado ($PYTHON_CMD)"
- # Si python3 del PATH no es el que encontramos, avisar al usuario
- DEFAULT_PY_VER=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
- if [[ "$PYTHON_CMD" != "python3" ]] && [[ "$DEFAULT_PY_VER" != "$PYTHON_VERSION" ]]; then
- info "Nota: 'python3' en tu PATH es $DEFAULT_PY_VER (demasiado antiguo)"
- info "Los hooks del plugin usaran '$PYTHON_CMD' en su lugar"
- fi
- if [[ -z "${HOME:-}" ]] || [[ ! -d "${HOME}" ]]; then
- error "La variable HOME no esta definida o no apunta a un directorio valido"
- exit 1
- fi
- if [ ! -d "${HOME}/.claude" ]; then
- error "No se encontro el directorio ~/.claude"
- error "Asegurate de tener Claude Code instalado: https://code.claude.com/docs/en/setup"
- exit 1
- fi
- if ! command -v claude &>/dev/null; then
- error "El comando 'claude' no esta disponible en el PATH"
- error "Asegurate de tener Claude Code instalado y accesible desde la terminal"
- exit 1
- fi
- # -- Instalacion ------------------------------------------------------------
- printf "\n${BOLD}Alfred Dev${NC} ${DIM}v${VERSION}${NC}\n"
- printf "${DIM}Plugin de ingenieria de software automatizada${NC}\n\n"
- # -- 1. Registrar fuente global en Claude Code ------------------------------
- # Si ya existe, la actualizamos eliminandola primero para forzar un refresh
- # del registro global y del cache con los ficheros mas recientes del repo.
- info "Registrando fuente GitHub global en Claude Code..."
- normalize_to_user_scope_installation
- # Si existe una instalacion previa, la quitamos antes de refrescar el
- # marketplace. Esto evita estados intermedios donde el plugin sigue apuntando
- # a un marketplace ya corrupto o incompleto en disco.
- if claude plugin list 2>/dev/null | grep -q "${PLUGIN_NAME}@${PLUGIN_NAME}"; then
- claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope user >/dev/null 2>&1 || true
- fi
- if claude plugin marketplace list 2>/dev/null | grep -q "${PLUGIN_NAME}"; then
- claude plugin marketplace remove "${PLUGIN_NAME}" --scope user >/dev/null 2>&1 || true
- fi
- remove_stale_user_marketplace_checkout
- if claude plugin marketplace add "${REPO}" --scope user 2>&1; then
- ok "Fuente GitHub declarada"
- else
- error "No se pudo registrar la fuente GitHub"
- error "Verifica tu conexion a internet y que el repositorio sea accesible:"
- error " https://github.com/${REPO}"
- exit 1
- fi
- # Lo que vuelve global la instalacion no es una carpeta concreta, sino que
- # Claude Code deje registrada la fuente en known_marketplaces.json.
- if is_global_source_registered; then
- ok "Fuente GitHub registrada globalmente"
- else
- info "La CLI respondio OK, pero la fuente no quedo registrada; reintentando..."
- claude plugin marketplace remove "${PLUGIN_NAME}" --scope user >/dev/null 2>&1 || true
- if claude plugin marketplace add "${REPO}" --scope user 2>&1 && is_global_source_registered; then
- ok "Fuente GitHub registrada globalmente tras reintento"
- else
- error "Claude Code no dejo registrada la fuente global del plugin"
- error "Fichero esperado: ${HOME}/.claude/plugins/known_marketplaces.json"
- error "Prueba a ejecutar manualmente:"
- error " claude plugin marketplace remove ${PLUGIN_NAME} --scope user"
- error " claude plugin marketplace add ${REPO} --scope user"
- exit 1
- fi
- fi
- refresh_user_marketplace
- # -- 2. Instalar plugin -----------------------------------------------------
- info "Instalando plugin..."
- if claude plugin install "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope user 2>&1; then
- ok "Plugin instalado y habilitado"
- else
- error "No se pudo instalar el plugin"
- error "Puedes intentar instalarlo manualmente:"
- error " claude plugin marketplace add ${REPO} --scope user"
- error " claude plugin install ${PLUGIN_NAME}@${PLUGIN_NAME} --scope user"
- exit 1
- fi
- info "Usa /alfred-dev:alfred o /alfred-dev:feature. No se pisa ~/.claude/skills."
- verify_user_scope_installation
- # -- 3. Parchear hooks y MCP si python3 no es 3.10+ ------------------------
- # Si el python3 por defecto del sistema es demasiado antiguo pero encontramos
- # una version compatible (python3.12, python3.11, etc.), actualizamos la
- # configuracion instalada para que hooks y el MCP usen esa version concreta.
- if [[ "$PYTHON_CMD" != "python3" ]]; then
- _patch_in_place() {
- local file="$1"
- local expression="$2"
- if sed -i.bak "$expression" "$file" 2>/dev/null; then
- rm -f "${file}.bak"
- return 0
- fi
- # macOS sed tiene sintaxis diferente para -i
- sed -i '' "$expression" "$file" 2>/dev/null
- }
- # Obtener la ruta absoluta del Python compatible
- PYTHON_ABS=$(command -v "$PYTHON_CMD" 2>/dev/null || echo "$PYTHON_CMD")
- # Resolver de forma determinista la raiz del plugin recien instalado.
- # Si coexisten varias versiones en cache, preferimos la ruta exacta de
- # la version que acaba de instalarse y, en ultimo termino, la mas reciente
- # cuyo plugin.json declare esa version.
- PLUGIN_ROOT=$(resolve_installed_plugin_root 2>/dev/null || true)
- HOOKS_JSON=""
- MCP_JSON=""
- if [[ -n "${PLUGIN_ROOT}" ]]; then
- HOOKS_JSON="${PLUGIN_ROOT}/hooks/hooks.json"
- MCP_JSON="${PLUGIN_ROOT}/.mcp.json"
- fi
- if [[ -f "$HOOKS_JSON" ]]; then
- if "${PYTHON_CMD}" - "$HOOKS_JSON" "$PYTHON_ABS" <<'PYEOF'
- import json
- import os
- import sys
- import tempfile
- path, python_abs = sys.argv[1:3]
- with open(path, "r", encoding="utf-8") as fh:
- data = json.load(fh)
- patched = False
- for event_group in data.get("hooks", {}).values():
- if not isinstance(event_group, list):
- continue
- for matcher in event_group:
- if not isinstance(matcher, dict):
- continue
- for hook in matcher.get("hooks", []):
- if not isinstance(hook, dict) or hook.get("type") != "command":
- continue
- command = hook.get("command")
- if command == "python3":
- hook["command"] = python_abs
- patched = True
- elif isinstance(command, str) and "python3 ${CLAUDE_PLUGIN_ROOT}" in command:
- hook["command"] = command.replace(
- "python3 ${CLAUDE_PLUGIN_ROOT}",
- f"{python_abs} ${{CLAUDE_PLUGIN_ROOT}}",
- )
- patched = True
- if not patched:
- raise SystemExit("hooks.json no contiene hooks Python parcheables")
- directory = os.path.dirname(path)
- fd, tmp_path = tempfile.mkstemp(prefix=".tmp-plugin-", dir=directory)
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as fh:
- json.dump(data, fh, ensure_ascii=False, indent=2)
- fh.write("\n")
- os.replace(tmp_path, path)
- except Exception:
- try:
- os.unlink(tmp_path)
- except OSError:
- pass
- raise
- PYEOF
- then
- ok "hooks.json parcheado para usar $PYTHON_ABS"
- else
- info "Aviso: no se pudo parchear hooks.json, los hooks usaran 'python3'"
- fi
- else
- info "Aviso: no se encontro hooks.json en la instalacion activa para parchear Python"
- fi
- if [[ -f "$MCP_JSON" ]]; then
- if "${PYTHON_CMD}" - "$MCP_JSON" "$PYTHON_ABS" <<'PYEOF'
- import json
- import os
- import sys
- import tempfile
- path, python_abs = sys.argv[1:3]
- with open(path, "r", encoding="utf-8") as fh:
- data = json.load(fh)
- mcp_servers = data.get("mcpServers") if isinstance(data.get("mcpServers"), dict) else data
- if not isinstance(mcp_servers, dict):
- raise SystemExit(".mcp.json no declara servidores MCP")
- alfred_memory = mcp_servers.get("alfred-memory")
- if not isinstance(alfred_memory, dict):
- raise SystemExit(".mcp.json no declara alfred-memory")
- alfred_memory["command"] = python_abs
- directory = os.path.dirname(path)
- fd, tmp_path = tempfile.mkstemp(prefix=".tmp-plugin-", dir=directory)
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as fh:
- json.dump(data, fh, ensure_ascii=False, indent=2)
- fh.write("\n")
- os.replace(tmp_path, path)
- except Exception:
- try:
- os.unlink(tmp_path)
- except OSError:
- pass
- raise
- PYEOF
- then
- ok ".mcp.json parcheado para usar $PYTHON_ABS"
- else
- info "Aviso: no se pudo parchear .mcp.json, el MCP usara 'python3'"
- fi
- else
- info "Aviso: no se encontro .mcp.json en la instalacion activa para parchear Python"
- fi
- fi
- # -- Resultado --------------------------------------------------------------
- printf "\n${GREEN}${BOLD}Instalacion completada${NC}\n\n"
- printf " En Claude Code, ejecuta ${BOLD}/reload-plugins${NC} y despues:\n"
- printf " ${BOLD}/alfred-dev:alfred${NC}\n"
- printf " ${DIM}Estado: /alfred-dev:progress · retomar: /alfred-dev:retomar${NC}\n\n"
- printf " ${DIM}Si /reload-plugins avisa por MCP/coste de cache o no aparece el plugin, reinicia Claude Code.${NC}\n"
- printf " ${DIM}Repositorio: https://github.com/${REPO}${NC}\n"
- printf " ${DIM}Documentacion: https://alfred-dev.com${NC}\n\n"
scripts/release_audit.py · Bundled script · 4,056 lines · 2 findings marked
- #!/usr/bin/env python3
- """Verificador reproducible para la auditoria de release 0.7.0.
- El modo por defecto ejecuta checks locales rapidos: versionado, manifiestos,
- inventario del repositorio, documentacion de la auditoria y forma del MCP.
- Los smokes que dependen de herramientas externas se activan con flags.
- """
- from __future__ import annotations
- import argparse
- from collections import Counter
- import hashlib
- import importlib.util
- import json
- import os
- import re
- import selectors
- import subprocess
- import sys
- import tempfile
- import unicodedata
- from pathlib import Path
- from typing import Iterable
- ROOT = Path(__file__).resolve().parents[1]
- if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
- VERSION = "0.7.0"
- OLD_VERSION = "0.5" + ".3"
- INSTALLED_PLUGIN_DIR = Path.home() / ".claude" / "plugins" / "cache" / "alfred-dev" / "alfred-dev" / VERSION
- GLOBAL_ALFRED_ALIAS_FILE = Path.home() / ".claude" / "skills" / "alfred" / "SKILL.md"
- GLOBAL_ALFRED_COMMAND_FILE = Path.home() / ".claude" / "commands" / "alfred.md"
- INSTALLED_CACHE_FRESHNESS_ROOTS = (
- ".claude-plugin",
- "agents",
- "commands",
- "core",
- "hooks",
- "mcp",
- "skills",
- "templates",
- ".mcp.json",
- "package.json",
- "README.md",
- "scripts",
- )
- PUBLISHABLE_SYMLINK_ROOTS = INSTALLED_CACHE_FRESHNESS_ROOTS
- IGNORE_DIRS = {
- ".git",
- ".pytest_cache",
- "__pycache__",
- "node_modules",
- "dist",
- "coverage-html",
- "site/dist",
- "site/node_modules",
- }
- IGNORED_TEXT_FILE_GLOBS = {
- "docs/external-live-smoke*.json",
- "docs/manual-smoke*.json",
- "docs/manual-smoke*.md",
- }
- MANUAL_ONLY_SKILLS = (
- "skills/style-direction/SKILL.md",
- "skills/incident-response/SKILL.md",
- "skills/sonarqube/SKILL.md",
- "skills/pr-workflow/SKILL.md",
- )
- TEMPLATE_PATHS = (
- "templates/adr.md",
- "templates/changelog-entry.md",
- "templates/prd.md",
- "templates/release-notes.md",
- "templates/sbom.md",
- "templates/test-plan.md",
- "templates/threat-model.md",
- "templates/compliance.md",
- )
- PLUGIN_COMPONENT_FIELDS_REQUIRING_EXPLICIT_AUDIT = {
- "agents": "Claude los descubre desde agents/",
- "hooks": "usar hooks/hooks.json y mantener el gate especifico de hooks",
- "mcpServers": "usar .mcp.json raiz y mantener el gate especifico de MCP",
- "lspServers": "anadir gate de LSP antes de publicarlo",
- "outputStyles": "anadir gate de output-styles antes de publicarlo",
- "channels": "anadir gate de channels/MCP antes de publicarlo",
- "dependencies": "anadir gate de dependencias de plugins antes de publicarlas",
- }
- PLUGIN_EXPERIMENTAL_FIELDS_REQUIRING_EXPLICIT_AUDIT = {
- "themes": "anadir gate de themes antes de publicarlo",
- "monitors": "anadir gate de monitors antes de publicarlo",
- }
- MARKETPLACE_ENTRY_FIELDS_REQUIRING_EXPLICIT_AUDIT = {
- "agents": "no suplementar agentes fuera de plugin.json",
- "commands": "no suplementar comandos fuera de plugin.json",
- "dependencies": "no introducir dependencias de marketplace sin gate",
- "hooks": "no suplementar hooks fuera de hooks/hooks.json",
- "lspServers": "no activar LSP desde marketplace sin gate",
- "mcpServers": "no suplementar MCP fuera de .mcp.json",
- "outputStyles": "no activar output-styles desde marketplace sin gate",
- "skills": "no suplementar skills fuera de plugin.json",
- "experimental": "no activar componentes experimentales desde marketplace sin gate",
- "defaultEnabled": "no cambiar enablement desde marketplace; plugin.json/documentacion deben ser la autoridad",
- }
- HOOK_EVENTS_WITHOUT_MATCHER = {
- "CwdChanged",
- "MessageDisplay",
- "PostToolBatch",
- "SessionEnd",
- "Stop",
- "TaskCompleted",
- "TaskCreated",
- "TeammateIdle",
- "UserPromptSubmit",
- "WorktreeCreate",
- "WorktreeRemove",
- }
- HOOK_EVENTS_WITH_IF_SUPPORT = {
- "PreToolUse",
- "PostToolUse",
- "PostToolUseFailure",
- "PermissionRequest",
- "PermissionDenied",
- }
- HOOK_SYNC_TIMEOUT_LIMIT = 10
- SKILL_SUPPORTED_FIELDS = {
- "name",
- "description",
- "when_to_use",
- "argument-hint",
- "arguments",
- "disable-model-invocation",
- "user-invocable",
- "allowed-tools",
- "disallowed-tools",
- "model",
- "effort",
- "context",
- "agent",
- "hooks",
- "paths",
- "shell",
- }
- SKILL_BOOLEAN_FIELDS = {"disable-model-invocation", "user-invocable"}
- SKILL_BOOLEAN_VALUES = {"true", "false"}
- SKILL_CONTEXT_VALUES = {"fork"}
- SKILL_EFFORT_VALUES = {"low", "medium", "high", "xhigh", "max"}
- SKILL_LISTING_TEXT_LIMIT = 1536
- SKILL_SHELL_VALUES = {"bash", "powershell"}
- COMMAND_SUPPORTED_FIELDS = {
- "allowed-tools",
- "argument-hint",
- "description",
- "disallowed-tools",
- "disable-model-invocation",
- "model",
- }
- AGENT_SUPPORTED_FIELDS = {
- "name",
- "description",
- "prompt",
- "tools",
- "disallowedTools",
- "model",
- "maxTurns",
- "skills",
- "initialPrompt",
- "memory",
- "effort",
- "background",
- "isolation",
- "color",
- }
- PLUGIN_IGNORED_AGENT_FIELDS = {"hooks", "mcpServers", "permissionMode"}
- AGENT_MODEL_ALIASES = {"sonnet", "opus", "haiku", "fable", "inherit"}
- AGENT_MODEL_ID_RE = re.compile(r"^claude-[a-z0-9]+(?:-[a-z0-9]+)*$")
- AGENT_COLOR_VALUES = {"red", "blue", "green", "yellow", "purple", "orange", "pink", "cyan"}
- CLAUDE_TOOL_NAMES = {
- "Agent",
- "Artifact",
- "AskUserQuestion",
- "Bash",
- "CronCreate",
- "CronDelete",
- "CronList",
- "Edit",
- "EnterPlanMode",
- "EnterWorktree",
- "ExitPlanMode",
- "ExitWorktree",
- "Glob",
- "Grep",
- "ListMcpResourcesTool",
- "LSP",
- "Monitor",
- "NotebookEdit",
- "PowerShell",
- "PushNotification",
- "Read",
- "ReadMcpResourceTool",
- "RemoteTrigger",
- "SendMessage",
- "ShareOnboardingGuide",
- "WaitForMcpServers",
- "WebFetch",
- "WebSearch",
- "Workflow",
- "Write",
- }
- CLAUDE_PERMISSION_RULE_NAMES = CLAUDE_TOOL_NAMES | {"Skill"}
- SUBAGENT_UNAVAILABLE_TOOLS = {
- "AskUserQuestion",
- "EnterPlanMode",
- "ExitPlanMode",
- "ScheduleWakeup",
- "WaitForMcpServers",
- }
- ALFRED_AGENT_MODEL_POLICY = Counter({"inherit": 10})
- class AuditError(AssertionError):
- """Error de contrato de release."""
- def _read(path: str) -> str:
- return (ROOT / path).read_text(encoding="utf-8")
- def _json(path: str):
- return json.loads(_read(path))
- def _has_site() -> bool:
- return (ROOT / "site" / "package.json").is_file()
- def _fail(message: str) -> None:
- raise AuditError(message)
- def _rel(path: Path) -> str:
- return str(path.relative_to(ROOT))
- def _sha256(path: Path) -> str:
- return hashlib.sha256(path.read_bytes()).hexdigest()
- def _iter_installed_cache_freshness_files() -> Iterable[str]:
- for root_name in INSTALLED_CACHE_FRESHNESS_ROOTS:
- root_path = ROOT / root_name
- if root_path.is_file():
- yield root_name
- continue
- if not root_path.is_dir():
- continue
- for path in sorted(root_path.rglob("*")):
- if "__pycache__" in path.parts or path.suffix in {".pyc", ".pyo"}:
- continue
- if path.is_file():
- yield _rel(path)
- def _normalize(text: str) -> str:
- decomposed = unicodedata.normalize("NFKD", text)
- return "".join(ch for ch in decomposed if not unicodedata.combining(ch)).lower()
- def _iter_text_files() -> Iterable[Path]:
- for path in ROOT.rglob("*"):
- if not path.is_file():
- continue
- rel_path = path.relative_to(ROOT)
- rel_name = str(rel_path)
- if any(rel_path.match(pattern) or rel_name == pattern for pattern in IGNORED_TEXT_FILE_GLOBS):
- continue
- rel_parts = path.relative_to(ROOT).parts
- rel_prefixes = {
- "/".join(rel_parts[:index])
- for index in range(1, len(rel_parts) + 1)
- }
- if rel_prefixes & IGNORE_DIRS:
- continue
- if path.suffix in {".png", ".jpg", ".jpeg", ".gif", ".ico", ".db"}:
- continue
- yield path
- def check_versions() -> list[str]:
- plugin = _json(".claude-plugin/plugin.json")
- package = _json("package.json")
- version_points = {
- ".claude-plugin/plugin.json": plugin.get("version"),
- "package.json": package.get("version"),
- }
- if _has_site():
- site_package = _json("site/package.json")
- site_lock = _json("site/package-lock.json")
- version_points.update({
- "site/package.json": site_package.get("version"),
- "site/package-lock.json": site_lock.get("version"),
- "site/package-lock root": site_lock["packages"][""].get("version"),
- })
- bad = {
- name: value
- for name, value in version_points.items()
- if value != VERSION
- }
- if bad:
- _fail(f"Versiones no alineadas a {VERSION}: {bad}")
- offenders: list[str] = []
- for path in _iter_text_files():
- try:
- text = path.read_text(encoding="utf-8")
- except UnicodeDecodeError:
- continue
- if OLD_VERSION in text or f"v{OLD_VERSION}" in text:
- offenders.append(_rel(path))
- if offenders:
- _fail(f"Quedan restos vivos de {OLD_VERSION}: {offenders}")
- return [f"versiones alineadas a {VERSION}", f"sin restos de {OLD_VERSION}"]
- def _skill_files_from_manifest(plugin: dict) -> list[Path]:
- skill_files: list[Path] = []
- declared = plugin.get("skills") or ["./skills/"]
- for relative in declared:
- absolute = ROOT / relative.lstrip("./")
- if absolute.is_dir():
- skill_files.extend(sorted(absolute.rglob("SKILL.md")))
- elif absolute.name == "SKILL.md" and absolute.is_file():
- skill_files.append(absolute)
- return sorted(skill_files)
- def _manifest_component_paths(plugin: dict, field: str) -> tuple[list[Path], list[str]]:
- values = plugin.get(field)
- if field == "skills" and values is None:
- return [ROOT / "skills"], []
- if not isinstance(values, list):
- return [], [f"plugin.json {field} debe ser una lista"]
- paths: list[Path] = []
- problems: list[str] = []
- seen: set[str] = set()
- root = ROOT.resolve()
- for index, raw_value in enumerate(values):
- label = f"plugin.json {field}[{index}]"
- if not isinstance(raw_value, str):
- problems.append(f"{label} debe ser string relativo: {raw_value!r}")
- continue
- if not raw_value.startswith("./"):
- problems.append(f"{label} debe empezar por ./ para resolverse desde el root del plugin: {raw_value!r}")
- if Path(raw_value).is_absolute():
- problems.append(f"{label} no puede ser absoluto: {raw_value!r}")
- if ".." in Path(raw_value).parts:
- problems.append(f"{label} no puede atravesar fuera del plugin con ..: {raw_value!r}")
- normalized = raw_value[2:] if raw_value.startswith("./") else raw_value
- if normalized in seen:
- problems.append(f"{label} duplica una ruta del manifest: {raw_value!r}")
- seen.add(normalized)
- target = (ROOT / normalized).resolve()
- try:
- target.relative_to(root)
- except ValueError:
- problems.append(f"{label} resuelve fuera del root del plugin: {raw_value!r}")
- paths.append(ROOT / normalized)
- return paths, problems
- def check_inventory() -> list[str]:
- plugin = _json(".claude-plugin/plugin.json")
- marketplace = _json(".claude-plugin/marketplace.json")
- marketplace_plugins = marketplace.get("plugins")
- marketplace_problems: list[str] = []
- if marketplace.get("name") != plugin.get("name"):
- marketplace_problems.append(
- f"marketplace.name debe coincidir con plugin.name: {marketplace.get('name')!r}"
- )
- if not isinstance(marketplace.get("owner"), dict) or not marketplace["owner"].get("name"):
- marketplace_problems.append("marketplace.owner.name es obligatorio")
- if not isinstance(marketplace_plugins, list) or len(marketplace_plugins) != 1:
- marketplace_problems.append("marketplace.plugins debe contener exactamente una entrada")
- marketplace_plugin = {}
- else:
- marketplace_plugin = marketplace_plugins[0]
- if not isinstance(marketplace_plugin, dict):
- marketplace_problems.append("marketplace.plugins[0] debe ser objeto")
- marketplace_plugin = {}
- if marketplace_plugin:
- if marketplace_plugin.get("name") != plugin.get("name"):
- marketplace_problems.append(
- "marketplace.plugins[0].name debe coincidir con plugin.name: "
- f"{marketplace_plugin.get('name')!r}"
- )
- if marketplace_plugin.get("strict") is False:
- marketplace_problems.append(
- "marketplace.plugins[0].strict=false haria que marketplace reemplace plugin.json"
- )
- marketplace_problems.extend(
- f"marketplace.plugins[0] no debe declarar {field}: {reason}"
- for field, reason in sorted(MARKETPLACE_ENTRY_FIELDS_REQUIRING_EXPLICIT_AUDIT.items())
- if field in marketplace_plugin
- )
- if marketplace_problems:
- _fail("Marketplace de Alfred Dev desalineado: " + "; ".join(marketplace_problems))
- plugin_component_problems = [
- f"plugin.json no debe declarar {field}: {reason}"
- for field, reason in sorted(PLUGIN_COMPONENT_FIELDS_REQUIRING_EXPLICIT_AUDIT.items())
- if field in plugin
- ]
- experimental = plugin.get("experimental")
- if experimental is not None and not isinstance(experimental, dict):
- plugin_component_problems.append("plugin.json experimental debe ser un objeto")
- elif isinstance(experimental, dict):
- plugin_component_problems.extend(
- f"plugin.json no debe declarar experimental.{field}: {reason}"
- for field, reason in sorted(
- PLUGIN_EXPERIMENTAL_FIELDS_REQUIRING_EXPLICIT_AUDIT.items()
- )
- if field in experimental
- )
- if plugin_component_problems:
- _fail("Componentes de plugin sin auditoria explicita: " + "; ".join(plugin_component_problems))
- command_paths, command_path_problems = _manifest_component_paths(plugin, "commands")
- _skill_manifest_paths, skill_path_problems = _manifest_component_paths(plugin, "skills")
- path_problems = command_path_problems + skill_path_problems
- if path_problems:
- _fail("Paths de componentes del manifest incompatibles: " + "; ".join(path_problems))
- missing_commands = [_rel(path) for path in command_paths if not path.exists()]
- if missing_commands:
- _fail(f"Comandos publicados inexistentes: {missing_commands}")
- public_command_paths = {path.resolve() for path in command_paths}
- extra_command_files = sorted(
- path for path in (ROOT / "commands").glob("*.md")
- if path.resolve() not in public_command_paths
- )
- if set(_rel(path) for path in extra_command_files) != {
- "commands/_composicion.md",
- "commands/_docs_vivas.md",
- "commands/next.md",
- "commands/search.md",
- }:
- _fail(
- "commands/ contiene ficheros no publicados inesperados: "
- f"{[_rel(path) for path in extra_command_files]}"
- )
- agent_files = sorted((ROOT / "agents").glob("*.md"))
- nested_agent_files = [
- path for path in (ROOT / "agents").rglob("*.md")
- if path.parent != ROOT / "agents"
- ]
- agent_frontmatter_problems: list[str] = []
- agent_models: Counter[str] = Counter()
- for path in agent_files:
- agent_text = _read(_rel(path))
- frontmatter_values = _frontmatter_top_level_values(agent_text)
- field_set = set(frontmatter_values)
- ignored = sorted(field_set & PLUGIN_IGNORED_AGENT_FIELDS)
- unknown = sorted(field_set - AGENT_SUPPORTED_FIELDS - PLUGIN_IGNORED_AGENT_FIELDS)
- if ignored:
- agent_frontmatter_problems.append(
- f"{_rel(path)} usa campos ignorados en agentes de plugin: {ignored}"
- )
- if unknown:
- agent_frontmatter_problems.append(
- f"{_rel(path)} usa campos no soportados en frontmatter: {unknown}"
- )
- for required in ("name", "description", "model"):
- if required not in field_set:
- agent_frontmatter_problems.append(f"{_rel(path)} no declara {required}")
- model = frontmatter_values.get("model")
- if model:
- agent_models[model] += 1
- if not _is_supported_agent_model(model):
- agent_frontmatter_problems.append(
- f"{_rel(path)} usa modelo no soportado por Claude Code actual: {model!r}"
- )
- color = frontmatter_values.get("color")
- if color and color not in AGENT_COLOR_VALUES:
- agent_frontmatter_problems.append(
- f"{_rel(path)} usa color de subagente no soportado por Claude Code actual: {color!r}"
- )
- unavailable_tools = sorted(
- _frontmatter_tool_names(frontmatter_values.get("tools", ""))
- & SUBAGENT_UNAVAILABLE_TOOLS
- )
- unknown_tools = sorted(
- tool_name
- for tool_name in _frontmatter_tool_names(frontmatter_values.get("tools", ""))
- if not _is_known_agent_tool_name(tool_name)
- )
- if unknown_tools:
- agent_frontmatter_problems.append(
- f"{_rel(path)} lista herramientas desconocidas por Claude Code actual: {unknown_tools}"
- )
- if unavailable_tools:
- agent_frontmatter_problems.append(
- f"{_rel(path)} lista herramientas no disponibles en subagentes: {unavailable_tools}"
- )
- unavailable_mentions = sorted(
- tool for tool in SUBAGENT_UNAVAILABLE_TOOLS if tool in agent_text
- )
- if unavailable_mentions:
- agent_frontmatter_problems.append(
- f"{_rel(path)} instruye herramientas no disponibles en subagentes: {unavailable_mentions}"
- )
- if agent_models and agent_models != ALFRED_AGENT_MODEL_POLICY:
- agent_frontmatter_problems.append(
- "distribucion de modelos de agentes desalineada con la politica 0.7.0: "
- f"actual={dict(sorted(agent_models.items()))} "
- f"esperada={dict(sorted(ALFRED_AGENT_MODEL_POLICY.items()))}"
- )
- if agent_frontmatter_problems:
- _fail("Frontmatter de agentes incompatible: " + "; ".join(agent_frontmatter_problems))
- skill_files = _skill_files_from_manifest(plugin)
- skill_frontmatter_problems: list[str] = []
- skill_names: dict[str, list[str]] = {}
- for path in skill_files:
- skill_text = _read(_rel(path))
- frontmatter_values = _frontmatter_top_level_values(skill_text)
- field_set = set(frontmatter_values)
- unknown = sorted(field_set - SKILL_SUPPORTED_FIELDS)
- if unknown:
- skill_frontmatter_problems.append(
- f"{_rel(path)} usa campos no soportados en skill frontmatter: {unknown}"
- )
- for required in ("name", "description"):
- if required not in field_set:
- skill_frontmatter_problems.append(f"{_rel(path)} no declara {required}")
- listing_text_length = len(
- _frontmatter_field_text(skill_text, "description")
- + _frontmatter_field_text(skill_text, "when_to_use")
- )
- if listing_text_length > SKILL_LISTING_TEXT_LIMIT:
- skill_frontmatter_problems.append(
- f"{_rel(path)} excede el limite de listing de skills "
- f"{SKILL_LISTING_TEXT_LIMIT} chars: {listing_text_length}"
- )
- name = frontmatter_values.get("name")
- if name:
- skill_names.setdefault(name, []).append(_rel(path))
- if name != path.parent.name:
- skill_frontmatter_problems.append(
- f"{_rel(path)} declara name={name!r} pero el directorio es {path.parent.name!r}"
- )
- for boolean_field in sorted(SKILL_BOOLEAN_FIELDS):
- value = frontmatter_values.get(boolean_field)
- if value and value.lower() not in SKILL_BOOLEAN_VALUES:
- skill_frontmatter_problems.append(
- f"{_rel(path)} usa {boolean_field} no booleano: {value!r}"
- )
- model = frontmatter_values.get("model")
- if model and not _is_supported_agent_model(model):
- skill_frontmatter_problems.append(
- f"{_rel(path)} usa modelo de skill no soportado por Claude Code actual: {model!r}"
- )
- effort = frontmatter_values.get("effort")
- if effort and effort not in SKILL_EFFORT_VALUES:
- skill_frontmatter_problems.append(
- f"{_rel(path)} usa effort no soportado por Claude Code actual: {effort!r}"
- )
- context = frontmatter_values.get("context")
- if context and context not in SKILL_CONTEXT_VALUES:
- skill_frontmatter_problems.append(
- f"{_rel(path)} usa context no soportado por Claude Code actual: {context!r}"
- )
- if frontmatter_values.get("agent") and context != "fork":
- skill_frontmatter_problems.append(
- f"{_rel(path)} declara agent sin context: fork"
- )
- shell = frontmatter_values.get("shell")
- if shell and shell not in SKILL_SHELL_VALUES:
- skill_frontmatter_problems.append(
- f"{_rel(path)} usa shell no soportado por Claude Code actual: {shell!r}"
- )
- for tools_field in ("allowed-tools", "disallowed-tools"):
- unknown_tools = sorted(
- tool_name
- for tool_name in _frontmatter_tool_rule_names(
- _frontmatter_field_rule_text(skill_text, tools_field)
- )
- if not _is_known_permission_rule_name(tool_name)
- )
- if unknown_tools:
- skill_frontmatter_problems.append(
- f"{_rel(path)} {tools_field} declara herramientas desconocidas {unknown_tools}"
- )
- duplicated_skill_names = {
- name: paths for name, paths in sorted(skill_names.items()) if len(paths) > 1
- }
- if duplicated_skill_names:
- skill_frontmatter_problems.append(
- f"skills con name duplicado: {duplicated_skill_names}"
- )
- if skill_frontmatter_problems:
- _fail("Frontmatter de skills incompatible: " + "; ".join(skill_frontmatter_problems))
- domains = {
- path.relative_to(ROOT / "skills").parts[0]
- for path in skill_files
- if path.is_relative_to(ROOT / "skills")
- }
- if plugin.get("skills"):
- _fail(
- "plugin.json no debe listar skills: Claude las descubre en skills/*/SKILL.md"
- )
- if plugin.get("displayName") != "Alfred Dev":
- _fail("plugin.json debe declarar displayName humano 'Alfred Dev'")
- if marketplace_plugin.get("displayName") != plugin.get("displayName"):
- _fail("marketplace.json debe reutilizar el displayName humano del plugin")
- if "version" in marketplace_plugin:
- _fail(
- "marketplace.json no debe duplicar version cuando plugin.json ya "
- "declara version; Claude Code usa plugin.json como fuente canonica"
- )
- marketplace_source = marketplace_plugin.get("source")
- if isinstance(marketplace_source, str) and ".." in marketplace_source.split("/"):
- _fail("El source relativo del marketplace no debe escapar del root")
- if marketplace_source != "./":
- _fail(
- "El marketplace local debe apuntar al root del plugin para esta "
- f"auditoria: {marketplace_source!r}"
- )
- expected = {
- "commands": (len(plugin["commands"]), 18),
- "agents": (len(agent_files), 10),
- "nested_agents": (len(nested_agent_files), 0),
- "skills": (len(skill_files), 11),
- "skill_domains": (len(domains), 11),
- }
- bad = {
- key: {"actual": actual, "expected": wanted}
- for key, (actual, wanted) in expected.items()
- if actual != wanted
- }
- if bad:
- _fail(f"Inventario desalineado: {bad}")
- if not (ROOT / "commands" / "alfred.md").is_file():
- _fail("commands/alfred.md debe existir como comando publico")
- if "./commands/alfred.md" not in plugin.get("commands", []):
- _fail("plugin.json debe publicar ./commands/alfred.md")
- return [
- "18 comandos namespaced publicados",
- "commands/alfred.md publicado como entrada contextual",
- "commands/_composicion.md interno",
- "10 agentes en agents/ raiz",
- "frontmatter de agentes compatible con plugins",
- "herramientas de agentes validadas contra nombres oficiales de Claude Code",
- "herramientas no disponibles excluidas de subagentes",
- "modelos inherit en los 10 agentes",
- "11 skills planas",
- "frontmatter de skills compatible con Claude Code actual",
- "valores de frontmatter de skills validados contra Claude Code actual",
- "descripciones de skills dentro del limite de listing 1536",
- "displayName humano alineado entre manifest y marketplace",
- "version canonica solo en plugin.json; marketplace sin version duplicada",
- "marketplace no suplementa componentes ni enablement",
- "paths de comandos/skills acotados al root del plugin",
- "manifest sin componentes no auditados",
- ]
- def _command_names_from_manifest(plugin: dict) -> list[str]:
- return [
- Path(relative_path).stem
- for relative_path in plugin["commands"]
- ]
- def _public_route_names(plugin: dict | None = None) -> set[str]:
- plugin = plugin or _json(".claude-plugin/plugin.json")
- names = set(_command_names_from_manifest(plugin))
- return names
- def _public_argument_commands(plugin: dict | None = None) -> set[str]:
- """Comandos cuya superficie publica acepta texto, flags u opciones libres."""
- plugin = plugin or _json(".claude-plugin/plugin.json")
- commands: set[str] = set()
- for relative_path in plugin["commands"]:
- text = _read(relative_path.lstrip("./"))
- frontmatter = _frontmatter_block(text)
- if "$ARGUMENTS" in text or re.search(r"(?m)^argument-hint:\s*.+$", frontmatter):
- commands.add(Path(relative_path).stem)
- if (ROOT / "skills" / "alfred" / "alfred" / "SKILL.md").exists():
- commands.add("alfred")
- return commands
- def _validate_manual_option_contract_shape(manual_smoke, option_coverage: dict[str, list[str]]) -> None:
- """Evita falsos verdes por typos en los IDs de opciones manuales."""
- option_contracts = tuple(manual_smoke.OPTION_CONTRACTS)
- problems: list[str] = []
- duplicates = sorted({
- key for key in option_contracts
- if option_contracts.count(key) > 1
- })
- if duplicates:
- problems.append(f"OPTION_CONTRACTS duplicados: {duplicates}")
- malformed = sorted(
- key for key in option_contracts
- if key.count(":") != 1 or not key.split(":", 1)[0] or not key.split(":", 1)[1]
- )
- if malformed:
- problems.append(f"OPTION_CONTRACTS mal formados: {malformed}")
- public_commands = _public_route_names(_json(".claude-plugin/plugin.json"))
- aliases = getattr(manual_smoke, "_PUBLIC_COMMAND_ALIASES", {})
- unknown_prefixes = sorted({
- key.split(":", 1)[0]
- for key in option_contracts
- if key.count(":") == 1
- and key.split(":", 1)[0] not in public_commands
- and aliases.get(key.split(":", 1)[0]) not in public_commands
- })
- if unknown_prefixes:
- problems.append(f"OPTION_CONTRACTS con comandos no publicados: {unknown_prefixes}")
- from core import config_loader
- expected_config_options = {
- "config:exit-without-changes",
- *{
- f"config:{section.replace('_', '-')}"
- for section in config_loader._CONFIG_SECTION_ORDER
- },
- }
- actual_config_options = {
- key for key in option_contracts
- if key.startswith("config:")
- }
- missing_config_options = sorted(expected_config_options - actual_config_options)
- extra_config_options = sorted(actual_config_options - expected_config_options)
- if missing_config_options or extra_config_options:
- problems.append(
- "OPTION_CONTRACTS de /config desalineados: "
- f"missing={missing_config_options} extra={extra_config_options}"
- )
- expected_lucius_options = {
- "lucius:default-scope-all",
- "lucius:scope-all",
- "lucius:scope-security",
- "lucius:scope-tests",
- "lucius:scope-architecture",
- "lucius:scope-performance",
- "lucius:target-directory",
- "lucius:invalid-scope",
- }
- actual_lucius_options = {
- key for key in option_contracts
- if key.startswith("lucius:")
- }
- missing_lucius_options = sorted(expected_lucius_options - actual_lucius_options)
- extra_lucius_options = sorted(actual_lucius_options - expected_lucius_options)
- if missing_lucius_options or extra_lucius_options:
- problems.append(
- "OPTION_CONTRACTS de /lucius desalineados: "
- f"missing={missing_lucius_options} extra={extra_lucius_options}"
- )
- expected_human_menu_options = {
- "audit:sonarqube-docker-install-menu",
- "audit:sonarqube-docker-start-menu",
- "ship:deploy-confirmation-menu",
- "feature:user-gate-menu",
- "fix:user-gate-menu",
- "spike:conclusion-review-menu",
- "discuss:route-menu",
- "alfred:route-menu",
- "update:confirm-update-menu",
- }
- missing_human_menu_options = sorted(expected_human_menu_options - set(option_contracts))
- if missing_human_menu_options:
- problems.append(
- "OPTION_CONTRACTS sin menus humanos obligatorios: "
- f"{missing_human_menu_options}"
- )
- coverage_only = sorted(set(option_coverage) - set(option_contracts))
- if coverage_only:
- problems.append(f"option_coverage contiene claves fuera de OPTION_CONTRACTS: {coverage_only}")
- if problems:
- _fail("Contratos de opciones manuales invalidos: " + "; ".join(problems))
- def _validate_manual_runtime_contract_shape(manual_smoke, runtime_coverage: dict[str, list[str]]) -> None:
- """Valida que los contratos runtime describan scopes reales de /update."""
- runtime_contracts = tuple(manual_smoke.RUNTIME_CONTRACTS)
- problems: list[str] = []
- duplicates = sorted({
- key for key in runtime_contracts
- if runtime_contracts.count(key) > 1
- })
- if duplicates:
- problems.append(f"RUNTIME_CONTRACTS duplicados: {duplicates}")
- malformed = sorted(
- key for key in runtime_contracts
- if key.count(":") != 1 or not key.split(":", 1)[0] or not key.split(":", 1)[1]
- )
- if malformed:
- problems.append(f"RUNTIME_CONTRACTS mal formados: {malformed}")
- public_commands = _public_route_names(_json(".claude-plugin/plugin.json"))
- unknown_prefixes = sorted({
- key.split(":", 1)[0]
- for key in runtime_contracts
- if key.count(":") == 1 and key.split(":", 1)[0] not in public_commands
- })
- if unknown_prefixes:
- problems.append(f"RUNTIME_CONTRACTS con comandos no publicados: {unknown_prefixes}")
- expected_update_contracts = {
- "update:scope-user-or-unknown",
- "update:scope-local-to-user",
- "update:scope-project-to-user",
- "update:scope-managed",
- }
- actual_update_contracts = {
- key for key in runtime_contracts
- if key.startswith("update:")
- }
- missing_update = sorted(expected_update_contracts - actual_update_contracts)
- extra_update = sorted(actual_update_contracts - expected_update_contracts)
- if missing_update or extra_update:
- problems.append(
- "RUNTIME_CONTRACTS de /update desalineados: "
- f"missing={missing_update} extra={extra_update}"
- )
- coverage_only = sorted(set(runtime_coverage) - set(runtime_contracts))
- if coverage_only:
- problems.append(f"runtime_coverage contiene claves fuera de RUNTIME_CONTRACTS: {coverage_only}")
- if problems:
- _fail("Contratos runtime manuales invalidos: " + "; ".join(problems))
- def _validate_manual_case_contract_links(manual_smoke) -> None:
- """Asegura que cada contrato manual esté cubierto por un caso del comando correcto."""
- aliases = getattr(manual_smoke, "_PUBLIC_COMMAND_ALIASES", {})
- def _canon(name: str) -> str:
- return aliases.get(name, name)
- problems: list[str] = []
- for case in manual_smoke.CASES:
- case_commands = set(getattr(case, "commands", ()) or ())
- prompt = getattr(case, "prompt", "")
- prompt_commands = set(re.findall(r"/alfred-dev:([a-z0-9-]+)", prompt))
- if re.search(r"(?<!\S)/alfred(?:\s|$)", prompt):
- prompt_commands.add("alfred")
- mapped_case = {_canon(name) for name in case_commands}
- mapped_prompt = {_canon(name) for name in prompt_commands}
- if case_commands:
- missing_prompt_commands = sorted(mapped_case - mapped_prompt)
- extra_prompt_commands = sorted(mapped_prompt - mapped_case)
- if missing_prompt_commands:
- problems.append(
- f"{case.case_id}: prompt no invoca {missing_prompt_commands}"
- )
- if extra_prompt_commands:
- problems.append(
- f"{case.case_id}: prompt invoca comandos no declarados {extra_prompt_commands}"
- )
- elif prompt_commands:
- problems.append(
- f"{case.case_id}: prompt invoca comandos sin declarar {sorted(prompt_commands)}"
- )
- for key in getattr(case, "option_keys", ()) or ():
- command_name = key.split(":", 1)[0] if ":" in key else ""
- if _canon(command_name) not in mapped_case:
- problems.append(f"{case.case_id}: option {key} no corresponde a {sorted(case_commands)}")
- for key in getattr(case, "runtime_keys", ()) or ():
- command_name = key.split(":", 1)[0] if ":" in key else ""
- if _canon(command_name) not in mapped_case:
- problems.append(f"{case.case_id}: runtime {key} no corresponde a {sorted(case_commands)}")
- if problems:
- _fail("Contratos manuales enlazados al caso equivocado: " + "; ".join(problems))
- def _slash_command_names(text: str) -> list[str]:
- return re.findall(r"`/alfred-dev:([a-z0-9-]+)`", text)
- def _section_between(text: str, start: str, end: str) -> str:
- start_index = text.index(start)
- end_index = text.index(end, start_index)
- return text[start_index:end_index]
- def check_command_catalog() -> list[str]:
- plugin = _json(".claude-plugin/plugin.json")
- manifest_names = _command_names_from_manifest(plugin)
- manifest_set = set(manifest_names)
- architecture = _read("docs/architecture.md")
- alfred_text = _read("commands/alfred.md")
- unpublished = {"_composicion", "_docs_vivas", "next", "search"}
- disk_names = {
- path.stem
- for path in (ROOT / "commands").glob("*.md")
- if path.stem not in unpublished
- }
- problems: list[str] = []
- if manifest_set != disk_names:
- problems.append(
- "comandos publicados y commands/*.md no coinciden: "
- f"faltan={sorted(disk_names - manifest_set)} sobran={sorted(manifest_set - disk_names)}"
- )
- if "alfred" not in manifest_set:
- problems.append("falta el comando publico alfred")
- if "/alfred-dev:alfred" not in alfred_text and "/alfred" not in alfred_text:
- problems.append("commands/alfred.md debe describir la entrada contextual")
- if "18 comandos" not in architecture and "/alfred-dev:alfred" not in architecture:
- problems.append("docs/architecture.md debe mencionar 18 comandos o /alfred-dev:alfred")
- for relative_path, name in zip(plugin["commands"], manifest_names):
- text = _read(relative_path.lstrip("./"))
- if not text.startswith("---\n"):
- problems.append(f"{relative_path}: falta frontmatter")
- continue
- frontmatter = text.split("---", 2)[1]
- frontmatter_values = _frontmatter_top_level_values(text)
- unknown_fields = sorted(set(frontmatter_values) - COMMAND_SUPPORTED_FIELDS)
- if unknown_fields:
- problems.append(
- f"{relative_path}: campos de frontmatter no soportados {unknown_fields}"
- )
- if not re.search(r"(?m)^description:\s*['\"]?.+['\"]?\s*$", frontmatter):
- problems.append(f"{relative_path}: falta description en frontmatter")
- model = frontmatter_values.get("model")
- if model and not _is_supported_agent_model(model):
- problems.append(
- f"{relative_path}: usa modelo de comando no soportado por Claude Code actual: {model!r}"
- )
- for tools_field in ("allowed-tools", "disallowed-tools"):
- unknown_tools = sorted(
- tool_name
- for tool_name in _frontmatter_tool_rule_names(
- _frontmatter_field_rule_text(text, tools_field)
- )
- if not _is_known_permission_rule_name(tool_name)
- )
- if unknown_tools:
- problems.append(
- f"{relative_path}: {tools_field} declara herramientas desconocidas {unknown_tools}"
- )
- if f"/alfred-dev:{name}" not in text:
- problems.append(f"{relative_path}: no menciona su slash command")
- if problems:
- _fail("Catalogo de comandos desalineado: " + "; ".join(problems))
- return [
- "18 comandos namespaced alineados entre plugin.json y arquitectura",
- "commands/alfred.md publicado como entrada contextual",
- "frontmatter de comandos con description",
- "frontmatter de comandos compatible con Claude Code actual",
- "model de comandos validado contra Claude Code actual",
- ]
- def _frontmatter_block(text: str) -> str:
- if not text.startswith("---\n"):
- return ""
- parts = text.split("---", 2)
- return parts[1] if len(parts) >= 3 else ""
- def _frontmatter_top_level_fields(text: str) -> list[str]:
- fields: list[str] = []
- for line in _frontmatter_block(text).splitlines():
- match = re.match(r"^([A-Za-z][A-Za-z_-]*)\s*:", line)
- if match:
- fields.append(match.group(1))
- return fields
- def _frontmatter_top_level_values(text: str) -> dict[str, str]:
- values: dict[str, str] = {}
- for line in _frontmatter_block(text).splitlines():
- match = re.match(r"^([A-Za-z][A-Za-z_-]*)\s*:\s*(.*)$", line)
- if not match:
- continue
- key, value = match.groups()
- values[key] = value.strip().strip('"').strip("'")
- return values
- def _frontmatter_field_text(text: str, field: str) -> str:
- lines = _frontmatter_block(text).splitlines()
- for index, line in enumerate(lines):
- match = re.match(r"^([A-Za-z][A-Za-z_-]*)\s*:\s*(.*)$", line)
- if not match:
- continue
- key, value = match.groups()
- if key != field:
- continue
- stripped_value = value.strip()
- if stripped_value not in {"|", ">"}:
- return stripped_value.strip('"').strip("'")
- collected: list[str] = []
- for following in lines[index + 1:]:
- if re.match(r"^[A-Za-z][A-Za-z_-]*\s*:", following):
- break
- if following.startswith((" ", "\t")):
- collected.append(following.strip())
- return "\n".join(collected)
- return ""
- def _is_supported_agent_model(model: str) -> bool:
- return model in AGENT_MODEL_ALIASES or AGENT_MODEL_ID_RE.fullmatch(model) is not None
- def _frontmatter_tool_names(tools: str) -> set[str]:
- names: set[str] = set()
- for item in tools.split(","):
- name = item.strip()
- if not name:
- continue
- names.add(re.split(r"[\s(]", name, maxsplit=1)[0])
- return names
- def _frontmatter_tool_rule_names(rules: str) -> set[str]:
- return set(
- re.findall(r"(?:^|[\s,])([A-Za-z][A-Za-z0-9_]*)(?:\(|(?=$|[\s,]))", rules)
- )
- def _frontmatter_field_rule_text(text: str, field: str) -> str:
- """Devuelve reglas inline o de lista YAML simple para allowed/disallowed tools."""
- lines = _frontmatter_block(text).splitlines()
- values: list[str] = []
- collecting = False
- for line in lines:
- top_level = re.match(r"^([A-Za-z][A-Za-z_-]*)\s*:\s*(.*)$", line)
- if top_level:
- key, value = top_level.groups()
- collecting = key == field
- if collecting and value.strip():
- values.append(value.strip().strip("[]").strip('"').strip("'"))
- continue
- if collecting:
- list_item = re.match(r"^\s*-\s*(.+?)\s*$", line)
- if list_item:
- values.append(list_item.group(1))
- return " ".join(values)
- def _is_known_agent_tool_name(tool_name: str) -> bool:
- return tool_name in CLAUDE_TOOL_NAMES or tool_name.startswith("mcp__")
- def _is_known_permission_rule_name(tool_name: str) -> bool:
- return tool_name in CLAUDE_PERMISSION_RULE_NAMES or tool_name.startswith("mcp__")
- def check_command_execution_contracts() -> list[str]:
- """Verifica que cada comando publicado conserve su estrategia operativa."""
- plugin = _json(".claude-plugin/plugin.json")
- commands = {
- Path(relative_path).stem: _read(relative_path.lstrip("./"))
- for relative_path in plugin["commands"]
- }
- composition = _read("commands/_composicion.md")
- problems: list[str] = []
- for name, text in commands.items():
- frontmatter = _frontmatter_block(text)
- has_arguments = "$ARGUMENTS" in text
- has_hint = re.search(r"(?m)^argument-hint:\s*.+$", frontmatter) is not None
- if has_arguments and not has_hint:
- problems.append(f"{name}: usa $ARGUMENTS pero no declara argument-hint")
- if has_hint and not has_arguments:
- problems.append(f"{name}: declara argument-hint pero no inserta $ARGUMENTS")
- if re.search(r"`/alfred:[^`]*`|^/alfred:", text, re.MULTILINE):
- problems.append(f"{name}: contiene slash command legacy /alfred:")
- if re.search(r"\bTask\b", text):
- problems.append(f"{name}: contiene nomenclatura obsoleta Task")
- if re.search(r"\*\*GATE \(libre\):\*\*.*\bSe aprueba siempre\b", text):
- problems.append(
- f"{name}: gate libre promete aprobacion incondicional sin evidencia"
- )
- helper_contracts = {
- "alfred": [
- 'consume-prefetch "$PWD" --expected alfred',
- 'alfred-continuity.py next "$PWD" --json',
- "No ofrezcas un menú por defecto",
- ],
- "discuss": [
- 'consume-prefetch "$PWD" --expected discuss',
- 'alfred-continuity.py discuss "$PWD" --raw "$ARGUMENTS"',
- "respuesta final",
- "commands/_docs_vivas.md",
- ],
- "map-codebase": [
- 'consume-prefetch "$PWD" --expected map-codebase',
- 'alfred-continuity.py map-codebase "$PWD" --raw "$ARGUMENTS"',
- "NO inventes stack, entrypoints o riesgos",
- "commands/_docs_vivas.md",
- ],
- "memory-ui": [
- 'consume-prefetch "$PWD" --expected memory-ui',
- 'alfred-continuity.py memory-ui "$PWD" --raw "$ARGUMENTS"',
- "--stop",
- ],
- "next": [
- 'alfred-continuity.py next "$PWD" --json',
- "un único `AskUserQuestion` navegable",
- ],
- "pause": [
- 'alfred-continuity.py pause "$PWD"',
- "Primero ejecuta el helper determinista",
- "No la reenvuelvas con un segundo resumen",
- ],
- "progress": [
- 'alfred-continuity.py progress "$PWD"',
- "úsalo como respuesta final",
- "NO uses `AskUserQuestion`",
- ],
- "quick": [
- 'alfred-continuity.py quick "$PWD" --raw "$ARGUMENTS"',
- "`Write` ni `Edit`",
- "## Cierre canónico del comando",
- ],
- "search": [
- 'alfred-continuity.py search "$PWD" --raw "$ARGUMENTS"',
- "Si `$ARGUMENTS` está vacío, dilo claramente",
- ],
- "sync-github": [
- 'alfred-continuity.py sync-github "$PWD" --raw "$ARGUMENTS"',
- "Mantén la verdad local",
- ],
- "uat": [
- 'alfred-continuity.py verify "$PWD" --raw "$ARGUMENTS"',
- "NO marques una UAT como aprobada sin una indicación explícita",
- "NO añadas una segunda capa de resumen",
- ],
- "retomar": [
- 'alfred-continuity.py resume "$PWD"',
- "Primero ejecuta el helper determinista",
- ],
- }
- commands_for_contracts = dict(commands)
- commands_for_contracts["alfred"] = _read("commands/alfred.md")
- commands_for_contracts["next"] = _read("commands/next.md")
- commands_for_contracts["search"] = _read("commands/search.md")
- for name, needles in helper_contracts.items():
- text = commands_for_contracts[name]
- for needle in needles:
- if needle not in text:
- problems.append(f"{name}: falta contrato helper {needle!r}")
- flow_contracts = {
- "feature": [
- "Flujo de hasta 7 fases",
- "## HARD-GATES",
- "Maximo 5 intentos",
- "## Cierre canónico del comando",
- "siguiente paso esperado",
- "commands/_docs_vivas.md",
- "check-project-docs",
- ],
- "fix": [
- "Flujo de 3 fases",
- "test que reproduce el bug",
- "Maximo 5 intentos",
- "## Cierre canónico del comando",
- "bug/causa raíz en curso",
- "commands/_docs_vivas.md",
- ],
- "quick": [
- "Flujo ligero de 2 fases",
- "Cuándo quick deja de ser quick",
- "## Cierre canónico del comando",
- "/alfred-dev:uat",
- "commands/_docs_vivas.md",
- "cierre",
- ],
- "spike": [
- "Flujo de 2 fases",
- "Los spikes NO generan código de producción",
- "## Cierre canónico del comando",
- "ADR",
- "no implementar todavía",
- ],
- "ship": [
- "Flujo de 4 fases",
- "Gate de despliegue SIEMPRE interactiva",
- "NUNCA auto-apruebes un despliegue",
- "## Cierre canónico del comando",
- "commands/_docs_vivas.md",
- "hygiene",
- ],
- "audit": [
- "Preflight de SonarQube",
- "Lanza 4 agentes EN PARALELO",
- "No toca código, solo genera informes",
- "## Cierre canónico del comando",
- "commands/_docs_vivas.md",
- ],
- }
- for name, needles in flow_contracts.items():
- text = commands[name]
- for needle in needles:
- if needle not in text:
- problems.append(f"{name}: falta contrato de flujo {needle!r}")
- composition_reader_contracts = ("feature", "fix", "quick", "spike", "ship", "audit")
- for name in composition_reader_contracts:
- text = commands[name]
- for needle in (
- "${CLAUDE_PLUGIN_ROOT}/commands/_composicion.md",
- ):
- if needle not in text:
- problems.append(f"{name}: carga _composicion sin contrato de plugin: {needle!r}")
- docs_reader_contracts = ("feature", "fix", "quick", "spike", "ship", "audit")
- for name in docs_reader_contracts:
- text = commands[name]
- if "${CLAUDE_PLUGIN_ROOT}/commands/_docs_vivas.md" not in text:
- problems.append(
- f"{name}: carga _docs_vivas sin contrato de plugin: "
- "'${CLAUDE_PLUGIN_ROOT}/commands/_docs_vivas.md'"
- )
- autopilot_texts = {
- "_composicion": composition,
- "feature": commands["feature"],
- "fix": commands["fix"],
- "ship": commands["ship"],
- }
- for name, text in autopilot_texts.items():
- if '"autopilot": true' not in text:
- problems.append(f"{name}: no reconoce el flag canonico de estado autopilot")
- if '"modo": "autopilot"' not in text:
- problems.append(f"{name}: no conserva el alias legacy de estado autopilot")
- interactive_contracts = {
- "ajustes": [
- "principal navegable",
- "core/config_cli.py",
- "CONFIG_HEADLESS_MENU",
- "no llames `AskUserQuestion`",
- "vuelve cancelada",
- "build_config_section_summaries()",
- "build_config_section_menu()",
- "build_config_section_change_preview()",
- "update_config_section()",
- ],
- "lucius": [
- "Argumentos del usuario: $ARGUMENTS",
- "codex login",
- "scope=all",
- "No implementes ningún ítem",
- "siguiente paso verificable",
- ],
- "update": [
- "semver real",
- "0.10.0",
- "un único `AskUserQuestion`",
- "ejecutar **`/reload-plugins`**",
- "`/reload-plugins --force`",
- "entonces debe reiniciar",
- "## Cierre canónico del comando",
- ],
- }
- for name, needles in interactive_contracts.items():
- text = commands[name]
- for needle in needles:
- if needle not in text:
- problems.append(f"{name}: falta contrato interactivo {needle!r}")
- if problems:
- _fail("Contratos de ejecución de comandos incompletos: " + "; ".join(problems))
- return [
- "18 comandos namespaced preservan argumentos, prefijo y nomenclatura actual",
- "18 wrappers helper-first cubiertos",
- "6 flujos principales con cierre canónico",
- "_composicion se carga desde la instalación del plugin",
- "config/lucius/update con contratos interactivos verificables",
- "gates libres sin aprobacion incondicional",
- "autopilot por config/estado sin flag publico fantasma",
- ]
- def _registered_hook_script_count() -> int:
- hooks = _json("hooks/hooks.json").get("hooks", {})
- scripts: set[str] = set()
- for groups in hooks.values():
- for group in groups:
- for hook in group.get("hooks", []):
- args = hook.get("args", [])
- if not isinstance(args, list):
- continue
- for arg in args:
- if isinstance(arg, str) and arg.startswith("${CLAUDE_PLUGIN_ROOT}/hooks/"):
- scripts.add(Path(arg).name)
- return len(scripts)
- def check_public_claims() -> list[str]:
- """Mantiene los claims publicos alineados con inventario y docs actuales."""
- readme = _read("README.md")
- architecture = _read("docs/architecture.md")
- skills_doc = _read("docs/skills.md")
- help_command = _read("commands/alfred.md")
- alfred_agent = _read("agents/alfred.md")
- lucius_agent = _read("agents/lucius.md")
- agents_readme = _read("docs/agents/README.md")
- has_site = _has_site()
- personality = _read("docs/personality.md")
- changelog = _read("CHANGELOG.md")
- agent_count = len(list((ROOT / "agents").glob("*.md")))
- skill_count = len(list((ROOT / "skills").rglob("SKILL.md")))
- command_count = len(_json(".claude-plugin/plugin.json")["commands"])
- hook_script_count = _registered_hook_script_count()
- expected_counts = {
- "agents": (agent_count, 10),
- "skills": (skill_count, 11),
- "commands": (command_count, 18),
- "hooks": (hook_script_count, hook_script_count),
- }
- for label, (actual, expected) in expected_counts.items():
- if actual != expected:
- _fail(f"Inventario publico {label}={actual}, esperado {expected}")
- required = {
- "README.md": [
- "10 agentes",
- "11 skills",
- "quality gates",
- "https://code.claude.com/docs/en/overview",
- "Novedades en v0.7.0",
- ],
- "docs/skills.md": [
- "catalogo de 11 skills",
- "disable-model-invocation: true",
- "memory",
- "style-direction",
- ],
- "docs/architecture.md": [
- "18 comandos",
- "El manifiesto no declara la clave `agents`",
- ],
- "commands/alfred.md": [
- "Agent Teams",
- "/alfred-dev:feature",
- ],
- "agents/alfred.md": [
- "Alfred",
- ],
- "docs/agents/README.md": [
- "Claude Code los descubre directamente desde `agents/`",
- "el manifiesto `plugin.json` no declara una seccion `agents` manual",
- "quality gates verificables con evidencia",
- "El resultado no se promete determinista",
- "reduce variabilidad",
- ],
- "agents/lucius.md": [
- "No fuerces un modelo por tu cuenta",
- "Codex CLI (configuración local del usuario)",
- "codex exec",
- "--sandbox read-only",
- "--ephemeral",
- "--json",
- "--output-last-message",
- "codex_report",
- "codex_jsonl",
- "approval_policy",
- "status --porcelain=v1 -z",
- ],
- "CHANGELOG.md": [
- "displayName: \"Alfred Dev\"",
- "Alfred Dev (alfred-dev)",
- "namespace técnico",
- "42 opciones públicas",
- "4 contratos runtime de `/update`",
- ],
- "site/src/i18n/data.es.ts": [
- "displayName: \"Alfred Dev\"",
- "Alfred Dev (alfred-dev)",
- "namespace técnico",
- "Claude Code 2.1.183",
- "plugins, skills, hooks y MCP",
- "claude update",
- ],
- "site/src/i18n/data.en.ts": [
- "displayName: \"Alfred Dev\"",
- "Alfred Dev (alfred-dev)",
- "technical namespace",
- "Claude Code 2.1.183",
- "plugins, skills, hooks, and MCP",
- "claude update",
- "quality gates that require evidence before work can close",
- ],
- }
- sources = {
- "README.md": readme,
- "docs/skills.md": skills_doc,
- "docs/architecture.md": architecture,
- "commands/alfred.md": help_command,
- "agents/alfred.md": alfred_agent,
- "docs/agents/README.md": agents_readme,
- "agents/lucius.md": lucius_agent,
- "CHANGELOG.md": changelog,
- }
- if has_site:
- sources.update({
- "site/src/i18n/data.es.ts": _read("site/src/i18n/data.es.ts"),
- "site/src/i18n/data.en.ts": _read("site/src/i18n/data.en.ts"),
- })
- else:
- required = {
- path: needles
- for path, needles in required.items()
- if not path.startswith("site/")
- }
- missing: list[str] = []
- for path, needles in required.items():
- for needle in needles:
- if needle not in sources[path]:
- missing.append(f"{path}: {needle}")
- if missing:
- _fail(f"Claims publicos incompletos: {missing}")
- stale_exact = {
- "README.md": [
- "### Skills (60)",
- "### Hooks (12)",
- "### Core (6 modulos)",
- "### Core (6 módulos)",
- "GPT-5.4",
- "--autopilot",
- "keywords contextuales",
- "https://docs.anthropic.com/en/docs/claude-code",
- "quality gates infranqueables",
- "No hay excepciones, no hay modo de saltárselas",
- ],
- "docs/architecture.md": ["Agentes de nucleo** (9)", "se registran igualmente en `plugin.json`"],
- "docs/agents/README.md": [
- "tambien aparecen en `plugin.json`",
- "quality gates infranqueables",
- "El resultado es previsible y reproducible",
- "produce resultados consistentes porque no arrastra",
- ],
- "commands/alfred.md": ["GPT-5.4"],
- "agents/alfred.md": [
- "9 agentes de nucleo + 8 opcionales",
- "reglas infranqueables",
- "NUNCA se pueden saltar",
- ],
- "agents/lucius.md": ["GPT-5.4", "gpt-5.4"],
- "docs/personality.md": ["GPT-5.4"],
- "CHANGELOG.md": [
- "GPT-5.4",
- "gpt-5.4",
- "22 opciones/variantes",
- "`codex review`",
- "approval: never",
- "sin prompt de confirmación al usuario",
- "ejecuta el scanner end-to-end",
- "Quality gates infranqueables",
- ],
- "site/src/i18n/data.es.ts": [
- "6 módulos core",
- "GPT-5.4",
- "codex review",
- "approval: never",
- "--autopilot",
- "sin pedir confirmación al usuario",
- "Verificado end-to-end con Docker",
- "ejecuta el scanner end-to-end",
- "No hay requisito de versión mínima específica",
- "Cualquier versión de Claude Code",
- "Claude Code instalado.",
- ],
- "site/src/i18n/data.en.ts": [
- "6 core modules",
- "GPT-5.4",
- "modelo configurado por el usuario",
- "codex review",
- "approval: never",
- "--autopilot",
- "quality gates the workflow cannot skip",
- "without asking the user for confirmation",
- "Verified end-to-end with Docker",
- "runs the scanner end-to-end",
- "There is no specific minimum version requirement",
- "Any version of Claude Code",
- "Claude Code installed.",
- ],
- "site/src/components/BrutalistLandingPage.astro": [
- "GPT-5.4",
- "codex review",
- "Los quality gates son infranqueables",
- ],
- "hooks/session-start.sh": [
- "Las quality gates son infranqueables",
- ],
- "site/src/components/Footer.astro": ["https://docs.anthropic.com/en/docs/claude-code"],
- "docs/skills.md": [
- "garantizar que el resultado sea consistente, reproducible y de calidad profesional",
- "procedimiento verificable y reproducible",
- "garantizar que el software sea usable por todas las personas",
- ],
- "docs/flows.md": [
- "garantiza que cada linea de código tiene al menos un test",
- "garantiza que cada línea de código tiene al menos un test",
- ],
- "docs/agents/security-officer.md": [
- "garantizar que el software cumple con los estandares de seguridad",
- ],
- "agents/security-officer.md": [
- "garantiza que nada con vulnerabilidades conocidas llega a los usuarios",
- "bloqueantes absolutos. Sin excepciones",
- "seguridad infranqueable",
- ],
- }
- stale_sources = {
- "README.md": readme,
- "docs/skills.md": skills_doc,
- "docs/flows.md": _read("docs/flows.md"),
- "docs/agents/security-officer.md": _read("docs/agents/security-officer.md"),
- "agents/security-officer.md": _read("agents/security-officer.md"),
- "hooks/session-start.sh": _read("hooks/session-start.sh"),
- "docs/architecture.md": architecture,
- "commands/alfred.md": help_command,
- "agents/alfred.md": alfred_agent,
- "docs/agents/README.md": agents_readme,
- "agents/lucius.md": lucius_agent,
- "docs/personality.md": personality,
- "CHANGELOG.md": changelog,
- }
- if has_site:
- stale_sources.update({
- "site/src/i18n/data.es.ts": _read("site/src/i18n/data.es.ts"),
- "site/src/i18n/data.en.ts": _read("site/src/i18n/data.en.ts"),
- "site/src/components/BrutalistLandingPage.astro": _read("site/src/components/BrutalistLandingPage.astro"),
- "site/src/components/Footer.astro": _read("site/src/components/Footer.astro"),
- })
- else:
- stale_exact = {
- path: needles
- for path, needles in stale_exact.items()
- if not path.startswith("site/")
- }
- stale_hits: list[str] = []
- for path, needles in stale_exact.items():
- for needle in needles:
- if needle in stale_sources[path]:
- stale_hits.append(f"{path}: {needle}")
- if stale_hits:
- _fail(f"Claims obsoletos en superficie actual: {stale_hits}")
- manual_only_problems: list[str] = []
- for relative_path in MANUAL_ONLY_SKILLS:
- frontmatter = _frontmatter_block(_read(relative_path))
- if not re.search(r"(?m)^disable-model-invocation:\s*true\s*$", frontmatter):
- manual_only_problems.append(relative_path)
- if manual_only_problems:
- _fail(
- "Skills delicados sin activacion manual explicita: "
- f"{manual_only_problems}"
- )
- legacy_runtime: list[str] = []
- legacy_pattern = re.compile(r"/alfred\s+(feature|fix|ship|spike|audit|config)\b")
- for path in sorted((ROOT / "agents").glob("*.md")):
- text = path.read_text(encoding="utf-8")
- for match in legacy_pattern.finditer(text):
- legacy_runtime.append(f"{_rel(path)}:{match.group(0)}")
- if legacy_runtime:
- _fail(f"Prompts runtime con slash command legacy: {legacy_runtime}")
- surface_message = (
- "README, landing, arquitectura, help y agentes sin contadores antiguos"
- if has_site
- else "README, arquitectura, help y agentes sin contadores antiguos"
- )
- display_name_message = (
- "displayName humano reflejado en README, changelog y landing"
- if has_site
- else "displayName humano reflejado en README y changelog"
- )
- return [
- "inventario publico 10/11/18 verificado",
- surface_message,
- display_name_message,
- "skills delicados mantienen activacion manual explicita",
- "Lucius no fija modelo obsoleto de Codex CLI",
- "prompts runtime sin /alfred legacy",
- ]
- def check_config_contracts() -> list[str]:
- """Verifica que /alfred-dev:ajustes exponga las opciones reales del runtime."""
- from core import config_loader
- from core import optional_agents
- def assert_ask_user_question_payload(label: str, payload: dict) -> None:
- questions = payload.get("questions")
- if not isinstance(questions, list) or len(questions) != 1:
- _fail(f"{label} no expone questions[0] para AskUserQuestion: {payload}")
- question = questions[0]
- if not isinstance(question, dict):
- _fail(f"{label}.questions[0] no es objeto: {question}")
- for field in ("question", "header", "options", "multiSelect"):
- if field not in question:
- _fail(f"{label}.questions[0] no declara {field}")
- if question["multiSelect"] is not False:
- _fail(f"{label}.questions[0].multiSelect debe ser false")
- if question["question"] != payload.get("question"):
- _fail(f"{label}.questions[0].question no coincide con legacy question")
- if question["header"] != payload.get("header"):
- _fail(f"{label}.questions[0].header no coincide con legacy header")
- if question["options"] != payload.get("options"):
- _fail(f"{label}.questions[0].options no coincide con legacy options")
- for index, option in enumerate(question["options"]):
- if not isinstance(option, dict):
- _fail(f"{label}.questions[0].options[{index}] no es objeto")
- if not str(option.get("label", "")).strip():
- _fail(f"{label}.questions[0].options[{index}] no declara label")
- if not str(option.get("description", "")).strip():
- _fail(f"{label}.questions[0].options[{index}] no declara description")
- def assert_prompt_examples_use_current_ask_user_question_schema(
- relative_path: str,
- text: str,
- ) -> None:
- for match in re.finditer(r"AskUserQuestion\(\{(?P<body>.*?)^\}\)", text, re.DOTALL | re.MULTILINE):
- body = match.group("body")
- missing = [
- needle
- for needle in ("questions: [", "multiSelect: false", "options: [")
- if needle not in body
- ]
- if missing:
- _fail(
- "Ejemplo AskUserQuestion obsoleto en "
- f"{relative_path}: faltan {missing}"
- )
- expected_sections = (
- "autonomia",
- "proyecto",
- "agentes_opcionales",
- "memoria",
- "compliance",
- "integraciones",
- "personalidad",
- )
- if tuple(config_loader._CONFIG_SECTION_ORDER) != expected_sections:
- _fail(
- "Orden de secciones config desalineado: "
- f"{config_loader._CONFIG_SECTION_ORDER}"
- )
- labels = config_loader._CONFIG_SECTION_LABELS
- if set(labels) != set(expected_sections):
- _fail(f"Labels config desalineados: {sorted(labels)}")
- summaries = config_loader.build_config_section_summaries(config_loader.DEFAULT_CONFIG)
- summary_sections = tuple(section["section"] for section in summaries)
- if summary_sections != expected_sections:
- _fail(f"Summaries config desalineados: {summary_sections}")
- menu = config_loader.build_config_section_menu(config_loader.DEFAULT_CONFIG)
- menu_labels = [option["label"] for option in menu["options"]]
- if menu_labels[0] != "Salir sin cambios":
- _fail(f"Menu config sin salida inicial: {menu_labels}")
- missing_labels = [
- labels[section]
- for section in expected_sections
- if labels[section] not in menu_labels
- ]
- if missing_labels:
- _fail(f"Menu config no expone secciones: {missing_labels}")
- assert_ask_user_question_payload("build_config_section_menu", menu)
- for group_name in optional_agents.OPTIONAL_AGENT_GROUP_ORDER:
- assert_ask_user_question_payload(
- f"build_optional_agent_group_menu[{group_name}]",
- optional_agents.build_optional_agent_group_menu(group_name),
- )
- preview = config_loader.build_config_section_change_preview(
- config_loader.DEFAULT_CONFIG,
- "memoria",
- {"enabled": True},
- )
- if not preview["changed"] or not preview["updated_config"]["memoria"]["enabled"]:
- _fail(f"Preview config no detecta cambio de memoria: {preview}")
- section_updates = {
- "autonomia": {
- "producto": "interactivo",
- "calidad": "semi-autonomo",
- },
- "proyecto": {
- "runtime": "node",
- "lenguaje": "typescript",
- "framework": "next",
- "test_runner": "vitest",
- "bundler": "vite",
- },
- "agentes_opcionales": {
- "lucius": True,
- "lucius": True,
- },
- "memoria": {
- "enabled": True,
- "sync_commits_limit": 3,
- "retention_days": 30,
- },
- "compliance": {
- "estilo": "strict",
- "lint": False,
- "format_on_save": False,
- },
- "integraciones": {
- "git": False,
- "ci": True,
- "deploy": True,
- },
- "personalidad": {
- "nivel_sarcasmo": 1,
- "verbosidad": "alta",
- "idioma": "es-ES",
- "celebrar_victorias": False,
- },
- }
- if tuple(section_updates) != expected_sections:
- _fail(f"Matriz config desalineada: {tuple(section_updates)}")
- stack_fixtures = {
- "node-typescript": {
- "files": {
- "package.json": json.dumps({"dependencies": {"next": "^15.0.0"}}),
- "tsconfig.json": "{}",
- },
- "expected": {"runtime": "node", "lenguaje": "typescript", "framework": "next"},
- },
- "python": {
- "files": {"requirements.txt": "fastapi==0.110.0\npytest==8.0.0\n"},
- "expected": {"runtime": "python", "lenguaje": "python", "framework": "fastapi"},
- },
- "rust": {
- "files": {"Cargo.toml": "[package]\nname = \"demo\"\n"},
- "expected": {"runtime": "rust", "lenguaje": "rust"},
- },
- "go": {
- "files": {"go.mod": "module example.com/demo\n"},
- "expected": {"runtime": "go", "lenguaje": "go"},
- },
- "ruby": {
- "files": {"Gemfile": "source 'https://rubygems.org'\n"},
- "expected": {"runtime": "ruby", "lenguaje": "ruby"},
- },
- "elixir": {
- "files": {"mix.exs": "defmodule Demo.MixProject do\nend\n"},
- "expected": {"runtime": "elixir", "lenguaje": "elixir"},
- },
- "java": {
- "files": {
- "pom.xml": (
- "<project><dependencies>"
- "<dependency><groupId>org.springframework.boot</groupId>"
- "<artifactId>spring-boot-starter-web</artifactId></dependency>"
- "</dependencies></project>"
- ),
- },
- "expected": {"runtime": "jvm", "lenguaje": "java", "framework": "spring-boot"},
- },
- "kotlin": {
- "files": {
- "build.gradle.kts": (
- "plugins { kotlin(\"jvm\") version \"2.0.0\" }\n"
- "dependencies { implementation(\"io.quarkus:quarkus-rest\") }\n"
- ),
- },
- "expected": {"runtime": "jvm", "lenguaje": "kotlin", "framework": "quarkus"},
- },
- "php": {
- "files": {
- "composer.json": json.dumps({"require": {"laravel/framework": "^11.0"}}),
- },
- "expected": {"runtime": "php", "lenguaje": "php", "framework": "laravel"},
- },
- "dotnet": {
- "files": {"App.csproj": '<Project Sdk="Microsoft.NET.Sdk.Web"></Project>'},
- "expected": {"runtime": "dotnet", "lenguaje": "csharp", "framework": "aspnet"},
- },
- "swift": {
- "files": {
- "Package.swift": (
- "let package = Package("
- "dependencies: [.package(url: \"https://github.com/vapor/vapor\", from: \"4.0.0\")])"
- ),
- },
- "expected": {"runtime": "swift", "lenguaje": "swift", "framework": "vapor"},
- },
- }
- with tempfile.TemporaryDirectory(prefix="alfred-stack-audit-") as tmp:
- tmp_path = Path(tmp)
- for fixture_name, fixture in stack_fixtures.items():
- project_path = tmp_path / fixture_name
- project_path.mkdir()
- for relative_path, content in fixture["files"].items():
- target = project_path / relative_path
- target.parent.mkdir(parents=True, exist_ok=True)
- target.write_text(content, encoding="utf-8")
- stack = config_loader.detect_stack(str(project_path))
- for key, expected_value in fixture["expected"].items():
- actual = stack.get(key)
- if actual != expected_value:
- _fail(
- "Deteccion de stack prometido desalineada: "
- f"{fixture_name}.{key}={actual!r} != {expected_value!r}"
- )
- with tempfile.TemporaryDirectory(prefix="alfred-config-audit-") as tmp:
- config_path = Path(tmp) / "alfred-dev.local.md"
- config_path.write_text(
- "---\n"
- "memoria:\n"
- " enabled: false\n"
- "---\n\n"
- "## Notas\n\n"
- "Nota estable.\n",
- encoding="utf-8",
- )
- for section_name, values in section_updates.items():
- section_preview = config_loader.build_config_section_change_preview(
- config_loader.DEFAULT_CONFIG,
- section_name,
- values,
- )
- if not section_preview["changed"]:
- _fail(f"Preview config no detecta cambio en {section_name}: {section_preview}")
- for key, value in values.items():
- actual = section_preview["updated_config"][section_name].get(key)
- if actual != value:
- _fail(
- "Preview config no aplica valor "
- f"{section_name}.{key}: {actual!r} != {value!r}"
- )
- persisted_preview = config_loader.update_config_section(
- str(config_path),
- section_name,
- values,
- include_defaults=False,
- )
- if persisted_preview["section"] != section_name:
- _fail(
- "Persistencia config devuelve seccion incorrecta: "
- f"{persisted_preview}"
- )
- reloaded = config_loader.load_config(str(config_path))
- for key, value in values.items():
- actual = reloaded[section_name].get(key)
- if actual != value:
- _fail(
- "Persistencia config no conserva valor "
- f"{section_name}.{key}: {actual!r} != {value!r}"
- )
- if "Nota estable" not in reloaded.get("notas", ""):
- _fail(f"Persistencia config pierde notas tras {section_name}")
- command_norm = _normalize(_read("commands/ajustes.md"))
- docs_norm = _normalize(_read("docs/configuration.md"))
- architecture = _read("docs/architecture.md")
- assert_prompt_examples_use_current_ask_user_question_schema(
- "commands/ajustes.md",
- _read("commands/ajustes.md"),
- )
- assert_prompt_examples_use_current_ask_user_question_schema(
- "commands/_composicion.md",
- _read("commands/_composicion.md"),
- )
- required_human_labels = [
- "autonomia por fase",
- "proyecto",
- "agentes opcionales",
- "memoria persistente",
- "compliance",
- "integraciones",
- "personalidad",
- ]
- missing: list[str] = []
- for label in required_human_labels:
- if label not in command_norm:
- missing.append(f"commands/config.md: {label}")
- if label not in docs_norm:
- missing.append(f"docs/configuration.md: {label}")
- helper_names = [
- "build_config_section_summaries()",
- "build_config_section_menu()",
- "apply_config_section_update()",
- "build_config_section_change_preview()",
- "update_config_section()",
- "update_project_config_section()",
- ]
- for helper_name in helper_names:
- if helper_name not in _read("commands/ajustes.md"):
- missing.append(f"commands/config.md: {helper_name}")
- if helper_name not in _read("docs/configuration.md"):
- missing.append(f"docs/configuration.md: {helper_name}")
- if helper_name not in architecture:
- missing.append(f"docs/architecture.md: {helper_name}")
- for needle in ("questions[]", "multiselect: false"):
- if needle not in docs_norm:
- missing.append(f"docs/configuration.md: {needle}")
- if missing:
- _fail("Contratos config incompletos: " + "; ".join(missing))
- return [
- "7 secciones config alineadas con runtime",
- "deteccion automatica cubre stacks prometidos",
- "menu config principal expone salida y secciones canonicas",
- "preview config antes/despues operativo",
- "7 secciones config con round-trip preview/persistencia",
- "docs y comando config cubren helpers canonicos",
- "AskUserQuestion config/optional usa questions[] y multiSelect actuales",
- ]
- def check_flow_gate_claims() -> list[str]:
- """Ejercita claims publicos de flujos, Selina, gates y autopilot."""
- from core.config_loader import has_frontend
- from core.orchestrator import (
- FLOWS,
- advance_phase,
- check_gate,
- create_session,
- is_autopilot_gate_passable,
- )
- problems: list[str] = []
- flows_doc = _read("docs/flows.md")
- configuration_doc = _read("docs/configuration.md")
- readme = _read("README.md")
- has_site = _has_site()
- free_gate_doc_requirements = {
- "docs/flows.md": (
- "evidencia directa del artefacto o checklist esperado",
- "no la convierte en una aprobacion incondicional",
- "Docs completas, gate libre con evidencia",
- ),
- "docs/configuration.md": (
- "Requiere resultado favorable y evidencia/checklist; no pide aprobacion humana.",
- ),
- "README.md": (
- "Todos los artefactos están documentados con checklist/evidencia revisable",
- ),
- }
- free_gate_sources = {
- "docs/flows.md": flows_doc,
- "docs/configuration.md": configuration_doc,
- "README.md": readme,
- }
- for path, needles in free_gate_doc_requirements.items():
- for needle in needles:
- if needle not in free_gate_sources[path]:
- problems.append(f"{path}: gate libre/documentacion sin contrato honesto {needle!r}")
- stale_free_gate_claims = {
- "docs/flows.md": (
- "Se supera siempre que el resultado sea favorable.",
- "Avance automático con gate libre",
- ),
- "docs/configuration.md": (
- "Se supera siempre que el resultado sea favorable.",
- ),
- "README.md": (
- "Todos los artefactos están documentados |",
- ),
- }
- for path, needles in stale_free_gate_claims.items():
- for needle in needles:
- if needle in free_gate_sources[path]:
- problems.append(f"{path}: claim de gate libre demasiado laxo {needle!r}")
- public_gate_sources = {
- "README.md": readme,
- "docs/README.md": _read("docs/README.md"),
- "docs/agents/README.md": _read("docs/agents/README.md"),
- "docs/hooks.md": _read("docs/hooks.md"),
- "docs/release.md": _read("docs/release.md"),
- }
- public_gate_requirements = {
- "README.md": (
- "quality gates verificables",
- "Autopilot solo resuelve gates de usuario configuradas",
- "no salta tests, seguridad, evidencia ni confirmación humana de despliegue",
- ),
- "docs/README.md": ("quality gates verificables con evidencia",),
- "docs/agents/README.md": ("quality gates verificables con evidencia",),
- "docs/hooks.md": ("quality gates verificables con evidencia",),
- "docs/release.md": ("quality gates son verificables por contrato local",),
- }
- if has_site:
- public_gate_sources["site/src/i18n/data.en.ts"] = _read("site/src/i18n/data.en.ts")
- public_gate_requirements["site/src/i18n/data.en.ts"] = (
- "quality gates that require evidence before work can close",
- )
- for path, needles in public_gate_requirements.items():
- for needle in needles:
- if needle not in public_gate_sources[path]:
- problems.append(f"{path}: claim de gates sin evidencia verificable {needle!r}")
- public_gate_stale = {
- "README.md": (
- "quality gates infranqueables",
- "No hay excepciones, no hay modo de saltárselas",
- ),
- "docs/README.md": ("quality gates infranqueables",),
- "docs/agents/README.md": ("quality gates infranqueables",),
- "docs/hooks.md": ("quality gates infranqueables",),
- "docs/release.md": ("quality gates son infranqueables",),
- }
- if has_site:
- public_gate_stale["site/src/i18n/data.en.ts"] = ("quality gates the workflow cannot skip",)
- for path, needles in public_gate_stale.items():
- for needle in needles:
- if needle in public_gate_sources[path]:
- problems.append(f"{path}: claim absoluto de gate sin matiz de evidencia {needle!r}")
- feature_phases = FLOWS["feature"]["fases"]
- if len(feature_phases) != 7:
- problems.append(f"feature debe tener 7 fases, tiene {len(feature_phases)}")
- estilo = feature_phases[1] if len(feature_phases) > 1 else {}
- expected_style_contract = {
- "nombre": "estilo_visual",
- "agentes": ["selina"],
- "gate_tipo": "usuario",
- "condicion": "tiene_frontend",
- }
- for key, expected in expected_style_contract.items():
- if estilo.get(key) != expected:
- problems.append(f"estilo_visual.{key}={estilo.get(key)!r} != {expected!r}")
- if not has_frontend({"framework": "next", "runtime": "node"}):
- problems.append("has_frontend no reconoce Next como frontend")
- if has_frontend({"framework": "fastapi", "runtime": "python"}):
- problems.append("has_frontend trata FastAPI como frontend")
- frontend_session = create_session(
- "feature",
- "Panel con UI",
- stack={"runtime": "node", "framework": "next"},
- )
- frontend_session = advance_phase(frontend_session, resultado="aprobado")
- if frontend_session["fase_actual"] != "estilo_visual":
- problems.append("feature con frontend no entra en estilo_visual tras producto")
- backend_session = create_session(
- "feature",
- "API sin UI",
- stack={"runtime": "python", "framework": "fastapi"},
- )
- backend_session = advance_phase(backend_session, resultado="aprobado")
- skipped_style = [
- phase
- for phase in backend_session.get("fases_completadas", [])
- if phase.get("nombre") == "estilo_visual"
- ]
- if backend_session["fase_actual"] != "arquitectura" or not skipped_style:
- problems.append("feature sin frontend no salta estilo_visual hacia arquitectura")
- elif skipped_style[0].get("resultado") != "saltada":
- problems.append(f"estilo_visual saltada registra resultado inesperado: {skipped_style[0]}")
- gate_session = create_session("feature", "Gates estrictas")
- gate_session = advance_phase(gate_session, resultado="aprobado")
- gate_session = advance_phase(gate_session, resultado="aprobado")
- gate_session = advance_phase(gate_session, resultado="aprobado")
- if check_gate(gate_session, resultado="aprobado", tests_ok=False)["passed"]:
- problems.append("gate automatica de desarrollo no bloquea tests rojos")
- gate_session = advance_phase(gate_session, resultado="aprobado", tests_ok=True)
- if check_gate(gate_session, resultado="aprobado", security_ok=False)["passed"]:
- problems.append("gate automatico+seguridad de calidad no bloquea seguridad KO")
- autopilot_session = create_session("feature", "Autopilot")
- autopilot_session["autopilot"] = True
- if not is_autopilot_gate_passable(autopilot_session)["passed"]:
- problems.append("autopilot no aprueba gate de usuario")
- autopilot_session = advance_phase(autopilot_session, resultado="aprobado")
- autopilot_session = advance_phase(autopilot_session, resultado="aprobado")
- autopilot_session = advance_phase(autopilot_session, resultado="aprobado")
- if is_autopilot_gate_passable(autopilot_session, tests_ok=False)["passed"]:
- problems.append("autopilot salta gate automatica con tests rojos")
- ship_session = create_session("ship", "Release autopilot")
- ship_session["autopilot"] = True
- ship_session = advance_phase(ship_session, resultado="aprobado", tests_ok=True, security_ok=True)
- ship_session = advance_phase(ship_session, resultado="aprobado")
- ship_session = advance_phase(ship_session, resultado="aprobado", tests_ok=True, security_ok=True)
- ship_gate = is_autopilot_gate_passable(ship_session, security_ok=True)
- if ship_session["fase_actual"] != "despliegue":
- problems.append(f"ship no llega a despliegue en la fase esperada: {ship_session['fase_actual']}")
- if ship_gate["passed"] or "confirmación explícita del usuario" not in ship_gate.get("reason", ""):
- problems.append("ship autopilot no conserva confirmacion humana de despliegue")
- if problems:
- _fail("Claims de flujos/gates desalineados: " + "; ".join(problems))
- return [
- "feature mantiene 7 fases con Selina condicional",
- "Selina se ejecuta solo con frontend y se salta con backend",
- "gates libres documentadas como evidencia sin aprobacion humana",
- "gates automaticas bloquean tests rojos y seguridad KO",
- "autopilot no salta gates automaticas ni despliegue humano",
- ]
- def check_hook_contracts() -> list[str]:
- """Verifica que hooks.json siga el contrato moderno de Claude Code."""
- hooks_config = _json("hooks/hooks.json")
- hooks_by_event = hooks_config.get("hooks")
- if not isinstance(hooks_by_event, dict):
- _fail("hooks/hooks.json no declara hooks")
- expected_events = {
- "SessionStart",
- "SessionEnd",
- "UserPromptSubmit",
- "PreToolUse",
- "PostToolUse",
- }
- actual_events = set(hooks_by_event)
- if actual_events != expected_events:
- missing_events = sorted(expected_events - actual_events)
- extra_events = sorted(actual_events - expected_events)
- _fail(
- "Eventos de hooks desalineados: "
- f"actual={sorted(hooks_by_event)} missing={missing_events} extra={extra_events}"
- )
- visible_scripts = sorted(
- path.name
- for path in (ROOT / "hooks").iterdir()
- if path.is_file()
- and path.suffix in {".py", ".sh"}
- and path.name not in {"evidence_guard_lib.py", "secret-guard.sh"}
- )
- if len(visible_scripts) != 10:
- _fail(f"Hooks visibles inesperados: {visible_scripts}")
- registered: list[tuple[str, str, dict]] = []
- problems: list[str] = []
- for event, groups in hooks_by_event.items():
- if not isinstance(groups, list) or not groups:
- problems.append(f"{event}: debe contener grupos")
- continue
- for group in groups:
- if not isinstance(group, dict):
- problems.append(f"{event}: grupo no es objeto")
- continue
- if event in HOOK_EVENTS_WITHOUT_MATCHER and "matcher" in group:
- problems.append(
- f"{event}: declara matcher que Claude Code ignora en este evento"
- )
- for hook in group.get("hooks", []):
- if not isinstance(hook, dict) or hook.get("type") != "command":
- problems.append(f"{event}: hook no command")
- continue
- if "if" in hook:
- if event not in HOOK_EVENTS_WITH_IF_SUPPORT:
- problems.append(
- f"{event}: declara if que Claude Code no evalua en este evento"
- )
- elif not isinstance(hook["if"], str) or not hook["if"].strip():
- problems.append(f"{event}: if debe ser string no vacio")
- command = hook.get("command")
- args = hook.get("args")
- if not isinstance(command, str) or not command:
- problems.append(f"{event}: command invalido")
- continue
- if "|| true" in command or "test -f" in command:
- problems.append(f"{event}: command shell neutraliza errores: {command}")
- if "${CLAUDE_PLUGIN_ROOT}" in command:
- problems.append(f"{event}: usa placeholder en command en vez de args: {command}")
- if not isinstance(args, list) or len(args) != 1 or not isinstance(args[0], str):
- problems.append(f"{event}: hook sin args exec form para {command}")
- continue
- script_arg = args[0]
- prefix = "${CLAUDE_PLUGIN_ROOT}/hooks/"
- if not script_arg.startswith(prefix):
- problems.append(f"{event}: args no apunta a hooks/: {script_arg}")
- continue
- script_name = script_arg.removeprefix(prefix)
- script_path = ROOT / "hooks" / script_name
- if not script_path.is_file():
- problems.append(f"{event}: script no existe {script_name}")
- continue
- if script_name.endswith(".py") and command != "python3":
- problems.append(f"{script_name}: debe usar command python3")
- if script_name.endswith(".sh") and command != "bash":
- problems.append(f"{script_name}: debe usar command bash")
- if "async" in hook and not isinstance(hook["async"], bool):
- problems.append(f"{script_name}: async debe ser booleano")
- timeout = hook.get("timeout")
- if hook.get("async") is not True:
- if type(timeout) is not int:
- problems.append(f"{script_name}: hook sincronico sin timeout entero")
- elif timeout > HOOK_SYNC_TIMEOUT_LIMIT:
- problems.append(
- f"{script_name}: hook sincronico supera timeout "
- f"{HOOK_SYNC_TIMEOUT_LIMIT}s ({timeout}s)"
- )
- registered.append((event, script_name, hook))
- registered_names = {script_name for _, script_name, _ in registered}
- missing = sorted(set(visible_scripts) - registered_names)
- extras = sorted(registered_names - set(visible_scripts))
- if missing:
- problems.append(f"scripts sin registrar: {missing}")
- if extras:
- problems.append(f"scripts registrados inesperados: {extras}")
- blocking = {
- "secret-guard.py",
- "dangerous-command-guard.py",
- }
- for script_name in blocking:
- matches = [
- (event, hook)
- for event, registered_script, hook in registered
- if registered_script == script_name
- ]
- if not matches:
- problems.append(f"{script_name}: no registrado")
- continue
- for event, hook in matches:
- if event != "PreToolUse":
- problems.append(f"{script_name}: debe registrarse en PreToolUse, no {event}")
- if hook.get("async"):
- problems.append(f"{script_name}: no puede ser async")
- if hook.get("timeout", 99) > 5:
- problems.append(f"{script_name}: timeout debe ser <= 5")
- for path in sorted((ROOT / "hooks").glob("*.py")):
- source = path.read_text(encoding="utf-8")
- compile(source, str(path), "exec")
- for path in sorted((ROOT / "hooks").glob("*.sh")):
- result = subprocess.run(
- ["bash", "-n", str(path)],
- cwd=ROOT,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- check=False,
- )
- if result.returncode != 0:
- problems.append(f"{_rel(path)}: bash -n fallo: {result.stdout}")
- wrapper_needles = (
- "EMBEDDED_PLUGIN_ROOT",
- "CLAUDE_PLUGIN_ROOT",
- "ALFRED_DEV_PLUGIN_ROOT",
- "def _cache_candidates():",
- "core/continuity.py",
- )
- for script_name in ("session-bootstrap.sh",):
- source = _read(f"hooks/{script_name}")
- for needle in wrapper_needles:
- if needle not in source:
- problems.append(f"{script_name}: wrapper no contiene {needle}")
- hooks_doc = _read("docs/hooks.md")
- if '"decisión": "block"' in hooks_doc:
- problems.append("docs/hooks.md usa clave obsoleta \"decisión\" en vez de decision")
- nested_hook_output = re.findall(
- r"hookSpecificOutput\.(?:"
- r"SessionStart|UserPromptSubmit|UserPromptExpansion|Stop|PreToolUse|PreCompact|PostToolUse|"
- r"PostToolUseFailure|PostToolBatch|PermissionRequest|Notification|"
- r"Setup|SubagentStart"
- r")\.[A-Za-z]",
- hooks_doc,
- )
- if nested_hook_output:
- problems.append(
- "docs/hooks.md usa hookSpecificOutput anidado por evento: "
- f"{sorted(set(nested_hook_output))}"
- )
- for needle in (
- '"decision": "block"',
- "hookSpecificOutput.hookEventName",
- "hookSpecificOutput.additionalContext",
- "systemMessage",
- "Claude Code ignora `matcher`",
- "El campo `if` solo se evalua en eventos de herramientas",
- "`manual\\|auto` omitido para cubrir ambos",
- "Claude Code ignora cualquier JSON cuando el proceso sale con `2`",
- "no mezcles JSON de control con `exit 2`",
- ):
- if needle not in hooks_doc:
- problems.append(f"docs/hooks.md no documenta contrato moderno de hooks: {needle}")
- if "Los hooks sincronos no deben superar los 10 segundos" not in hooks_doc:
- problems.append("docs/hooks.md no documenta limite de timeout sincronico")
- direct_checks = [
- (
- "secret-guard invalid json",
- ["bash", str(ROOT / "hooks" / "secret-guard.sh")],
- "not-json",
- ),
- (
- "dangerous-command invalid json",
- [sys.executable, str(ROOT / "hooks" / "dangerous-command-guard.py")],
- "not-json",
- ),
- (
- "dangerous-command rm root",
- [sys.executable, str(ROOT / "hooks" / "dangerous-command-guard.py")],
- json.dumps(
- {
- "hook_event_name": "PreToolUse",
- "tool_name": "Bash",
- "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
- }
- ),
- ),
- ]
- for name, command, stdin in direct_checks:
- result = subprocess.run(
- command,
- cwd=ROOT,
- input=stdin,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=False,
- timeout=10,
- )
- if result.returncode != 2:
- problems.append(
- f"{name}: esperaba exit 2, obtuvo {result.returncode}; "
- f"stdout={result.stdout!r} stderr={result.stderr!r}"
- )
- if result.stdout:
- problems.append(
- f"{name}: un hook con exit 2 no debe emitir JSON/stdout "
- f"porque Claude Code lo ignora: {result.stdout!r}"
- )
- with tempfile.TemporaryDirectory() as tmpdir:
- project = Path(tmpdir)
- (project / ".claude").mkdir()
- (project / ".claude" / "alfred-prefetch.json").write_text(
- json.dumps(
- {
- "source_command": "alfred",
- "prefetched_command": "map-codebase",
- "response_text": "prefetch listo",
- "expires_at": "2999-01-01T00:00:00+00:00",
- }
- ),
- encoding="utf-8",
- )
- pass
- if problems:
- _fail("Contratos de hooks incompletos: " + "; ".join(problems))
- return [
- "10 hooks visibles registrados",
- "scripts de hooks declarados existen y cubren los 9 visibles",
- "exec form sin shell wrappers ni rutas sin comillas",
- "hooks bloqueantes conservan exit 2",
- "hooks con exit 2 no emiten JSON ignorado por Claude Code",
- "eventos SessionStart, SessionEnd, UserPromptSubmit, PreToolUse y PostToolUse",
- "eventos sin matcher no declaran matcher ignorado",
- "hooks no usan if fuera de eventos de herramienta",
- "hooks sincronos declaran timeout entero <= 10 segundos",
- "sintaxis de hooks validada",
- "wrapper helper-first resiliente a cache de plugin rotada",
- "docs de hooks usan decision/hookSpecificOutput actuales",
- ]
- def check_mcp_config() -> list[str]:
- mcp = _json(".mcp.json")
- server = mcp.get("mcpServers", {}).get("alfred-memory")
- if not isinstance(server, dict):
- _fail(".mcp.json no declara mcpServers.alfred-memory")
- if server.get("command") != "python3":
- _fail("alfred-memory debe arrancar con command python3 para que los instaladores puedan parchearlo")
- args = server.get("args")
- if not isinstance(args, list) or not args or "memory_server.py" not in str(args[0]):
- _fail("alfred-memory debe apuntar a mcp/memory_server.py")
- if "${CLAUDE_PLUGIN_ROOT}" not in str(args[0]):
- _fail("alfred-memory debe usar CLAUDE_PLUGIN_ROOT")
- return ["MCP raiz portable con memory_server.py"]
- def _npm_pack_dry_run_package() -> dict:
- completed = subprocess.run(
- ["npm", "pack", "--dry-run", "--json"],
- cwd=ROOT,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=30,
- check=False,
- )
- if completed.returncode != 0:
- _fail(f"npm pack --dry-run fallo: {completed.stderr.strip()}")
- try:
- payload = json.loads(completed.stdout)
- except json.JSONDecodeError as exc:
- _fail(f"npm pack no devolvio JSON valido: {exc}: {completed.stdout[:500]}")
- if not isinstance(payload, list) or not payload:
- _fail(f"npm pack devolvio payload inesperado: {payload!r}")
- package = payload[0]
- if not isinstance(package, dict):
- _fail(f"npm pack devolvio paquete inesperado: {package!r}")
- return package
- def _publishable_symlink_problems() -> list[str]:
- problems: list[str] = []
- root = ROOT.resolve()
- for root_name in PUBLISHABLE_SYMLINK_ROOTS:
- root_path = ROOT / root_name
- if not root_path.exists() and not root_path.is_symlink():
- continue
- candidates = [root_path]
- if root_path.is_dir() and not root_path.is_symlink():
- candidates.extend(root_path.rglob("*"))
- for path in candidates:
- if not path.is_symlink():
- continue
- try:
- target = path.resolve(strict=True)
- except FileNotFoundError:
- problems.append(f"{_rel(path)} es un symlink roto")
- continue
- try:
- target.relative_to(root)
- except ValueError:
- problems.append(
- f"{_rel(path)} es un symlink fuera del plugin: {os.readlink(path)!r}"
- )
- return problems
- def check_packaging_contracts() -> list[str]:
- """Verifica el paquete real que produciría npm antes de publicar."""
- package = _npm_pack_dry_run_package()
- if package.get("name") != "alfred-dev" or package.get("version") != VERSION:
- _fail(f"npm pack empaqueta identidad inesperada: {package}")
- packed_paths = {
- entry.get("path")
- for entry in package.get("files", [])
- if isinstance(entry, dict)
- }
- required_paths = {
- ".claude-plugin/plugin.json",
- ".claude-plugin/marketplace.json",
- ".mcp.json",
- "commands/_composicion.md",
- "commands/alfred.md",
- "agents/alfred.md",
- "hooks/hooks.json",
- "mcp/memory_server.py",
- "core/continuity.py",
- "scripts/release_audit.py",
- "visual/scripts/frame-template.html",
- "visual/scripts/helper.js",
- "visual/scripts/read-choice.py",
- "visual/scripts/server.cjs",
- "visual/scripts/start-server.sh",
- "visual/scripts/stop-server.sh",
- "visual/scripts/write-guided-style-options.py",
- "visual/scripts/write-style-demo-gallery.py",
- "visual/scripts/write-style-direction.py",
- "visual/scripts/write-style-options.py",
- "visual/scripts/write-style-selector.py",
- }
- required_paths.update(TEMPLATE_PATHS)
- missing_required = sorted(required_paths - packed_paths)
- if missing_required:
- _fail(f"npm pack no incluye artefactos criticos: {missing_required}")
- forbidden_prefixes = (
- ".alfred-dev/",
- ".claude/",
- ".crupier/",
- ".git/",
- ".pytest_cache/",
- "docs/manual-smoke",
- "node_modules/",
- "site/.astro/",
- "site/dist/",
- "site/node_modules/",
- "tests/",
- )
- forbidden_suffixes = (
- ".pyc",
- ".pyo",
- )
- leaked = sorted(
- path for path in packed_paths
- if path and (
- path.startswith(forbidden_prefixes)
- or any(part == "__pycache__" for part in path.split("/"))
- or path.endswith(forbidden_suffixes)
- )
- )
- if leaked:
- _fail(f"npm pack incluye artefactos locales o de test: {leaked[:20]}")
- symlink_problems = _publishable_symlink_problems()
- if symlink_problems:
- _fail("Symlinks publicables incompatibles con la cache de Claude: " + "; ".join(symlink_problems))
- manifest_command_paths = {
- path.lstrip("./")
- for path in _json(".claude-plugin/plugin.json")["commands"]
- }
- public_command_paths = [
- path for path in packed_paths
- if path in manifest_command_paths
- ]
- agent_paths = [
- path for path in packed_paths
- if path.startswith("agents/") and path.endswith(".md")
- ]
- skill_paths = [
- path for path in packed_paths
- if path.startswith("skills/") and path.endswith("/SKILL.md")
- ]
- template_paths = [
- path for path in packed_paths
- if path.startswith("templates/") and path.endswith(".md")
- ]
- if len(public_command_paths) != 18 or len(agent_paths) != 10 or len(skill_paths) != 11:
- _fail(
- "npm pack desalineado con inventario publico: "
- f"commands={len(public_command_paths)} agents={len(agent_paths)} skills={len(skill_paths)}"
- )
- if sorted(template_paths) != sorted(TEMPLATE_PATHS):
- _fail(
- "npm pack desalineado con templates de artefactos: "
- f"{sorted(template_paths)}"
- )
- return [
- f"npm pack dry-run {VERSION} valido",
- "paquete sin caches locales ni tests",
- "paquete sin .claude/.crupier ni evidencias manuales",
- "paquete sin symlinks publicables fuera del plugin",
- "paquete contiene 18 comandos namespaced, 10 agentes y 11 skills",
- "paquete contiene 8 templates de artefactos",
- "paquete contiene runtime visual de Selina",
- ]
- def check_published_secret_scan() -> list[str]:
- """Escanea el artefacto publicable para detectar secretos reales."""
- from core.secrets import find_secret_label
- package = _npm_pack_dry_run_package()
- packed_paths = {
- entry.get("path")
- for entry in package.get("files", [])
- if isinstance(entry, dict)
- }
- findings: list[str] = []
- for relative in sorted(path for path in packed_paths if isinstance(path, str)):
- path = ROOT / relative
- if not path.is_file():
- continue
- try:
- text = path.read_text(encoding="utf-8")
- except UnicodeDecodeError:
- continue
- label = find_secret_label(text)
- if label:
- findings.append(f"{relative}: {label}")
- if findings:
- _fail(
- "El paquete publicable contiene posibles secretos reales: "
- + "; ".join(findings[:20])
- )
- return ["paquete publicable sin patrones de secretos reales"]
- def check_install_update_contracts() -> list[str]:
- """Verifica instalación, desinstalación y update con scopes explícitos."""
- install_sh = _read("install.sh")
- install_ps1 = _read("install.ps1")
- uninstall_sh = _read("uninstall.sh")
- uninstall_ps1 = _read("uninstall.ps1")
- update_command = _read("commands/update.md")
- installation_docs = _read("docs/installation.md")
- requirements = {
- "install.sh": [
- 'claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope local',
- 'claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope project',
- 'claude plugin marketplace remove "${PLUGIN_NAME}" --scope local',
- 'claude plugin marketplace remove "${PLUGIN_NAME}" --scope project',
- 'claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope user',
- 'claude plugin marketplace remove "${PLUGIN_NAME}" --scope user',
- 'claude plugin marketplace add "${REPO}" --scope user',
- 'claude plugin install "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope user',
- "claude plugin list --json",
- "Instalacion global de usuario confirmada (--scope user)",
- "No se pisa ~/.claude/skills",
- 'HOOKS_JSON="${PLUGIN_ROOT}/hooks/hooks.json"',
- 'MCP_JSON="${PLUGIN_ROOT}/.mcp.json"',
- "/reload-plugins",
- "MCP/coste de cache",
- ],
- "install.ps1": [
- "claude plugin uninstall $PluginKey --scope local",
- "claude plugin uninstall $PluginKey --scope project",
- "claude plugin marketplace remove $PluginName --scope local",
- "claude plugin marketplace remove $PluginName --scope project",
- "claude plugin uninstall $pluginKey --scope user",
- "claude plugin marketplace remove $PluginName --scope user",
- "claude plugin marketplace add $Repo --scope user",
- "claude plugin install $pluginKey --scope user",
- "claude plugin list --json",
- "Instalacion global de usuario confirmada (--scope user)",
- "No se pisa ~/.claude/skills",
- 'Join-Path $PluginRoot "hooks/hooks.json"',
- 'Join-Path $PluginRoot ".mcp.json"',
- "/reload-plugins",
- "MCP/coste de cache",
- ],
- "uninstall.sh": [
- 'claude plugin uninstall "${PLUGIN_KEY}" --scope user',
- 'claude plugin marketplace remove "${PLUGIN_NAME}" --scope user',
- 'known_marketplaces.json',
- 'installed_plugins.json',
- 'enabledPlugins',
- "Alias global /alfred eliminado",
- "Shim de comando global /alfred eliminado",
- ],
- "uninstall.ps1": [
- "claude plugin uninstall $PluginKey --scope user",
- "claude plugin marketplace remove $PluginName --scope user",
- "known_marketplaces.json",
- "installed_plugins.json",
- "enabledPlugins",
- "Alias global /alfred eliminado",
- "Shim de comando global /alfred eliminado",
- ],
- "commands/update.md": [
- "claude plugin list --json",
- "semver real",
- "un único `AskUserQuestion`",
- "Actualizar ahora",
- "Ahora no",
- "normaliza a `--scope user`",
- "no pisa `~/.claude/skills`",
- "No uses `claude plugin update --scope local`",
- "`claude plugin update --scope project`",
- "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 2,707 on GitHub
- "ejecutar **`/reload-plugins`**",
- "`/reload-plugins --force`",
- "entonces debe reiniciar",
- ],
- "docs/installation.md": [
- "--scope user",
- "instalación global de usuario",
- "No pisa",
- "~/.claude/commands/alfred.md",
- "claude plugin list --json",
- "No usa un marketplace oficial de Anthropic",
- "`/reload-plugins` aplica los cambios",
- "`/reload-plugins --force`",
- ],
- }
- sources = {
- "install.sh": install_sh,
- "install.ps1": install_ps1,
- "uninstall.sh": uninstall_sh,
- "uninstall.ps1": uninstall_ps1,
- "commands/update.md": update_command,
- "docs/installation.md": installation_docs,
- }
- missing = []
- for path, needles in requirements.items():
- for needle in needles:
- if needle not in sources[path]:
- missing.append(f"{path}: {needle}")
- if missing:
- _fail("Contratos install/update incompletos: " + "; ".join(missing))
- stateful_plugin_command = re.compile(
- r"\bclaude plugin "
- r"(?:(?:marketplace\s+(?:add|remove))|(?:install|uninstall|update))\b"
- )
- bad_scope = []
- for path in ("install.sh", "install.ps1", "uninstall.sh", "uninstall.ps1"):
- for line_number, line in enumerate(sources[path].splitlines(), start=1):
- stripped = line.strip()
- if not stripped or stripped.startswith("#"):
- continue
- if not stateful_plugin_command.search(stripped):
- continue
- scope_match = re.search(r"--scope\s+([A-Za-z_$\{\}]+)", stripped)
- if not scope_match:
- bad_scope.append(f"{path}:{line_number}: {stripped}")
- continue
- scope = scope_match.group(1).strip("${}").lstrip("$")
- if scope == "user":
- continue
- is_cleanup = (
- path in {"install.sh", "install.ps1"}
- and scope in {"local", "project"}
- and (
- "plugin uninstall" in stripped
- or "plugin marketplace remove" in stripped
- )
- )
- if not is_cleanup:
- bad_scope.append(f"{path}:{line_number}: scope {scope} prohibido")
- if bad_scope:
- _fail(
- "CLI plugin sin scope explicito user o limpieza local/project permitida: "
- + "; ".join(bad_scope)
- )
- if "instalación local que limpiar" in uninstall_sh:
- _fail("uninstall.sh no debe describir Alfred Dev como instalacion local")
- return [
- "instaladores usan scope user explicito",
- "instaladores verifican scope user despues de instalar",
- "instaladores limpian scopes local/project heredados antes de instalar user",
- "instaladores no pisan ~/.claude/skills ni instalan alias global /alfred",
- "update conserva semver y menu humano, normaliza a scope user y documenta reload/reinicio",
- ]
- def check_audit_docs() -> list[str]:
- package = _json("package.json")
- readme = _read("README.md")
- docs_readme = _read("docs/README.md")
- architecture = _read("docs/architecture.md")
- install = _read("docs/installation.md")
- release_doc = _read("docs/release.md")
- gitignore = _read(".gitignore")
- npmignore = _read(".npmignore")
- required = {
- "README.md": [
- "Novedades en v0.7.0",
- "docs/release.md",
- "MCP stdio moderno",
- ],
- "docs/README.md": [
- "release.md",
- "11 skills",
- "18 comandos",
- ],
- "docs/installation.md": [
- "plugin:alfred-dev:alfred-memory",
- "Pending approval",
- "No hay que aprobar esa entrada de proyecto",
- 'claude plugin marketplace add "$PWD" --scope user',
- "Claude Code actual sí ofrece diagnósticos útiles",
- "claude plugin details alfred-dev@alfred-dev",
- "claude plugin validate . --strict",
- "claude --debug",
- "/plugin validate",
- ],
- "docs/architecture.md": [
- "`matcher` es opcional",
- "solo se declara en eventos donde Claude Code lo soporta",
- "Claude Code lo ignora",
- "PreCompact",
- "manuales como automáticas",
- ],
- "docs/release.md": [
- "18 comandos",
- "10 agentes",
- "11 skills",
- "10 hooks",
- "displayName: \"Alfred Dev\"",
- "namespace técnico es `alfred-dev`",
- "no pisa `~/.claude/skills`",
- "`_composicion.md`",
- "`_docs_vivas.md`",
- "commands/ como skills planas soportadas",
- "UX pública",
- "`/alfred-dev:*`",
- "argument-hint",
- "$ARGUMENTS",
- "1.536 caracteres",
- "disable-model-invocation: true",
- "npm run release:audit",
- "npm run release:audit:manual",
- "npm run release:audit:manual:evidence",
- "npm run release:audit:prepublish",
- "18 rutas publicas",
- "40 opciones publicas",
- "4 contratos runtime",
- "--auth-preflight",
- "core/secrets.py",
- "permisos `0600`",
- "evidence_file",
- "evidence_sha256",
- "plugin_surface.sha256",
- "notes_low_quality",
- "notes_repeated",
- "--require-current-auth-preflight",
- "auth_preflight.status=ok",
- "scripts/manual_smoke.py",
- "scripts/external_live_smoke.py",
- "no crea issues, no arranca contenedores",
- "quality gates son verificables por contrato local",
- "questions[]",
- "multiSelect",
- "hookSpecificOutput.additionalContext",
- "No aprueba la release por sí mismo",
- "Pendientes que no cubre el contrato local",
- "claude auth login",
- "scripts/claude_auth_recovery.py",
- ],
- }
- sources = {
- "README.md": readme,
- "docs/README.md": docs_readme,
- "docs/architecture.md": architecture,
- "docs/installation.md": install,
- "docs/release.md": release_doc,
- }
- missing = []
- for path, needles in required.items():
- for needle in needles:
- if needle not in sources[path]:
- missing.append(f"{path}: {needle}")
- if re.search(r"PreCompact[^.\n]*(?:ignora|ignorado)", architecture):
- _fail("docs/architecture.md afirma incorrectamente que PreCompact ignora matcher")
- if 'displayName: "Alfred Dev"' not in release_doc:
- _fail("docs/release.md debe documentar displayName humano")
- if re.search(r"plugin_surface\.sha256=[0-9a-f]{64}", release_doc):
- _fail("docs/release.md no debe congelar plugin_surface.sha256")
- if "docs/manual-smoke*.json" not in gitignore:
- _fail(".gitignore debe excluir evidencias/reviews manuales docs/manual-smoke*.json")
- if "docs/manual-smoke*.json" not in npmignore:
- _fail(".npmignore debe excluir evidencias/reviews manuales docs/manual-smoke*.json")
- if "docs/manual-smoke*.md" not in gitignore:
- _fail(".gitignore debe excluir reportes manuales docs/manual-smoke*.md")
- if "docs/manual-smoke*.md" not in npmignore:
- _fail(".npmignore debe excluir reportes manuales docs/manual-smoke*.md")
- if "docs/project/" not in gitignore:
- _fail(".gitignore debe excluir estado operativo local docs/project/")
- if "docs/project/" not in npmignore:
- _fail(".npmignore debe excluir estado operativo local docs/project/")
- if "docs/external-live-smoke*.json" not in gitignore:
- _fail(".gitignore debe excluir evidencias externas docs/external-live-smoke*.json")
- if "docs/external-live-smoke*.json" not in npmignore:
- _fail(".npmignore debe excluir evidencias externas docs/external-live-smoke*.json")
- if "docs/claude-auth-recovery*.json" not in gitignore:
- _fail(".gitignore debe excluir diagnosticos de auth docs/claude-auth-recovery*.json")
- if "docs/claude-auth-recovery*.json" not in npmignore:
- _fail(".npmignore debe excluir diagnosticos de auth docs/claude-auth-recovery*.json")
- if missing:
- _fail(f"Documentacion de auditoria incompleta: {missing}")
- scripts = package.get("scripts", {})
- expected_scripts = {
- "release:audit:external:preflight": (
- "python3 scripts/external_live_smoke.py --output docs/external-live-smoke-0.7.0.json"
- ),
- "release:audit:claude:commands": "python3 scripts/claude_command_discovery.py",
- "release:audit:manual": "python3 scripts/manual_smoke.py",
- "release:audit:manual:evidence": (
- "python3 scripts/manual_smoke.py --auth-preflight --output docs/manual-smoke-0.7.0.json"
- ),
- "release:audit:manual:evidence:installed": (
- "python3 scripts/manual_smoke.py --installed --auth-preflight --output docs/manual-smoke-installed-0.7.0.json"
- ),
- "release:audit:manual:preflight": "python3 scripts/manual_smoke.py --auth-preflight --preflight-only",
- "release:audit:manual:preflight:diagnose": (
- "python3 scripts/manual_smoke.py --auth-preflight --preflight-only --allow-auth-failure"
- ),
- "release:audit:manual:auth:diagnose": "python3 scripts/claude_auth_recovery.py",
- "release:audit:manual:auth:strict": "python3 scripts/claude_auth_recovery.py --strict",
- "release:audit:manual:review:init": (
- "python3 scripts/manual_review_gate.py --init-template docs/manual-smoke-0.7.0.json docs/manual-smoke-review-0.7.0.json"
- ),
- "release:audit:manual:review": (
- "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"
- ),
- "release:audit:manual:report": (
- "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"
- ),
- "release:audit:manual:review:installed:init": (
- "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"
- ),
- "release:audit:manual:review:installed": (
- "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"
- ),
- "release:audit:manual:report:installed": (
- "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"
- ),
- "release:audit:prepublish:prepare": (
- "npm run release:audit:full && "
- "npm run release:audit:manual:evidence && "
- "npm run release:audit:manual:evidence:installed"
- ),
- "release:audit:prepublish": (
- "npm run release:audit:full && "
- "npm run release:audit:manual:preflight && "
- "npm run release:audit:manual:review && "
- "npm run release:audit:manual:review:installed"
- ),
- }
- bad_scripts = {
- name: {"actual": scripts.get(name), "expected": expected}
- for name, expected in expected_scripts.items()
- if scripts.get(name) != expected
- }
- if bad_scripts:
- _fail(f"Scripts npm de smoke manual desalineados: {bad_scripts}")
- if not (ROOT / "scripts" / "manual_smoke.py").is_file():
- _fail("Falta scripts/manual_smoke.py para reproducir la matriz manual")
- if not (ROOT / "scripts" / "manual_review_gate.py").is_file():
- _fail("Falta scripts/manual_review_gate.py para validar la revision humana")
- if not (ROOT / "scripts" / "external_live_smoke.py").is_file():
- _fail("Falta scripts/external_live_smoke.py para capturar preflight externo")
- if not (ROOT / "scripts" / "claude_command_discovery.py").is_file():
- _fail("Falta scripts/claude_command_discovery.py para probar /alfred-dev:alfred interactivo")
- if not (ROOT / "docs" / "release.md").is_file():
- _fail("Falta docs/release.md para auditar claims y readiness de salida")
- prepare = scripts.get("release:audit:prepublish:prepare", "")
- required_prepare_parts = (
- "npm run release:audit:full",
- "npm run release:audit:manual:evidence",
- "npm run release:audit:manual:evidence:installed",
- )
- missing_prepare = [
- part for part in required_prepare_parts if part not in prepare
- ]
- if missing_prepare:
- _fail(f"release:audit:prepublish:prepare incompleto: {missing_prepare}")
- prepublish = scripts.get("release:audit:prepublish", "")
- required_prepublish_parts = (
- "npm run release:audit:full",
- "npm run release:audit:manual:preflight",
- "npm run release:audit:manual:review",
- "npm run release:audit:manual:review:installed",
- )
- missing_prepublish = [
- part for part in required_prepublish_parts if part not in prepublish
- ]
- if missing_prepublish:
- _fail(f"release:audit:prepublish incompleto: {missing_prepublish}")
- prepublish_parts = {part.strip() for part in prepublish.split("&&")}
- forbidden_prepublish_parts = {
- "npm run release:audit:manual:evidence",
- "npm run release:audit:manual:evidence:installed",
- }
- forbidden_present = sorted(prepublish_parts & forbidden_prepublish_parts)
- if forbidden_present:
- _fail(
- "release:audit:prepublish no debe regenerar evidencias ya revisadas: "
- f"{forbidden_present}"
- )
- spec = importlib.util.spec_from_file_location(
- "manual_smoke_release_audit",
- ROOT / "scripts" / "manual_smoke.py",
- )
- if spec is None or spec.loader is None:
- _fail("No se pudo cargar scripts/manual_smoke.py para auditar cobertura")
- manual_smoke = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(manual_smoke)
- if "plugin_surface.sha256" not in release_doc:
- _fail("docs/release.md debe exigir plugin_surface.sha256 de la run, no un hash congelado")
- manual_smoke_text = _read("scripts/manual_smoke.py")
- manual_review_gate_text = _read("scripts/manual_review_gate.py")
- manual_review_report_text = _read("scripts/manual_review_report.py")
- manual_smoke_runtime_needles = (
- '"--permission-mode",',
- '"bypassPermissions",',
- 'parser.add_argument("--budget", default="1.50"',
- 'parser.add_argument(\n "--preflight-only"',
- 'if args.preflight_only:',
- 'error_max_budget_usd',
- )
- missing_manual_smoke_runtime = [
- needle for needle in manual_smoke_runtime_needles if needle not in manual_smoke_text
- ]
- if missing_manual_smoke_runtime:
- _fail(
- "El smoke manual debe reproducir claude -p real sin permisos interactivos ni presupuesto bajo: "
- f"{missing_manual_smoke_runtime}"
- )
- preview_sanitizer_needles = (
- "from core.secrets import sanitize_text",
- "def _safe_preview(",
- "path.chmod(0o600)",
- "previews[relative] = _safe_preview(",
- '"response_preview": _safe_preview(response_text, 2000)',
- '"stderr_preview": _safe_preview(result.stderr, 2000)',
- '"response_preview": _safe_preview(response_text, 500)',
- '"stderr_preview": _safe_preview(result.stderr, 500)',
- )
- missing_preview_sanitizer = [
- needle for needle in preview_sanitizer_needles if needle not in manual_smoke_text
- ]
- if missing_preview_sanitizer:
- _fail(
- "La evidencia manual debe sanear previews con core/secrets.py: "
- f"{missing_preview_sanitizer}"
- )
- review_secret_gate_needles = (
- "from core.secrets import find_secret_label",
- "def _iter_secret_findings(",
- "evidence_secret_findings = _iter_secret_findings(evidence, \"evidence\")",
- "review_secret_findings = _iter_secret_findings(review, \"review\")",
- "evidence contiene posibles secretos reales",
- "review contiene posibles secretos reales",
- "No se crea plantilla de revisión con evidencia que contiene",
- "review_path.chmod(0o600)",
- "GENERIC_REVIEW_NOTES",
- "MIN_REVIEW_NOTE_CHARS",
- "MIN_REVIEW_NOTE_WORDS",
- "def _is_low_quality_review_note(",
- "review.cases con notes humanas demasiado genericas o cortas",
- "review.cases contiene notes humanas repetidas",
- "--require-current-auth-preflight",
- "preflight actual de Claude CLI no esta ok",
- )
- missing_review_secret_gate = [
- needle for needle in review_secret_gate_needles if needle not in manual_review_gate_text
- ]
- if missing_review_secret_gate:
- _fail(
- "El gate de revision manual debe rechazar secretos con core/secrets.py: "
- f"{missing_review_secret_gate}"
- )
- review_report_note_needles = (
- "def _plugin_surface_flags(",
- "## Superficie Del Plugin",
- "evidence.plugin_surface.roots no coincide con el plugin actual",
- "evidence.plugin_surface.file_count no coincide con el plugin actual",
- "evidence.plugin_surface.sha256 no coincide con el plugin actual",
- "def _review_quality_flags(",
- "_manual_review_gate_module()",
- "## Calidad De Review Humana",
- "notes_missing",
- "notes_low_quality",
- "notes_repeated",
- "review_secret_findings",
- "Sin flags automaticos de notas humanas",
- )
- missing_review_report_notes = [
- needle
- for needle in review_report_note_needles
- if needle not in manual_review_report_text
- ]
- if missing_review_report_notes:
- _fail(
- "El reporte de revision manual debe mostrar notas humanas debiles o repetidas: "
- f"{missing_review_report_notes}"
- )
- review_traceability_needles = (
- "review.evidence_file es obligatorio",
- "review.evidence_file no coincide con el evidence pasado al gate",
- "review.evidence_file coincide",
- "review.cases desalineados con matriz actual",
- "review.cases coincide con la matriz manual actual",
- )
- missing_review_traceability = [
- needle
- for needle in review_traceability_needles
- if needle not in manual_review_gate_text
- ]
- if missing_review_traceability:
- _fail(
- "El gate de revision manual debe atar evidence_file a la evidencia validada: "
- f"{missing_review_traceability}"
- )
- _validate_manual_case_contract_links(manual_smoke)
- coverage = manual_smoke._case_command_coverage()
- missing = [name for name, case_ids in coverage.items() if not case_ids]
- if len(coverage) != 18 or missing:
- _fail(f"La matriz manual no cubre las 18 rutas publicas: missing={missing}")
- option_coverage = manual_smoke._case_option_coverage()
- missing_options = [
- name for name, case_ids in option_coverage.items()
- if not case_ids
- ]
- expected_option_contracts = len(manual_smoke.OPTION_CONTRACTS)
- if len(option_coverage) != expected_option_contracts or missing_options:
- _fail(
- "La matriz manual no cubre las opciones publicas: "
- f"total={len(option_coverage)} missing={missing_options}"
- )
- _validate_manual_option_contract_shape(manual_smoke, option_coverage)
- aliases = getattr(manual_smoke, "_PUBLIC_COMMAND_ALIASES", {})
- covered_option_commands = set()
- for name, case_ids in option_coverage.items():
- if not case_ids:
- continue
- prefix = name.split(":", 1)[0]
- covered_option_commands.add(prefix)
- mapped = aliases.get(prefix)
- if mapped:
- covered_option_commands.add(mapped)
- argument_commands = _public_argument_commands()
- missing_argument_commands = sorted(argument_commands - covered_option_commands)
- if missing_argument_commands:
- _fail(
- "Comandos con argument-hint/$ARGUMENTS sin contrato de opcion manual: "
- f"{missing_argument_commands}"
- )
- runtime_coverage = manual_smoke._case_runtime_coverage()
- missing_runtime = [
- name for name, case_ids in runtime_coverage.items()
- if not case_ids
- ]
- _validate_manual_runtime_contract_shape(manual_smoke, runtime_coverage)
- if len(runtime_coverage) != 4 or missing_runtime:
- _fail(
- "La matriz manual no cubre los contratos runtime: "
- f"total={len(runtime_coverage)} missing={missing_runtime}"
- )
- return [
- "docs/release.md es la pagina viva de auditoria",
- "nota project-scope MCP documentada",
- "commands/ documentado como skills planas soportadas",
- "matriz manual cubre 18 rutas publicas",
- f"matriz manual cubre {expected_option_contracts} opciones publicas",
- "matriz manual valida IDs de opcion contra comandos publicos",
- "matriz manual enlaza contratos al comando correcto",
- "matriz manual valida prompts contra comandos declarados",
- "matriz manual ata cada argument-hint a una opcion cubierta",
- "matriz manual valida contratos runtime de update",
- "matriz manual cubre 4 contratos runtime",
- "manual smoke usa worktree por defecto y --installed explicito",
- "manual smoke tiene preflight de autenticacion real y evidencia fail-fast",
- "evidencia manual y plantillas se escriben con permisos 0600",
- "evidencias manuales ignoradas por git y npm",
- "estado operativo docs/project ignorado por git y npm",
- "evidencia manual sanea previews con core/secrets.py",
- "manual review gate exige aprobacion humana explicita",
- "manual review gate rechaza evidencia/review con secretos",
- "manual review gate no crea plantillas desde evidencia con secretos",
- "manual review gate exige preflight actual antes de aprobar",
- "manual review report muestra notas humanas debiles o repetidas",
- "manual review gate exige origen worktree/installed correcto",
- "manual review gate ata evidence_file al JSON validado",
- "plugin_surface.sha256 se exige en revision humana, no se congela en docs",
- "manual review gate valida metadatos de casos contra matriz actual",
- "manual review gate valida metadatos de review contra matriz actual",
- "manual review gate valida mapas de cobertura contra matriz actual",
- "scripts npm manual/preflight alineados",
- "prepublish:prepare genera evidencias manuales antes de la revision humana",
- "prepublish valida evidencias manuales ya revisadas sin regenerarlas",
- "matriz documenta empaquetado seco",
- "plugin details documenta displayName humano",
- "docs oficiales revalidadas 2026-08-15",
- "readiness de salida mantiene pendientes humanos y externos",
- "runbook de revision humana documenta criterios y bloqueos",
- ]
- def check_human_contracts() -> list[str]:
- """Verifica contratos prompt-level de trato humano y honestidad operativa."""
- command_names = [
- "_composicion",
- "alfred",
- "ajustes",
- "discuss",
- "feature",
- "fix",
- "map-codebase",
- "memory-ui",
- "next",
- "pause",
- "progress",
- "quick",
- "retomar",
- "search",
- "ship",
- "sync-github",
- "uat",
- "update",
- ]
- commands = {name: _read(f"commands/{name}.md") for name in command_names}
- commands_norm = {name: _normalize(text) for name, text in commands.items()}
- alfred_agent = _read("agents/alfred.md")
- alfred_agent_norm = _normalize(alfred_agent)
- requirements = {
- "clarifying questions": [
- ("Solo usa `AskUserQuestion` si de verdad hay dos caminos plausibles", commands["alfred"]),
- ("una sola pregunta corta", commands["alfred"]),
- ("único `AskUserQuestion` con menú seleccionable real", commands["alfred"]),
- ("Si necesitas preguntar por ambigüedad real", commands["next"]),
- ("un único `AskUserQuestion` navegable", commands["next"]),
- ("NO uses `AskUserQuestion` por defecto", commands["discuss"]),
- ("no hace falta el menú", commands["discuss"]),
- ("DISCUSS_ROUTE_MENU_HEADLESS", commands["discuss"]),
- ("vuelve cancelada", commands["discuss"]),
- ("principal navegable", commands_norm["ajustes"]),
- ("config_headless_menu", commands_norm["ajustes"]),
- ("un único `AskUserQuestion`", commands["update"]),
- ],
- "human gates": [
- ("Si una gate de usuario queda pendiente, usa un único `AskUserQuestion`", commands["feature"]),
- ("Si una gate de usuario queda pendiente, usa un único `AskUserQuestion`", commands["fix"]),
- ("gate de despliegue siempre interactiva", commands_norm["ship"]),
- ("nunca auto-apruebes un despliegue", commands_norm["ship"]),
- ("NO marques una UAT como aprobada sin una indicación explícita del usuario", commands["uat"]),
- ("`/alfred-dev:verify aprobado`", commands["uat"]),
- ],
- "operational honesty": [
- ("Honestidad operativa y antifingimiento", commands["_composicion"]),
- ("No digas \"he ejecutado\", \"ha pasado\" o \"está validado\" si solo lo has inferido", commands["_composicion"]),
- ("Distingue siempre entre \"recomiendo ejecutar X\" y \"he ejecutado X", commands["_composicion"]),
- ("No finjas evidencia", commands["alfred"]),
- ("salida de herramienta", commands["alfred"]),
- ("siguiente paso verificable", commands["alfred"]),
- ("No finjas evidencia", alfred_agent),
- ("confirmación explícita del usuario", alfred_agent),
- ],
- "grounded fallbacks": [
- ("NO inventes stack, entrypoints o riesgos", commands["map-codebase"]),
- ("NO inventes un handoff", commands["pause"]),
- ("aceptacion manual prematura", commands_norm["uat"]),
- ("Si `$ARGUMENTS` está vacío, dilo claramente y no inventes una búsqueda", commands["search"]),
- ],
- }
- missing: list[str] = []
- for group, checks in requirements.items():
- for needle, haystack in checks:
- if needle not in haystack:
- missing.append(f"{group}: {needle}")
- helper_wrappers = [
- "alfred",
- "discuss",
- "map-codebase",
- "memory-ui",
- "pause",
- "progress",
- "retomar",
- "search",
- "sync-github",
- "uat",
- ]
- final_markers = (
- "respuesta final",
- "tal cual",
- "usala y termina",
- "usalo como respuesta final",
- "no sigas explorando",
- "segunda capa",
- "no la reenvuelvas",
- )
- for name in helper_wrappers:
- text_norm = commands_norm[name]
- if "helper" not in text_norm and "alfred-continuity.py" not in commands[name]:
- missing.append(f"helper-first {name}: falta helper")
- if not any(marker in text_norm for marker in final_markers):
- missing.append(f"helper-first {name}: falta regla de salida final sin reenvolver")
- if "No digas" not in commands["_composicion"] or "siguiente paso verificable" not in commands["alfred"]:
- missing.append("humanidad: falta contrato antifingimiento central")
- if "No finjas evidencia" not in alfred_agent:
- missing.append("humanidad: falta contrato antifingimiento en agente Alfred")
- if missing:
- _fail("Contratos de humanidad incompletos: " + "; ".join(missing))
- return [
- "AskUserQuestion limitado a ambigüedad real y gates humanas",
- "helpers operativos no duplican ni reenvuelven salida",
- "UAT exige indicación humana explícita",
- "antifingimiento centralizado en comandos y agente Alfred",
- ]
- def check_external_contracts() -> list[str]:
- audit = _read("commands/audit.md")
- audit_norm = _normalize(audit)
- sonarqube = _read("skills/sonarqube/SKILL.md")
- sonarqube_norm = _normalize(sonarqube)
- sync = _read("commands/sync-github.md")
- sync_norm = _normalize(sync)
- lucius_command = _read("commands/lucius.md")
- lucius_agent = _read("agents/lucius.md")
- lucius_all = lucius_command + "\n" + lucius_agent
- lucius_norm = _normalize(lucius_all)
- ship = _read("commands/ship.md")
- ship_norm = _normalize(ship)
- requirements = {
- "audit SonarQube preflight": [
- ("docker --version", audit),
- ("docker info", audit),
- ("AskUserQuestion", audit),
- ("NO intentes instalarlo por tu cuenta", audit),
- ("NO intentes arrancarlo por tu cuenta", audit),
- ("incluso si el proyecto esta en modo autopilot", audit_norm),
- ("sonarqube se omitio por decision explicita del usuario", audit_norm),
- ],
- "sonarqube skill permission": [
- ("no instales docker, no abras docker desktop y no arranques el daemon sin aprobacion explicita del usuario.", sonarqube_norm),
- ("si no existe una autorizacion previa, pidela ahora y espera respuesta.", sonarqube_norm),
- ("puerto `9000` ya esta en uso", sonarqube_norm),
- ("docker rm -f sonarqube-alfred", sonarqube),
- ("intenta igualmente la limpieza final del contenedor temporal", sonarqube_norm),
- ],
- "sync-github safe mirror": [
- ('python3 .claude/alfred-continuity.py sync-github "$PWD" --raw "$ARGUMENTS"', sync),
- ("gh --version", sync),
- ("gh auth status", sync),
- ("NO uses `AskUserQuestion` por defecto", sync),
- ("No borres issues ajenos a Alfred", sync),
- ("Mantén la verdad local", sync),
- ],
- "lucius external audit": [
- ("codex --version", lucius_all),
- ("codex login", lucius_all),
- ("confirmación explícita", lucius_all),
- ("codex exec", lucius_all),
- ("--sandbox read-only", lucius_all),
- ("--ephemeral", lucius_all),
- ("--json", lucius_all),
- ("--output-last-message", lucius_all),
- ("codex_report", lucius_all),
- ("codex_jsonl", lucius_all),
- ("approval_policy", lucius_all),
- ("status --porcelain=v1 -z", lucius_all),
- ("no modifiques ningun fichero", lucius_norm),
- ("nunca ejecutas codigo del proyecto", lucius_norm),
- ("no sustituyes a `qa-engineer`, `security-officer` ni `architect`", lucius_norm),
- ("no reemplaza el sign-off canonico", lucius_norm),
- ],
- "ship deploy gate": [
- ("gate de despliegue", ship_norm),
- ("siempre interactiva", ship_norm),
- ("un único `AskUserQuestion`", ship),
- ("nunca auto-apruebes un despliegue", ship_norm),
- ("usuario+seguridad", ship),
- ],
- }
- missing: list[str] = []
- for group, checks in requirements.items():
- for needle, haystack in checks:
- if needle not in haystack:
- missing.append(f"{group}: {needle}")
- if missing:
- _fail("Contratos externos incompletos: " + "; ".join(missing))
- return [
- "Docker/SonarQube pide permiso y documenta omisiones",
- "sync-github mantiene GitHub como espejo seguro",
- "Lucius confirma coste y no modifica ficheros",
- "ship mantiene deploy con gate humana",
- ]
- def run_command(name: str, command: list[str], timeout: int = 120) -> str:
- result = subprocess.run(
- command,
- cwd=ROOT,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- timeout=timeout,
- check=False,
- )
- if result.returncode != 0:
- raise AuditError(
- f"{name} fallo con codigo {result.returncode}\n{result.stdout}"
- )
- return result.stdout
- def _materialized_alfred_alias_bytes(*, invocable: bool = True) -> bytes:
- alias_source = ROOT / "skills" / "alfred" / "alfred" / "SKILL.md"
- text = alias_source.read_text(encoding="utf-8")
- value = "true" if invocable else "false"
- if re.search(r"(?m)^user-invocable:\s*(true|false)\s*$", text):
- text = re.sub(
- r"(?m)^user-invocable:\s*(true|false)\s*$",
- f"user-invocable: {value}",
- text,
- count=1,
- )
- elif text.startswith("---\n"):
- text = text.replace("---\n", f"---\nuser-invocable: {value}\n", 1)
- return text.encode("utf-8")
- def check_installed_cache_freshness() -> list[str]:
- if not INSTALLED_PLUGIN_DIR.is_dir():
- _fail(
- "No existe la cache instalada 0.7.0 de Claude. Refrescala con:\n"
- "claude plugin marketplace remove alfred-dev --scope user\n"
- "claude plugin marketplace add \"$PWD\" --scope user\n"
- "claude plugin uninstall alfred-dev@alfred-dev --scope user\n"
- "claude plugin install alfred-dev@alfred-dev --scope user"
- )
- missing: list[str] = []
- drifted: list[str] = []
- for relative in _iter_installed_cache_freshness_files():
- worktree_path = ROOT / relative
- installed_path = INSTALLED_PLUGIN_DIR / relative
- if not installed_path.is_file():
- missing.append(relative)
- continue
- if _sha256(worktree_path) != _sha256(installed_path):
- drifted.append(relative)
- if missing or drifted:
- details = []
- if missing:
- details.append("missing=" + ", ".join(missing[:12]))
- if drifted:
- details.append("drifted=" + ", ".join(drifted[:12]))
- _fail(
- "La cache instalada de Claude no coincide con el worktree auditado "
- f"({'; '.join(details)}). Refrescala con:\n"
- "claude plugin marketplace remove alfred-dev --scope user\n"
- "claude plugin marketplace add \"$PWD\" --scope user\n"
- "claude plugin uninstall alfred-dev@alfred-dev --scope user\n"
- "claude plugin install alfred-dev@alfred-dev --scope user"
- )
- return [
- "cache instalada 0.7.0 completa y coincide con el worktree"
- ]
- def _run_continuity(project_dir: Path, *args: str, timeout: int = 60) -> str:
- return run_command(
- f"continuity {' '.join(args)}",
- [sys.executable, str(ROOT / "core" / "continuity.py"), *args],
- timeout=timeout,
- )
- def _run_continuity_raw(project_dir: Path, *args: str, timeout: int = 60) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, str(ROOT / "core" / "continuity.py"), *args],
- cwd=ROOT,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=timeout,
- check=False,
- )
- def _complete_quick_session(project_dir: Path) -> None:
- from core.orchestrator import advance_phase, create_session, save_state
- session = create_session("quick", "Ajustar copy login")
- while session["fase_actual"] != "completado":
- session = advance_phase(session, resultado="aprobado", artefactos=[])
- save_state(session, str(project_dir / ".claude" / "alfred-dev-state.json"))
- def check_continuity_smoke() -> list[str]:
- with tempfile.TemporaryDirectory(prefix="alfred-release-audit-") as tmp:
- project = Path(tmp)
- (project / "src").mkdir()
- (project / "package.json").write_text('{"name":"fixture"}\n', encoding="utf-8")
- (project / "src" / "app.js").write_text(
- "export function label() { return 'Login'; }\n",
- encoding="utf-8",
- )
- sync_empty = project / "sync-empty"
- sync_empty.mkdir()
- sync_fail = _run_continuity_raw(sync_empty, "sync-github", str(sync_empty), "--raw", "owner/repo")
- if sync_fail.returncode == 0:
- _fail("sync-github deberia fallar sin tareas sincronizables preparadas para GitHub")
- sync_error = sync_fail.stderr + sync_fail.stdout
- if (
- "No hay tareas con identificador [T-XXX]" not in sync_error
- and "No hay tareas en docs/project/kanban/" not in sync_error
- ):
- _fail(f"sync-github no fallo de forma explicita sin tareas: {sync_error}")
- next_initial = json.loads(_run_continuity(project, "next", str(project), "--json"))
- if next_initial.get("command") != "map-codebase":
- _fail(f"next inicial esperaba map-codebase, obtuvo {next_initial}")
- mapped = json.loads(
- _run_continuity(project, "map-codebase", str(project), "--raw", "login", "--json")
- )
- if mapped.get("recommended_command") != "discuss":
- _fail(f"map-codebase esperaba recommend discuss, obtuvo {mapped}")
- if not (project / "docs" / "project" / "codebase-map.md").exists():
- _fail("map-codebase no creo docs/project/codebase-map.md")
- from core.continuity import save_prefetch_result
- save_prefetch_result(
- str(project),
- {
- "source_command": "map-codebase",
- "prefetched_command": "map-codebase",
- "project_name": "fixture",
- "stack": {"runtime": "node", "framework": "desconocido"},
- "recommended_command": "discuss",
- },
- )
- consumed = _run_continuity(
- project,
- "consume-prefetch",
- str(project),
- "--expected",
- "map-codebase",
- )
- if "## Mapeo brownfield completado" not in consumed:
- _fail("consume-prefetch no devolvio la respuesta helper-first esperada")
- if (project / ".claude" / "alfred-prefetch.json").exists():
- _fail("consume-prefetch no limpio el prefetch transitorio")
- discussed = json.loads(
- _run_continuity(project, "discuss", str(project), "--raw", "ajustar login", "--json")
- )
- if discussed.get("recommended_command") not in {"feature", "quick", "fix", "spike"}:
- _fail(f"discuss devolvio recomendacion inesperada: {discussed}")
- quick = _run_continuity(project, "quick", str(project), "--raw", "cambiar CTA")
- if "## Quick preparado" not in quick or "/alfred-dev:verify" not in quick:
- _fail("quick no devolvio resumen humano con siguiente verify")
- handoff = json.loads(_run_continuity(project, "write-handoff", str(project)))
- handoff_path = project / ".claude" / "alfred-handoff.json"
- handoff_payload = json.loads(handoff_path.read_text(encoding="utf-8")) if handoff_path.exists() else {}
- if handoff_payload.get("command") != "quick" or not Path(handoff.get("json_path", "")).exists():
- _fail(f"write-handoff no persistio handoff de quick: {handoff}")
- bypass = json.loads(
- _run_continuity(
- project,
- "allow-stop-once",
- str(project),
- "--command",
- "/alfred-dev:status",
- )
- )
- if bypass.get("command") != "/alfred-dev:status" or not Path(bypass.get("bypass_path", "")).exists():
- _fail(f"allow-stop-once no armo bypass valido: {bypass}")
- status = _run_continuity(project, "status", str(project))
- if "## Estado operativo de Alfred Dev" not in status:
- _fail("status no devolvio resumen operativo")
- pause = _run_continuity(project, "pause", str(project))
- if "## Sesión pausada" not in pause:
- _fail("pause no dejo salida humana de pausa")
- resume = _run_continuity(project, "resume", str(project))
- if "## Sesión reanudada" not in resume:
- _fail("resume no dejo salida humana de reanudacion")
- for command, expected in [
- ("progress", "## Resumen operativo del proyecto"),
- ("standup", "## Standup diario"),
- ("blocked", "## Tareas en blocked"),
- ("in-progress", "## Tareas en in progress"),
- ("validate", "## Validación operativa"),
- ]:
- output = _run_continuity(project, command, str(project))
- if expected not in output:
- _fail(f"{command} no contiene {expected!r}")
- search = _run_continuity(project, "search", str(project), "--raw", "login")
- if "## Resultados para `login`" not in search:
- _fail("search no devolvio resultados humanos")
- kanban = project / "docs" / "project" / "kanban"
- kanban.mkdir(parents=True, exist_ok=True)
- (kanban / "backlog.md").write_text(
- "# Backlog\n\n"
- "### [T-010] Validar login con /alfred-dev:verify\n\n"
- "- **Agente:** alfred:verify\n",
- encoding="utf-8",
- )
- for lane in ("in-progress", "done", "blocked"):
- (kanban / f"{lane}.md").write_text(f"# {lane.title()}\n", encoding="utf-8")
- normalize = _run_continuity(project, "normalize-kanban", str(project))
- if "## Normalización de kanban" not in normalize or "Tareas ajustadas" not in normalize:
- _fail("normalize-kanban no devolvio resumen de normalizacion")
- memory_started = False
- try:
- memory_ui = json.loads(
- _run_continuity(
- project,
- "memory-ui",
- str(project),
- "--json",
- "--no-open",
- timeout=90,
- )
- )
- memory_started = True
- if not str(memory_ui.get("url", "")).startswith("http://127.0.0.1:"):
- _fail(f"memory-ui no devolvio URL local valida: {memory_ui}")
- if not (project / ".claude" / "alfred-memory-ui.json").exists():
- _fail("memory-ui no persistio .claude/alfred-memory-ui.json")
- finally:
- if memory_started:
- _run_continuity(project, "memory-ui", str(project), "--stop", "--json", timeout=90)
- _complete_quick_session(project)
- verify = _run_continuity(project, "verify", str(project), "--raw", "aprobado")
- uat_path = project / ".claude" / "alfred-uat.json"
- uat = json.loads(uat_path.read_text(encoding="utf-8")) if uat_path.exists() else {}
- if (
- "Verificación manual / UAT" not in verify
- or "aprobada" not in verify.lower()
- or uat.get("status") != "approved"
- ):
- _fail("verify aprobado no registro UAT humana")
- return [
- "next/map-codebase/discuss/quick",
- "status/pause/resume/progress/standup",
- "blocked/in-progress/validate/search/verify",
- "write-handoff/allow-stop-once/consume-prefetch/normalize-kanban/memory-ui/sync-github-fail-closed",
- ]
- class _MCPJsonlClient:
- def __init__(self, project_dir: Path) -> None:
- self._next_id = 1
- self._proc = subprocess.Popen(
- [sys.executable, str(ROOT / "mcp" / "memory_server.py")],
- cwd=project_dir,
- text=True,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- )
- self._selector = selectors.DefaultSelector()
- assert self._proc.stdout is not None
- self._selector.register(self._proc.stdout, selectors.EVENT_READ)
- def close(self) -> None:
- if self._proc.stdin is not None:
- try:
- self._proc.stdin.close()
- except OSError:
- pass
- try:
- self._proc.wait(timeout=5)
- except subprocess.TimeoutExpired:
- self._proc.terminate()
- self._proc.wait(timeout=5)
- if self._proc.returncode not in {0, None}:
- stderr = self._proc.stderr.read() if self._proc.stderr else ""
- _fail(f"Servidor MCP termino con codigo {self._proc.returncode}: {stderr}")
- def notify(self, method: str, params: dict | None = None) -> None:
- assert self._proc.stdin is not None
- payload = {"jsonrpc": "2.0", "method": method}
- if params is not None:
- payload["params"] = params
- self._proc.stdin.write(json.dumps(payload, ensure_ascii=False) + "\n")
- self._proc.stdin.flush()
- def request(self, method: str, params: dict | None = None) -> dict:
- assert self._proc.stdin is not None
- request_id = self._next_id
- self._next_id += 1
- payload = {"jsonrpc": "2.0", "id": request_id, "method": method}
- if params is not None:
- payload["params"] = params
- self._proc.stdin.write(json.dumps(payload, ensure_ascii=False) + "\n")
- self._proc.stdin.flush()
- events = self._selector.select(timeout=10)
- if not events:
- stderr = self._proc.stderr.read() if self._proc.stderr else ""
- _fail(f"Timeout esperando respuesta MCP para {method}: {stderr}")
- line = self._proc.stdout.readline() # type: ignore[union-attr]
- if not line:
- stderr = self._proc.stderr.read() if self._proc.stderr else ""
- _fail(f"Servidor MCP cerro stdout durante {method}: {stderr}")
- response = json.loads(line)
- if response.get("id") != request_id:
- _fail(f"Respuesta MCP con id inesperado: {response}")
- if "error" in response:
- _fail(f"Error MCP en {method}: {response['error']}")
- return response["result"]
- def call_tool(self, name: str, arguments: dict | None = None) -> dict:
- result = self.request(
- "tools/call",
- {"name": name, "arguments": arguments or {}},
- )
- if result.get("isError"):
- _fail(f"{name} devolvio isError: {result}")
- content = result.get("content") or []
- if not content or content[0].get("type") != "text":
- _fail(f"{name} no devolvio contenido text: {result}")
- return json.loads(content[0]["text"])
- def check_mcp_tools_smoke() -> list[str]:
- with tempfile.TemporaryDirectory(prefix="alfred-mcp-audit-") as tmp:
- project = Path(tmp)
- (project / ".claude").mkdir()
- adr_dir = project / "docs" / "adr"
- adr_dir.mkdir(parents=True)
- (adr_dir / "0001-cache.md").write_text(
- "# Usar Redis\n\n"
- "## Contexto\n\nNecesitamos cachear lecturas frecuentes.\n\n"
- "## Decisión\n\nUsar Redis para cache compartida.\n",
- encoding="utf-8",
- )
- client = _MCPJsonlClient(project)
- try:
- init = client.request(
- "initialize",
- {
- "protocolVersion": "2025-11-25",
- "clientInfo": {"name": "alfred-release-audit", "version": VERSION},
- "capabilities": {},
- },
- )
- if init.get("serverInfo", {}).get("name") != "alfred-memory":
- _fail(f"initialize inesperado: {init}")
- client.notify("notifications/initialized")
- tools = client.request("tools/list")["tools"]
- tool_names = [tool["name"] for tool in tools]
- if len(tool_names) != 15:
- _fail(f"tools/list esperaba 15 herramientas, obtuvo {tool_names}")
- tool_by_name = {tool["name"]: tool for tool in tools}
- expected_limits = {
- "memory_search": 100,
- "memory_get_decisions": 200,
- "memory_import": 1000,
- }
- for tool_name, maximum in expected_limits.items():
- schema = tool_by_name[tool_name]["inputSchema"]["properties"]["limit"]
- if schema.get("minimum") != 1 or schema.get("maximum") != maximum:
- _fail(
- f"{tool_name} no declara limites MCP defensivos: {schema}"
- )
- event_schema = tool_by_name["memory_log_event"]["inputSchema"]["properties"]
- expected_event_bounds = {
- "event_type": 80,
- "phase": 80,
- "summary": 500,
- "content": 8000,
- }
- for field, maximum in expected_event_bounds.items():
- if event_schema[field].get("maxLength") != maximum:
- _fail(f"memory_log_event no declara maxLength para {field}: {event_schema[field]}")
- if "preview" not in event_schema["payload"].get("description", ""):
- _fail("memory_log_event no documenta preview para payload enorme")
- started = client.call_tool(
- "memory_manage_iteration",
- {"action": "start", "command": "feature", "description": "Login release audit"},
- )
- iteration_id = started.get("iteration_id")
- if not iteration_id:
- _fail(f"memory_manage_iteration no devolvio iteration_id: {started}")
- dec1 = client.call_tool(
- "memory_log_decision",
- {
- "title": "Cache de login",
- "chosen": "Redis",
- "context": "Login con lecturas frecuentes",
- "tags": ["release-audit"],
- },
- )["decision_id"]
- dec2 = client.call_tool(
- "memory_log_decision",
- {
- "title": "Sesion de usuario",
- "chosen": "Cookie segura",
- "tags": ["release-audit"],
- },
- )["decision_id"]
- client.call_tool(
- "memory_update_decision",
- {"id": dec1, "status": "superseded", "tags": ["mcp-smoke"]},
- )
- client.call_tool(
- "memory_link_decisions",
- {"source_id": dec1, "target_id": dec2, "link_type": "relates"},
- )
- client.call_tool(
- "memory_log_commit",
- {
- "sha": "abc123releaseaudit",
- "message": "feat: login cache",
- "author": "Alfred Audit",
- "decision_ids": [dec1],
- "files": ["src/login.py"],
- },
- )
- client.call_tool(
- "memory_log_event",
- {
- "event_type": "gate_passed",
- "phase": "calidad",
- "summary": "Redis cache validada",
- "payload": {"note": "redis cache validada"},
- },
- )
- large_event = client.call_tool(
- "memory_log_event",
- {
- "event_type": "custom",
- "phase": "calidad",
- "summary": "evento MCP grande",
- "content": "x" * 9000,
- "payload": {"blob": "y" * 9000},
- },
- )
- if not large_event.get("content_truncated") or not large_event.get("payload_truncated"):
- _fail(f"memory_log_event no recorto content/payload enormes: {large_event}")
- search = client.call_tool("memory_search", {"query": "Redis", "limit": 10})
- if search.get("total", 0) < 1:
- _fail(f"memory_search no encontro datos sembrados: {search}")
- capped_search = client.call_tool(
- "memory_search",
- {"query": "Redis", "limit": 999999},
- )
- if capped_search.get("applied_limit") != 100:
- _fail(f"memory_search no recorto limit abusivo: {capped_search}")
- if client.call_tool("memory_get_iteration", {"id": iteration_id}).get("iteration") is None:
- _fail("memory_get_iteration no devolvio la iteracion creada")
- if client.call_tool("memory_get_timeline", {"iteration_id": iteration_id}).get("total", 0) < 1:
- _fail("memory_get_timeline no devolvio eventos")
- if client.call_tool("memory_get_decisions", {"tags": ["release-audit"]}).get("total", 0) < 2:
- _fail("memory_get_decisions no devolvio decisiones sembradas")
- if client.call_tool("memory_stats").get("total_decisions", 0) < 2:
- _fail("memory_stats no conto decisiones")
- if client.call_tool("memory_health").get("status") != "healthy":
- _fail("memory_health no devolvio healthy")
- export_path = str(project / "DECISIONS.md")
- if client.call_tool("memory_export", {"format": "markdown", "path": export_path}).get("exported", 0) < 2:
- _fail("memory_export no exporto decisiones")
- if not Path(export_path).exists():
- _fail("memory_export no creo DECISIONS.md")
- blocked_export = client.request(
- "tools/call",
- {
- "name": "memory_export",
- "arguments": {
- "format": "markdown",
- "path": str(project.parent / "OUTSIDE.md"),
- },
- },
- )
- if not blocked_export.get("isError"):
- _fail(f"memory_export permitio escribir fuera del proyecto: {blocked_export}")
- if client.call_tool("memory_import", {"source": "adr", "path": str(adr_dir)}).get("imported") != 1:
- _fail("memory_import adr no importo el ADR fixture")
- purge = client.call_tool("memory_purge", {"retention_days": 1})
- if "purged_events" not in purge:
- _fail("memory_purge no devolvio purged_events")
- client.call_tool("memory_manage_iteration", {"action": "complete", "iteration_id": iteration_id})
- finally:
- client.close()
- return [
- "15 tools listadas",
- "15 tools invocadas con datos reales",
- "limites MCP defensivos en schemas y handlers",
- "memory_log_event recorta payload/content MCP enormes",
- "rutas MCP acotadas al proyecto",
- "SQLite temporal saludable",
- ]
- def check_external(args: argparse.Namespace) -> list[str]:
- ok: list[str] = []
- if args.with_external_contracts:
- for line in check_external_contracts():
- ok.append(f"external {line}")
- if args.with_human_contracts:
- for line in check_human_contracts():
- ok.append(f"human {line}")
- if args.with_continuity:
- for line in check_continuity_smoke():
- ok.append(f"continuity {line}")
- if args.with_mcp_tools:
- for line in check_mcp_tools_smoke():
- ok.append(f"mcp-tools {line}")
- if args.with_claude:
- for line in check_installed_cache_freshness():
- ok.append(f"claude {line}")
- details = run_command(
- "claude plugin validate/details",
- [
- "sh",
- "-c",
- "claude plugin validate . --strict && "
- "claude plugin details alfred-dev@alfred-dev | sed -n '1,18p' && "
- "claude mcp get plugin:alfred-dev:alfred-memory",
- ],
- timeout=90,
- )
- for needle in ("Alfred Dev (alfred-dev) 0.7.0", "Skills (11)", "Agents (10)", "MCP servers (1)", "Status: ✔ Connected"):
- if needle not in details:
- _fail(f"Smoke Claude no contiene {needle!r}")
- ok.append("Claude CLI valida inventario y MCP")
- discovery = run_command(
- "claude interactive /alfred discovery",
- [sys.executable, str(ROOT / "scripts" / "claude_command_discovery.py")],
- timeout=35,
- )
- if "ok claude interactive command discovery" not in discovery:
- _fail("Smoke Claude no confirmo descubrimiento interactivo de /alfred")
- if "FAIL claude-command-discovery" in discovery:
- _fail("Smoke Claude sigue mostrando fallo de descubrimiento interactivo de /alfred")
- ok.append("Claude CLI descubre /alfred en selector interactivo")
- if args.with_site:
- run_command("npm site check/build", ["sh", "-c", "npm --prefix site run check && npm --prefix site run build"], timeout=180)
- ok.append("site check/build")
- if args.with_tests:
- run_command("pytest completo", ["python3", "-m", "pytest", "tests/", "-q"], timeout=300)
- ok.append("pytest completo")
- if args.with_syntax:
- run_command(
- "syntax/json/diff",
- [
- "sh",
- "-c",
- "bash -n install.sh && "
- "python3 -m json.tool .mcp.json >/dev/null && "
- "python3 -m json.tool .claude-plugin/plugin.json >/dev/null && "
- "python3 -m json.tool .claude-plugin/marketplace.json >/dev/null && "
- "git diff --check",
- ],
- timeout=60,
- )
- ok.append("syntax/json/diff-check")
- return ok
- def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--with-claude", action="store_true", help="Ejecuta smokes con claude plugin/mcp.")
- parser.add_argument("--with-site", action="store_true", help="Ejecuta npm --prefix site run check/build.")
- parser.add_argument("--with-tests", action="store_true", help="Ejecuta python3 -m pytest tests/ -q.")
- parser.add_argument("--with-syntax", action="store_true", help="Ejecuta bash -n, json.tool y git diff --check.")
- parser.add_argument("--with-continuity", action="store_true", help="Ejecuta smoke operativo de helpers en fixture temporal.")
- parser.add_argument("--with-mcp-tools", action="store_true", help="Invoca las 15 herramientas MCP en una SQLite temporal.")
- parser.add_argument("--with-external-contracts", action="store_true", help="Verifica prompts seguros para Docker, GitHub, Lucius y deploy.")
- parser.add_argument("--with-human-contracts", action="store_true", help="Verifica trato humano, AskUserQuestion, UAT y antifingimiento.")
- parser.add_argument("--full", action="store_true", help="Activa todos los smokes externos.")
- args = parser.parse_args(argv)
- if args.full:
- args.with_claude = args.with_site = args.with_tests = True
- args.with_syntax = args.with_continuity = True
- args.with_mcp_tools = args.with_external_contracts = True
- args.with_human_contracts = True
- checks = [
- ("versionado", check_versions),
- ("inventario", check_inventory),
- ("catalogo", check_command_catalog),
- ("comandos", check_command_execution_contracts),
- ("claims", check_public_claims),
- ("config", check_config_contracts),
- ("flows", check_flow_gate_claims),
- ("hooks", check_hook_contracts),
- ("mcp", check_mcp_config),
- ("packaging", check_packaging_contracts),
- ("secrets", check_published_secret_scan),
- ("install", check_install_update_contracts),
- ("docs", check_audit_docs),
- ]
- try:
- for name, check in checks:
- for line in check():
- print(f"ok {name}: {line}")
- for line in check_external(args):
- print(f"ok smoke: {line}")
- except (AuditError, subprocess.TimeoutExpired) as exc:
- print(f"FAIL release-audit: {exc}", file=sys.stderr)
- return 1
- print(f"release-audit {VERSION} ok")
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
uninstall.ps1 · Bundled script · 191 lines · 1 finding marked
- # ---------------------------------------------------------------------------
- # Alfred Dev -- script de desinstalacion (Windows)
- #
- # Uso:
- # 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
- #
- # Estrategia:
- # 1. Si Claude CLI está disponible, desinstalar el plugin y eliminar el
- # marketplace usando la vía nativa.
- # 2. Limpiar cualquier resto físico en cache/ y marketplaces/.
- # 3. Limpiar de forma residual los JSON internos si todavía quedan rastros.
- # ---------------------------------------------------------------------------
- $ErrorActionPreference = 'Stop'
- $PluginName = "alfred-dev"
- $ClaudeDir = Join-Path $env:USERPROFILE ".claude"
- $PluginsDir = Join-Path $ClaudeDir "plugins"
- # La ruta de cache sigue la convencion de Claude Code: cache/<marketplace>/<plugin>/<version>.
- # Se borra el directorio completo del marketplace para cubrir instalaciones viejas y nuevas.
- $CacheDir = Join-Path $PluginsDir "cache" $PluginName
- $MarketplaceDir = Join-Path $PluginsDir "marketplaces" $PluginName
- $InstalledFile = Join-Path $PluginsDir "installed_plugins.json"
- $KnownMarketplaces = Join-Path $PluginsDir "known_marketplaces.json"
- $SettingsFile = Join-Path $ClaudeDir "settings.json"
- $PluginKey = "$PluginName@$PluginName"
- $GlobalAliasDir = Join-Path $ClaudeDir "skills/alfred"
- $GlobalAliasFile = Join-Path $GlobalAliasDir "SKILL.md"
- $GlobalCommandAliasDir = Join-Path $ClaudeDir "commands"
- $GlobalCommandAliasFile = Join-Path $GlobalCommandAliasDir "alfred.md"
- # -- Funciones auxiliares ---------------------------------------------------
- function Write-Info { param([string]$Msg) Write-Host ">" $Msg -ForegroundColor Blue }
- function Write-Ok { param([string]$Msg) Write-Host "+" $Msg -ForegroundColor Green }
- function Write-Err { param([string]$Msg) Write-Host "x" $Msg -ForegroundColor Red }
- function Read-JsonFile {
- param([string]$Path)
- if (-not (Test-Path $Path)) { return $null }
- try {
- return (Get-Content $Path -Raw -Encoding UTF8) | ConvertFrom-Json
- }
- catch {
- Write-Err "El fichero '$Path' contiene JSON invalido: $_"
- throw
- }
- }
- # Escribir JSON de forma atomica (fichero temporal en mismo directorio + mover).
- # Crear el temporal junto al destino garantiza que Move-Item sea un rename
- # atomico del sistema de ficheros, sin copias entre discos.
- function Write-JsonFileAtomic {
- param([string]$Path, [object]$Data)
- $targetDir = Split-Path $Path -Parent
- $tmpFile = Join-Path $targetDir ".tmp-$([System.IO.Path]::GetRandomFileName())"
- try {
- $Data | ConvertTo-Json -Depth 10 | Set-Content $tmpFile -Encoding UTF8
- Move-Item -Path $tmpFile -Destination $Path -Force
- }
- catch {
- if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
- throw
- }
- }
- function Test-EmptyDirectory {
- param([string]$Path)
- if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
- return $false
- }
- return $null -eq (Get-ChildItem -LiteralPath $Path -Force -ErrorAction SilentlyContinue)
- }
- function Remove-GlobalAlfredAlias {
- $removed = $false
- if (Test-Path $GlobalAliasFile -PathType Leaf) {
- $content = Get-Content $GlobalAliasFile -Raw -Encoding UTF8
- if ($content -match "Alfred Dev global alias") {
- Remove-Item $GlobalAliasFile -Force
- if (Test-EmptyDirectory $GlobalAliasDir) {
- Remove-Item $GlobalAliasDir -Force
- }
- Write-Ok "Alias global /alfred eliminado"
- $removed = $true
- }
- else {
- Write-Info "Se conserva ${GlobalAliasFile}: no parece ser el alias de Alfred Dev"
- }
- }
- if (Test-Path $GlobalCommandAliasFile -PathType Leaf) {
- $content = Get-Content $GlobalCommandAliasFile -Raw -Encoding UTF8
- if ($content -match "Alfred Dev global alias") {
- Remove-Item $GlobalCommandAliasFile -Force
- if (Test-EmptyDirectory $GlobalCommandAliasDir) {
- Remove-Item $GlobalCommandAliasDir -Force
- }
- Write-Ok "Shim de comando global /alfred eliminado"
- $removed = $true
- }
- else {
- Write-Info "Se conserva ${GlobalCommandAliasFile}: no parece ser el alias de Alfred Dev"
- }
- }
- if (-not $removed) {
- Write-Info "No se encontro alias global /alfred"
- }
- }
- # ---------------------------------------------------------------------------
- Write-Host ""
- Write-Host "Desinstalando Alfred Dev" -ForegroundColor White
- Write-Host ""
- # Intentar primero la vía canónica de Claude Code.
- $ClaudeCli = Get-Command claude -ErrorAction SilentlyContinue
- if ($null -ne $ClaudeCli) {
- Write-Info "Desinstalando plugin con Claude CLI..."
- & claude plugin uninstall $PluginKey --scope user 2>&1 | Out-Null
- & claude plugin marketplace remove $PluginName --scope user 2>&1 | Out-Null
- Write-Ok "Claude CLI ha intentado desregistrar el plugin y el marketplace"
- }
- else {
- Write-Info "El comando 'claude' no esta disponible; se aplicara limpieza manual de seguridad"
- }
- # Eliminar cache del plugin
- if (Test-Path $CacheDir) {
- Remove-Item $CacheDir -Recurse -Force
- Write-Ok "Cache del plugin eliminada"
- }
- else {
- Write-Info "No se encontro cache del plugin"
- }
- # Eliminar directorio de marketplace
- if (Test-Path $MarketplaceDir) {
- Remove-Item $MarketplaceDir -Recurse -Force
- Write-Ok "Directorio de marketplace eliminado"
- }
- else {
- Write-Info "No se encontro directorio de marketplace"
- }
- Remove-GlobalAlfredAlias
- # Eliminar marketplace de known_marketplaces.json
- if (Test-Path $KnownMarketplaces) {
- $known = Read-JsonFile $KnownMarketplaces
- if ($null -ne $known -and $known.PSObject.Properties.Name -contains $PluginName) {
- $known.PSObject.Properties.Remove($PluginName)
- Write-JsonFileAtomic $KnownMarketplaces $known
- Write-Ok "Marketplace limpiado de known_marketplaces.json"
- }
- }
- # Eliminar registro de installed_plugins.json
- if (Test-Path $InstalledFile) {
- $installed = Read-JsonFile $InstalledFile
- if ($null -ne $installed -and
- $installed.PSObject.Properties.Name -contains 'plugins' -and
- $installed.plugins.PSObject.Properties.Name -contains $PluginKey) {
- $installed.plugins.PSObject.Properties.Remove($PluginKey)
- Write-JsonFileAtomic $InstalledFile $installed
- Write-Ok "Registro limpiado de installed_plugins.json"
- }
- }
- # Deshabilitar en settings.json
- if (Test-Path $SettingsFile) {
- $settings = Read-JsonFile $SettingsFile
- if ($null -ne $settings -and
- $settings.PSObject.Properties.Name -contains 'enabledPlugins' -and
- $settings.enabledPlugins.PSObject.Properties.Name -contains $PluginKey) {
- $settings.enabledPlugins.PSObject.Properties.Remove($PluginKey)
- Write-JsonFileAtomic $SettingsFile $settings
- Write-Ok "Plugin limpiado de settings.json"
- }
- }
- else {
- Write-Info "No se encontro settings.json (nada que deshabilitar)"
- }
- Write-Host ""
- Write-Host "Alfred Dev desinstalado" -ForegroundColor Green
- Write-Host " Reinicia Claude Code para aplicar los cambios." -ForegroundColor DarkGray
- Write-Host ""
uninstall.sh · Bundled script · 276 lines · 1 finding marked
- #!/usr/bin/env bash
- # ---------------------------------------------------------------------------
- # Alfred Dev -- script de desinstalación
- #
- # Uso:
- # 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
- # bash ./uninstall.sh
- #
- # Estrategia:
- # 1. Si Claude CLI está disponible, desinstalar el plugin y eliminar el
- # marketplace usando la vía nativa.
- # 2. Limpiar cualquier resto físico en cache/ y marketplaces/.
- # 3. Como red de seguridad, limpiar known_marketplaces.json,
- # installed_plugins.json y settings.json si todavía contienen rastros.
- # ---------------------------------------------------------------------------
- set -euo pipefail
- PLUGIN_NAME="alfred-dev"
- PLUGIN_KEY="${PLUGIN_NAME}@${PLUGIN_NAME}"
- CLAUDE_DIR="${HOME}/.claude"
- PLUGINS_DIR="${CLAUDE_DIR}/plugins"
- MARKETPLACE_DIR="${PLUGINS_DIR}/marketplaces/${PLUGIN_NAME}"
- INSTALLED_FILE="${PLUGINS_DIR}/installed_plugins.json"
- KNOWN_MARKETPLACES="${PLUGINS_DIR}/known_marketplaces.json"
- SETTINGS_FILE="${CLAUDE_DIR}/settings.json"
- GLOBAL_ALIAS_DIR="${CLAUDE_DIR}/skills/alfred"
- GLOBAL_ALIAS_FILE="${GLOBAL_ALIAS_DIR}/SKILL.md"
- GLOBAL_COMMAND_ALIAS_DIR="${CLAUDE_DIR}/commands"
- GLOBAL_COMMAND_ALIAS_FILE="${GLOBAL_COMMAND_ALIAS_DIR}/alfred.md"
- RED='\033[0;31m'
- GREEN='\033[0;32m'
- BLUE='\033[0;34m'
- BOLD='\033[1m'
- DIM='\033[2m'
- NC='\033[0m'
- info() { printf "${BLUE}>${NC} %s\n" "$1"; }
- ok() { printf "${GREEN}+${NC} %s\n" "$1"; }
- error() { printf "${RED}x${NC} %s\n" "$1" >&2; }
- remove_global_alfred_alias() {
- local removed=0
- if [[ -f "${GLOBAL_ALIAS_FILE}" ]]; then
- if grep -q "Alfred Dev global alias" "${GLOBAL_ALIAS_FILE}"; then
- rm -f "${GLOBAL_ALIAS_FILE}"
- rmdir "${GLOBAL_ALIAS_DIR}" >/dev/null 2>&1 || true
- ok "Alias global /alfred eliminado"
- removed=1
- else
- info "Se conserva ${GLOBAL_ALIAS_FILE}: no parece ser el alias de Alfred Dev"
- fi
- fi
- if [[ -f "${GLOBAL_COMMAND_ALIAS_FILE}" ]]; then
- if grep -q "Alfred Dev global alias" "${GLOBAL_COMMAND_ALIAS_FILE}"; then
- rm -f "${GLOBAL_COMMAND_ALIAS_FILE}"
- rmdir "${GLOBAL_COMMAND_ALIAS_DIR}" >/dev/null 2>&1 || true
- ok "Shim de comando global /alfred eliminado"
- removed=1
- else
- info "Se conserva ${GLOBAL_COMMAND_ALIAS_FILE}: no parece ser el alias de Alfred Dev"
- fi
- fi
- if [[ "${removed}" -eq 0 ]]; then
- info "No se encontro alias global /alfred"
- fi
- }
- find_compatible_python() {
- local candidate ver major minor
- for candidate in python3 python3.13 python3.12 python3.11 python3.10; do
- if ! command -v "$candidate" &>/dev/null; then
- continue
- fi
- ver=$("$candidate" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
- major=$(echo "$ver" | cut -d. -f1)
- minor=$(echo "$ver" | cut -d. -f2)
- if [[ "$major" -ge 3 ]] && [[ "$minor" -ge 10 ]]; then
- printf '%s\n' "$candidate"
- return 0
- fi
- done
- for brew_path in /opt/homebrew/bin /usr/local/bin; do
- for candidate in python3.13 python3.12 python3.11 python3.10 python3; do
- local full="${brew_path}/${candidate}"
- if [[ ! -x "$full" ]]; then
- continue
- fi
- ver=$("$full" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
- major=$(echo "$ver" | cut -d. -f1)
- minor=$(echo "$ver" | cut -d. -f2)
- if [[ "$major" -ge 3 ]] && [[ "$minor" -ge 10 ]]; then
- printf '%s\n' "$full"
- return 0
- fi
- done
- done
- return 1
- }
- # Validar que HOME apunta a un directorio real
- if [[ -z "${HOME:-}" ]] || [[ ! -d "${HOME}" ]]; then
- error "La variable HOME no está definida o no apunta a un directorio válido"
- exit 1
- fi
- if [[ ! -d "${CLAUDE_DIR}" ]]; then
- info "No se encontró ${CLAUDE_DIR}; no hay instalación de usuario que limpiar"
- exit 0
- fi
- printf "\n${BOLD}Desinstalando Alfred Dev${NC}\n\n"
- # Intentar primero la vía canónica de Claude Code.
- if command -v claude &>/dev/null; then
- info "Desinstalando plugin con Claude CLI..."
- claude plugin uninstall "${PLUGIN_KEY}" --scope user >/dev/null 2>&1 || true
- claude plugin marketplace remove "${PLUGIN_NAME}" --scope user >/dev/null 2>&1 || true
- ok "Claude CLI ha intentado desregistrar el plugin y el marketplace"
- else
- info "El comando 'claude' no está disponible; se aplicará limpieza manual de seguridad"
- fi
- # Eliminar cache del plugin.
- # Se borra el directorio completo del marketplace en caché (cache/alfred-dev/)
- # para limpiar tanto instalaciones nuevas (cache/alfred-dev/alfred-dev/<version>)
- # como antiguas (cache/alfred-dev/<version>) de forma uniforme.
- CACHE_MARKETPLACE_DIR="${PLUGINS_DIR}/cache/${PLUGIN_NAME}"
- if [ -d "${CACHE_MARKETPLACE_DIR}" ]; then
- rm -rf "${CACHE_MARKETPLACE_DIR}"
- ok "Cache del plugin eliminada"
- else
- info "No se encontró cache del plugin"
- fi
- # Eliminar directorio de marketplace
- if [ -d "${MARKETPLACE_DIR}" ]; then
- rm -rf "${MARKETPLACE_DIR}"
- ok "Directorio de marketplace eliminado"
- else
- info "No se encontró directorio de marketplace"
- fi
- remove_global_alfred_alias
- # Si no hay Python compatible, no podemos aplicar la limpieza residual de JSON.
- PYTHON_CMD="$(find_compatible_python || true)"
- if [[ -z "${PYTHON_CMD}" ]]; then
- info "No se encontro Python 3.10+; se omite la limpieza residual de ficheros JSON"
- printf "\n${GREEN}${BOLD}Alfred Dev desinstalado${NC}\n"
- printf " ${DIM}Reinicia Claude Code para aplicar los cambios.${NC}\n\n"
- exit 0
- fi
- # Eliminar marketplace de known_marketplaces.json si aún quedara rastro.
- if [ -f "${KNOWN_MARKETPLACES}" ]; then
- "${PYTHON_CMD}" - "${KNOWN_MARKETPLACES}" "${PLUGIN_NAME}" <<'PYEOF'
- import json, os, sys, tempfile
- known_file, marketplace_name = sys.argv[1:3]
- try:
- with open(known_file, 'r') as f:
- data = json.load(f)
- except json.JSONDecodeError as e:
- print(f"Error: '{known_file}' contiene JSON inválido: {e}", file=sys.stderr)
- sys.exit(1)
- except OSError as e:
- print(f"Error: no se pudo leer '{known_file}': {e}", file=sys.stderr)
- sys.exit(1)
- if marketplace_name in data:
- del data[marketplace_name]
- # Escritura atómica
- try:
- tmp_fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(known_file))
- with os.fdopen(tmp_fd, 'w') as f:
- json.dump(data, f, indent=2)
- os.replace(tmp_path, known_file)
- except OSError as e:
- print(f"Error: no se pudo escribir '{known_file}': {e}", file=sys.stderr)
- try:
- os.unlink(tmp_path)
- except OSError:
- pass
- sys.exit(1)
- PYEOF
- ok "Marketplace limpiado de known_marketplaces.json"
- fi
- # Eliminar registro de installed_plugins.json si aún quedara rastro.
- if [ -f "${INSTALLED_FILE}" ]; then
- "${PYTHON_CMD}" - "${INSTALLED_FILE}" "${PLUGIN_KEY}" <<'PYEOF'
- import json, os, sys, tempfile
- installed_file, plugin_key = sys.argv[1:3]
- try:
- with open(installed_file, 'r') as f:
- data = json.load(f)
- except json.JSONDecodeError as e:
- print(f"Error: '{installed_file}' contiene JSON inválido: {e}", file=sys.stderr)
- sys.exit(1)
- except OSError as e:
- print(f"Error: no se pudo leer '{installed_file}': {e}", file=sys.stderr)
- sys.exit(1)
- if plugin_key in data.get('plugins', {}):
- del data['plugins'][plugin_key]
- # Escritura atómica
- try:
- tmp_fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(installed_file))
- with os.fdopen(tmp_fd, 'w') as f:
- json.dump(data, f, indent=2)
- os.replace(tmp_path, installed_file)
- except OSError as e:
- print(f"Error: no se pudo escribir '{installed_file}': {e}", file=sys.stderr)
- try:
- os.unlink(tmp_path)
- except OSError:
- pass
- sys.exit(1)
- PYEOF
- ok "Registro limpiado de installed_plugins.json"
- fi
- # Deshabilitar en settings.json si aún quedara rastro.
- if [ -f "${SETTINGS_FILE}" ]; then
- "${PYTHON_CMD}" - "${SETTINGS_FILE}" "${PLUGIN_KEY}" <<'PYEOF'
- import json, os, sys, tempfile
- settings_file, plugin_key = sys.argv[1:3]
- try:
- with open(settings_file, 'r') as f:
- data = json.load(f)
- except json.JSONDecodeError as e:
- print(f"Error: '{settings_file}' contiene JSON inválido: {e}", file=sys.stderr)
- sys.exit(1)
- except OSError as e:
- print(f"Error: no se pudo leer '{settings_file}': {e}", file=sys.stderr)
- sys.exit(1)
- if plugin_key in data.get('enabledPlugins', {}):
- del data['enabledPlugins'][plugin_key]
- # Escritura atómica
- try:
- tmp_fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(settings_file))
- with os.fdopen(tmp_fd, 'w') as f:
- json.dump(data, f, indent=2)
- os.replace(tmp_path, settings_file)
- except OSError as e:
- print(f"Error: no se pudo escribir '{settings_file}': {e}", file=sys.stderr)
- try:
- os.unlink(tmp_path)
- except OSError:
- pass
- sys.exit(1)
- PYEOF
- ok "Plugin limpiado de settings.json"
- else
- info "No se encontró settings.json (nada que deshabilitar)"
- fi
- printf "\n${GREEN}${BOLD}Alfred Dev desinstalado${NC}\n"
- printf " ${DIM}Reinicia Claude Code para aplicar los cambios.${NC}\n\n"
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.