# Technical Documentation: davila7/claude-code-templates

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/davila7/claude-code-templates)

### Overview (README.md)

[](https://www.npmjs.com/package/claude-code-templates)
[](https://www.npmjs.com/package/claude-code-templates)
[](https://opensource.org/licenses/MIT)
[](CONTRIBUTING.md)
[](https://z.ai/subscribe?ic=8JVLJQFSKB&utm_source=github&utm_medium=badge&utm_campaign=readme)
[](https://claude.com/contact-sales/claude-for-oss)
[](https://get.neon.com/4eCjZDz)
[](https://github.com/sponsors/davila7)
[](https://buymeacoffee.com/daniavila)
[](https://github.com/davila7/claude-code-templates)

<p align="center">
  <a href="https://trendshift.io/repositories/15113" target="_blank">
    <img src="https://trendshift.io/api/badge/repositories/15113" alt="davila7%2Fclaude-code-templates | Trendshift" style="width: 200px; height: 40px;" width="125" height="40"/>
  </a>
  <br />
  <br />
  <a href="https://vercel.com/oss">
  <img alt="Vercel OSS Program" src="https://vercel.com/oss/program-badge.svg" />
  </a>
  &nbsp;&nbsp;
  <a href="https://get.neon.com/4eCjZDz">
  <img alt="Neon Open Source Program" src="https://img.shields.io/badge/Neon-Open%20Source%20Program-00E599?style=for-the-badge" />
  </a>
  &nbsp;&nbsp;
  <a href="https://claude.com/contact-sales/claude-for-oss">
  <img alt="Claude for Open Source" src="docs/claude-oss-badge.svg" height="48" />
  </a>
</p>

---

<p align="center">
  <a href="https://www.swiftproxy.net/" target="_blank">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/swiftproxy-dark.png" />
      <source media="(prefers-color-scheme: light)" srcset="docs/sponsors/swiftproxy-light.png" />
      <img src="docs/sponsors/swiftproxy-light.png" alt="Swiftproxy" width="300" />
    </picture>
  </a>
</p>

<h3 align="center">Sponsored by <a href="https://www.swiftproxy.net/">Swiftproxy</a></h3>

<p align="center">
  <b>Swiftproxy proudly supports this project.</b><br />
  Connect your AI-powered workflows to reliable residential proxies for web data collection, browser automation, and AI-driven research.<br />
  90M+ residential IPs across 220+ locations, rotating and static residential proxies, with HTTP(S) and SOCKS5 support.
</p>

<p align="center">
  <a href="https://www.swiftproxy.net/">
    <img src="https://img.shields.io/badge/Get%2010%25%20off-code%20PROXY90-2563eb?style=for-the-badge" alt="Get 10% off with code PROXY90" />
  </a>
</p>

---

# Claude Code Templates ([aitmpl.com](https://aitmpl.com))

**Ready-to-use configurations for Anthropic's Claude Code.** A comprehensive collection of AI agents, custom commands, settings, hooks, external integrations (MCPs), and project templates to enhance your development workflow.

## Browse & Install Components and Templates

**[Browse All Templates](https://aitmpl.com)** - Interactive web interface to explore and install 100+ agents, commands, settings, hooks, and MCPs.

<img width="1787" height="958" alt="image" src="https://github.com/user-attachments/assets/d84feaa4-f871-4843-bbee-42d8f51b2f21" />


## 🚀 Quick Installation

```bash
# Install a complete development stack
npx claude-code-templates@latest --agent development-team/frontend-developer --command testing/generate-tests --mcp development/github-integration --yes

# Browse and install interactively
npx claude-code-templates@latest

# Install specific components
npx claude-code-templates@latest --agent development-tools/code-reviewer --yes
npx claude-code-templates@latest --command performance/optimize-bundle --yes
npx claude-code-templates@latest --setting performance/mcp-timeouts --yes
npx claude-code-templates@latest --hook git/pre-commit-validation --yes
npx claude-code-templates@latest --mcp database/postgresql-integration --yes
```

## What You Get

| Component | Description | Examples |
|-----------|-------------|----------|
| **🤖 Agents** | AI specialists for specific domains | Security auditor, React performance optimizer, database architect |
| **⚡ Commands** | Custom slash commands | `/generate-tests`, `/optimize-bundle`, `/check-security` |
| **🔌 MCPs** | External service integrations | GitHub, PostgreSQL, Stripe, AWS, OpenAI |
| **⚙️ Settings** | Claude Code configurations | Timeouts, memory settings, output styles |
| **🪝 Hooks** | Automation triggers | Pre-commit validation, post-completion actions |
| **🎨 Skills** | Reusable capabilities with progressive disclosure | PDF processing, Excel automation, custom workflows |

## 🛠️ Additional Tools

Beyond the template catalog, Claude Code Templates includes powerful development tools:

### 📊 Claude Code Analytics
Monitor your AI-powered development sessions in real-time with live state detection and performance metrics.

```bash
npx claude-code-templates@latest --analytics
```

### 💬 Conversation Monitor  
Mobile-optimized interface to view Claude responses in real-time with secure remote access.

```bash
# Local access
npx claude-code-templates@latest --chats

# Secure remote access via Cloudflare Tunnel
npx claude-code-templates@latest --chats --tunnel
```

### 🔍 Health Check
Comprehensive diagnostics to ensure your Claude Code installation is optimized.

```bash
npx claude-code-templates@latest --health-check
```

### 🔌 Plugin Dashboard
View marketplaces, installed plugins, and manage permissions from a unified interface.

```bash
npx claude-code-templates@latest --plugins
```

## 📖 Documentation

**[📚 docs.aitmpl.com](https://docs.aitmpl.com/)** - Complete guides, examples, and API reference for all components and tools.

## Contributing

We welcome contributions! **[Browse existing templates](https://aitmpl.com)** to see what's available, then check our [contributing guidelines](CONTRIBUTING.md) to add your own agents, commands, MCPs, settings, or hooks.

**Please read our [Code of Conduct](CODE_OF_CONDUCT.md) before contributing.**

## Attribution

This collection includes components from multiple sources:

**Scientific Skills:**
- **[K-Dense-AI/claude-scientific-skills](https://github.com/K-Dense-AI/claude-scientific-skills)** by K-Dense Inc. - MIT License (139 scientific skills for biology, chemistry, medicine, and computational research)

**Official Anthropic:**
- **[anthropics/skills](https://github.com/anthropics/skills)** - Official Anthropic skills (21 skills)
- **[anthropics/claude-code](https://github.com/anthropics/claude-code)** - Development guides and examples (10 skills)

**Community Skills & Agents:**
- **[obra/superpowers](https://github.com/obra/superpowers)** by Jesse Obra - MIT License (14 workflow skills)
- **[alirezarezvani/claude-skills](https://github.com/alirezarezvani/claude-skills)** by Alireza Rezvani - MIT License (36 professional role skills)
- **[wshobson/agents](https://github.com/wshobson/agents)** by wshobson - MIT License (48 agents)
- **NerdyChefsAI Skills** - Community contribution - MIT License (specialized enterprise skills)

**Commands & Tools:**
- **[awesome-claude-code](https://github.com/hesreallyhim/awesome-claude-code)** by hesreallyhim - CC0 1.0 Universal (21 commands)
- **[awesome-claude-skills](https://github.com/mehdi-lamrani/awesome-claude-skills)** - Apache 2.0 (community skills)
- **move-code-quality-skill** - MIT License
- **cocoindex-claude** - Apache 2.0

Each of these resources retains its **original license and attribution**, as defined by their respective authors.
We respect and credit all original creators for their work and contributions to the Claude ecosystem.

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🔗 Links

- **🌐 Browse Templates**: [aitmpl.com](https://aitmpl.com)
- **📚 Documentation**: [docs.aitmpl.com](https://docs.aitmpl.com)
- **💬 Community**: [GitHub Discussions](https://github.com/davila7/claude-code-templates/discussions)
- **🐛 Issues**: [GitHub Issues](https://github.com/davila7/claude-code-templates/issues)

## Stargazers over time
[](https://www.aitmpl.com/component/skill/git/star-history-chart)

---

**⭐ Found this useful? Give us a star to support the project!**

[](https://github.com/sponsors/davila7)

[](https://buymeacoffee.com/daniavila)

---

### README (`docs/README.md`)

# Claude Code Templates Website

This directory contains the static website for browsing and installing Claude Code configuration templates.

## Features

- **Dynamic Template Loading**: Templates are loaded directly from the GitHub repository's `templates.js` file
- **Interactive Cards**: Click any template card to see the installation command
- **Responsive Design**: Works on desktop and mobile devices
- **Framework Logos**: Uses Devicon CDN for professional programming language and framework logos
- **Copy to Clipboard**: Easy command copying with visual feedback

## Architecture

The website is built as a static site that:

1. **Fetches template data** from `cli-tool/src/templates.js` in the GitHub repository
2. **Parses the configuration** to extract available languages and frameworks
3. **Generates cards dynamically** with proper logos from Devicon CDN
4. **Updates automatically** when new templates are added to the repository

## Files

- `index.html` - Main HTML structure
- `styles.css` - Styling and responsive design
- `script.js` - JavaScript for dynamic content loading and interactions
- `_config.yml` - Jekyll configuration for GitHub Pages
- `README.md` - This documentation

## GitHub Pages Deployment

This website is automatically deployed to GitHub Pages when changes are pushed to the `docs/` directory in the main branch.

Visit: [https://davila7.github.io/claude-code-templates](https://davila7.github.io/claude-code-templates)

## Development

To test locally:

1. Clone the repository
2. Navigate to the `docs/` directory
3. Serve with any static file server (e.g., `python -m http.server 8000`)
4. Open `http://localhost:8000`

## Dependencies

- **Devicon CDN**: For programming language and framework logos
- **GitHub Raw Content**: For fetching template configurations
- **Modern Browser**: Support for ES6+ features and Fetch API

---

### Api README (`docs/api/README.md`)

# API Directory - Documentation

This directory contains **static files** for the Claude Code Templates project deployed on Vercel.

## 📁 Structure Overview

```
docs/api/
├── README.md     # This file
└── agents.json   # Static JSON file for agent queries
```

## 🔍 Why This Structure?

The project uses **TWO separate API directories**:

### 1. `/api/` (Root) - Serverless Functions ✅
```
/api/
├── track-download-supabase.js     # Serverless function
└── package.json                   # Dependencies
```

- **Purpose:** Vercel serverless functions (Edge Functions)
- **Auto-detected by Vercel:** Functions in `/api/` are automatically deployed
- **Runtime:** Node.js with ES Modules
- **URL:** `https://www.aitmpl.com/api/track-download-supabase`

### 2. `/docs/api/` - Static Files ✅
```
/docs/api/
├── README.md      # This documentation
└── agents.json    # Static data file
```

- **Purpose:** Static JSON files served with the frontend
- **Served from:** `outputDirectory: "docs"` in `vercel.json`
- **URL:** `https://www.aitmpl.com/api/agents.json`

## ⚠️ Important: Why Two Directories?

Vercel has a specific requirement:
- **Serverless functions MUST be in `/api/`** at the project root
- **Static files can be in `/docs/api/`** when using `outputDirectory: "docs"`

You **cannot** put serverless functions in `/docs/api/` - Vercel will serve them as static HTML files instead of executing them.

---

## 📄 Files in This Directory

### `agents.json` (Static File)
- **Type:** Static JSON data
- **Purpose:** Contains the list of available agents for the frontend
- **Accessed by:** Frontend application via fetch
- **URL:** `https://www.aitmpl.com/api/agents.json`
- **Size:** ~25KB
- **Updates:** Generated by `/scripts/generate_components_json.py` script

**Usage:**
```javascript
fetch('https://www.aitmpl.com/api/agents.json')
  .then(res => res.json())
  .then(data => console.log(data));
```

---

## 🔗 Related Files

### Serverless Functions (in `/api/`)

See `/api/README.md` for documentation on:
- `track-download-supabase.js` - Download tracking endpoint
- Environment variables required
- Request/response formats
- Database schema

---

## 📝 Best Practices

1. **Static Files:** Keep in `/docs/api/`
2. **Serverless Functions:** Keep in `/api/` (root)
3. **Never Mix:** Don't put serverless functions in `/docs/api/`
4. **Version Control:** Commit both directories separately

---

**Last Updated:** October 22, 2025
**Maintained by:** Claude Code Templates Team

---

### Blog README (`docs/blog/README.md`)

# Blog Management System

Este blog utiliza un sistema dinámico de gestión de artículos basado en JSON.

## 📁 Estructura de Archivos

```
docs/blog/
├── index.html              # Página principal del blog
├── blog-articles.json      # Base de datos de artículos
├── js/
│   └── blog-loader.js      # Cargador dinámico de artículos
└── assets/                 # Imágenes y recursos
```

## 🚀 Cómo Agregar Nuevos Artículos

Para agregar un nuevo artículo al blog, simplemente edita el archivo `blog-articles.json`:

### 1. Abre el archivo `blog-articles.json`

### 2. Agrega un nuevo objeto en el array `articles`:

```json
{
  "id": "unique-article-id",
  "title": "Título del Artículo",
  "description": "Descripción breve del artículo (1-2 líneas)",
  "url": "https://medium.com/@tu-usuario/url-del-articulo",
  "image": "https://www.aitmpl.com/blog/assets/imagen-cover.png",
  "category": "Categoría",
  "publishDate": "2025-02-10",
  "readTime": "5 min read",
  "tags": ["Tag1", "Tag2", "Tag3"],
  "platform": "medium",
  "order": 5
}
```

### 3. Actualiza los metadatos al final del archivo:

```json
"metadata": {
  "lastUpdated": "2025-02-10",
  "totalArticles": 5,
  "platforms": {
    "medium": 5,
    "local": 0
  }
}
```

## 📝 Campos Explicados

| Campo | Tipo | Descripción | Ejemplo |
|-------|------|-------------|---------|
| `id` | string | Identificador único del artículo | `"supabase-integration"` |
| `title` | string | Título completo del artículo | `"Claude Code + Supabase Integration"` |
| `description` | string | Descripción breve (1-2 líneas) | `"Learn how to integrate..."` |
| `url` | string | URL completa del artículo | `"https://medium.com/@..."` |
| `image` | string | URL de la imagen de portada | `"https://www.aitmpl.com/blog/assets/..."` |
| `category` | string | Categoría del artículo | `"Database"`, `"Development"`, etc. |
| `publishDate` | string | Fecha de publicación (YYYY-MM-DD) | `"2025-02-10"` |
| `readTime` | string | Tiempo estimado de lectura | `"5 min read"` |
| `tags` | array | Array de tags/etiquetas | `["Supabase", "Database", "MCP"]` |
| `difficulty` | string | Nivel de dificultad del artículo | `"basic"`, `"intermediate"`, `"advanced"` |
| `order` | number | Orden de aparición (menor = primero) | `1`, `2`, `3`, etc. |

## 🎨 Categorías Recomendadas

- **Database** - Artículos sobre bases de datos
- **Development** - Desarrollo general
- **Cloud & AI** - Cloud computing e inteligencia artificial
- **Documentation** - Documentación y guías
- **Frontend** - Desarrollo frontend
- **Backend** - Desarrollo backend
- **DevOps** - DevOps y CI/CD
- **Security** - Seguridad

## 🎓 Niveles de Dificultad

Clasifica cada artículo según su complejidad:

- **`basic`** - Verde (#00D084): Artículos introductorios, tutoriales para principiantes
- **`intermediate`** - Naranja (#FFA500): Requiere conocimientos previos, configuraciones más avanzadas
- **`advanced`** - Rojo (#FF4444): Temas complejos, integraciones avanzadas, arquitecturas elaboradas

El badge de dificultad se muestra automáticamente en la metadata del artículo.

## 🏷️ Tags Recomendados

Usa tags específicos y relevantes:
- Tecnologías: `Supabase`, `Next.js`, `React`, `Node.js`
- Conceptos: `Agents`, `Commands`, `MCP`, `Automation`
- Herramientas: `Git`, `Docker`, `Kubernetes`
- Plataformas: `Vercel`, `Google Cloud`, `AWS`

## 📊 Orden de Artículos

Los artículos se muestran según el campo `order`:
- **Menor número = Aparece primero**
- Usa números consecutivos: 1, 2, 3, 4, 5...
- Para reordenar, simplemente cambia los números

## 🔄 Proceso de Publicación

1. **Publica tu artículo** en Medium u otra plataforma
2. **Copia la URL** del artículo publicado
3. **Edita** `blog-articles.json`
4. **Agrega** el nuevo artículo con todos los campos
5. **Actualiza** los metadatos (totalArticles, lastUpdated)
6. **Commit y push** los cambios

```bash
git add docs/blog/blog-articles.json
git commit -m "Add new blog article: [Título]"
git push
```

## 🎯 Badges de Dificultad

El sistema automáticamente muestra un badge de dificultad con colores específicos:
- **Basic** (Verde): Para artículos introductorios y guías básicas
- **Intermediate** (Naranja): Para configuraciones más avanzadas
- **Advanced** (Rojo): Para temas complejos y arquitecturas avanzadas

## ✨ Características

- **Carga Dinámica**: Los artículos se cargan automáticamente desde JSON
- **Ordenamiento**: Controla el orden con el campo `order`
- **Seguridad**: HTML escapado automáticamente (prevención XSS)
- **Performance**: Lazy loading de imágenes
- **Responsive**: Diseño adaptable a móviles
- **Loading States**: Indicadores de carga mientras se obtienen los datos

## 🐛 Troubleshooting

### Los artículos no se cargan
1. Verifica que `blog-articles.json` esté en la raíz de `/docs/blog/`
2. Revisa la consola del navegador para errores
3. Asegúrate de que el JSON sea válido (usa un validador JSON online)

### Error de JSON inválido
- Verifica que todas las comillas sean dobles (`"`)
- Asegúrate de que no falten comas entre objetos
- El último elemento del array no debe tener coma final

### Las imágenes no se muestran
- Verifica que las URLs de las imágenes sean accesibles
- Usa URLs completas (no relativas)
- Asegúrate de que las imágenes estén en `/docs/blog/assets/`

## 📱 Testing Local

Para probar localmente:

```bash
cd docs/blog
python -m http.server 8000
# o
npx http-server
```

Luego abre: `http://localhost:8000`

## 🎉 Ejemplo Completo

```json
{
  "articles": [
    {
      "id": "my-new-article",
      "title": "Amazing New Feature in Claude Code",
      "description": "Discover how to use the latest feature that will revolutionize your workflow.",
      "url": "https://medium.com/@dan.avila7/amazing-new-feature-12345",
      "image": "https://www.aitmpl.com/blog/assets/new-feature-cover.png",
      "category": "Development",
      "publishDate": "2025-02-10",
      "readTime": "6 min read",
      "tags": ["Claude Code", "Productivity", "Automation"],
      "difficulty": "intermediate",
      "order": 1
    }
  ],
  "metadata": {
    "lastUpdated": "2025-02-10",
    "totalArticles": 5,
    "difficultyLevels": {
      "basic": 2,
      "intermediate": 2,
      "advanced": 1
    }
  }
}
```

---

**¡Eso es todo!** Ahora puedes agregar artículos fácilmente sin tocar el HTML. 🚀

---

### Cli Tool Components Skills Ai Research Loki Mode Docs Screenshots README (`cli-tool/components/skills/ai-research/loki-mode/docs/screenshots/README.md`)

# Dashboard Screenshots

This directory contains screenshots for the Loki Mode README.

---

## Required Screenshots

### 1. `dashboard-agents.png`

**What to capture:** The agent monitoring section of the Loki Mode dashboard showing active agents.

**How to create:**
1. Run Loki Mode with a test project:
   ```bash
   cd /path/to/test/project
   ../../autonomy/run.sh examples/simple-todo-app.md
   ```

2. Open the dashboard:
   ```bash
   open .loki/dashboard/index.html
   ```

3. Wait for agents to spawn (should happen within 30-60 seconds)

4. Take a screenshot of the **"Active Agents" section** showing:
   - Multiple agent cards (ideally 5-8 visible)
   - Agent IDs and types (e.g., "eng-frontend", "qa-001-testing")
   - Model badges (Sonnet, Haiku, Opus) with color coding
   - Current work being performed
   - Runtime and tasks completed stats
   - Status indicators (active/completed)

**Recommended size:** 1200px wide (use browser zoom to fit multiple agents)

**Save as:** `dashboard-agents.png`

---

### 2. `dashboard-tasks.png`

**What to capture:** The task queue kanban board section.

**How to create:**
1. Using the same running Loki Mode instance from above

2. Scroll down to the **"Task Queue" section**

3. Take a screenshot showing all four columns:
   - **Pending** (left column, ideally with 3-5 tasks)
   - **In Progress** (should have at least 1 task)
   - **Completed** (should show several completed tasks)
   - **Failed** (can be empty, that's fine)

4. Ensure the screenshot shows:
   - Column headers with count badges
   - Task cards with IDs, types, and descriptions
   - Clear separation between columns

**Recommended size:** 1200px wide

**Save as:** `dashboard-tasks.png`

---

## Screenshot Specifications

- **Format:** PNG (for quality and transparency support)
- **Resolution:** At least 1200px wide, retina/2x if possible
- **Browser:** Use Chrome or Firefox for consistent rendering
- **Zoom:** Adjust browser zoom to fit content nicely (90-100%)
- **Clean State:** Ensure no browser extensions visible, clean URL bar

---

## Testing the Screenshots

After adding screenshots, verify they display correctly in the README:

```bash
# View the README with screenshots
open README.md
# or use a Markdown viewer
```

Check that:
- [ ] Images load without errors
- [ ] Resolution is clear and readable
- [ ] Colors match the Loki Mode design (cream background, coral accents)
- [ ] Text in screenshots is legible

---

## Placeholder Images

If you don't have live agent data yet, you can use the test data provided in this repository:

```bash
# Create test agent data
cd /Users/lokesh/git/jobman  # or any test project
mkdir -p .agent/sub-agents .loki/state .loki/queue

# Copy test data from Loki Mode repo
cp ~/git/loki-mode/tests/fixtures/agents/*.json .agent/sub-agents/
cp ~/git/loki-mode/tests/fixtures/queue/*.json .loki/queue/

# Generate dashboard
~/git/loki-mode/autonomy/run.sh --generate-dashboard-only

# Open dashboard
open .loki/dashboard/index.html
```

---

## Current Status

- [ ] `dashboard-agents.png` - Not yet created
- [ ] `dashboard-tasks.png` - Not yet created

Once screenshots are added, update this checklist and commit:

```bash
git add docs/screenshots/*.png
git commit -m "Add dashboard screenshots for README"
```

---

## Alternative: Create Mock Screenshots

If you want to create mock/placeholder screenshots quickly:

1. Use the test fixture data (see above)
2. Edit `.loki/state/agents.json` to add more agents
3. Edit `.loki/queue/*.json` to populate task columns
4. Refresh dashboard and capture screenshots

This gives you polished screenshots without waiting for a full Loki Mode run.

---

**Note:** Screenshots should demonstrate Loki Mode's capabilities while being clean and professional. Avoid showing:
- Personal information or API keys
- Error states (unless specifically demonstrating error handling)
- Cluttered or confusing data

The goal is to show potential users what the dashboard looks like during normal operation.

---

### CLAUDE (`docs/CLAUDE.md`)

# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

This directory contains the static website (aitmpl.com) that serves as the public web interface for browsing and installing Claude Code components. The site is a vanilla JavaScript application that loads component data dynamically and provides an interactive browsing experience for 500+ components including agents, commands, settings, hooks, MCPs, and templates.

## Development Commands

### Local Development
```bash
# Serve locally with any static file server
python -m http.server 8000
# or
npx http-server

# Open browser to http://localhost:8000
```

### Component Data Generation
```bash
# From project root - regenerate components.json
cd ..
python scripts/generate_components_json.py

# This creates/updates docs/components.json with all components
```

### Deployment
- Site is automatically deployed to GitHub Pages when changes are pushed to `docs/` directory
- Deployed at: https://aitmpl.com (davila7.github.io/claude-code-templates)
- Vercel configuration in `vercel.json` for routing

## Architecture

### Data Flow
1. **Component Generation**: Python script (`scripts/generate_components_json.py`) scans `cli-tool/components/` and generates `docs/components.json` (~2MB file with embedded content)
2. **Static Loading**: Website loads `components.json` on page load (with mobile optimization and progress indicators)
3. **Dynamic Rendering**: JavaScript renders component cards based on user filters and search
4. **Download Tracking**: Supabase integration tracks component installations via backend API

### Key Files

#### HTML Pages
- `index.html` - Main page with component browser and search
- `component.html` - Individual component detail pages
- `plugin.html` - Plugin marketplace interface
- `trending.html` - Trending components dashboard
- `download-stats.html` - Analytics and download statistics

#### JavaScript Architecture (`js/`)
- `data-loader.js` - Loads and caches components.json, handles data fetching
- `search-functionality.js` - Real-time search across all components with fuzzy matching
- `cart-manager.js` - Shopping cart for batch component installation
- `stack-router.js` - Client-side routing for company stacks and plugins
- `index-events.js` - Event handlers for filters, modals, and user interactions
- `plugin-page.js` - Plugin marketplace functionality
- `trending.js` - Trending components data visualization

#### CSS (`css/`)
- Modular CSS with separate files for components, modals, responsive design
- Terminal-themed design system with monospace fonts and CLI aesthetics

#### Data Files
- `components.json` - Main component catalog (~2MB, generated file)
- `trending-data.json` - Trending components rankings
- `claude-jobs.json` - Job postings data

### Component System

#### Component Types
Each component type has specific structure:

**Agents** (162 total)
- AI specialists organized by category (Development, Data/AI, Security, Business, etc.)
- Stored in `cli-tool/components/agents/{category}/{name}.md`
- Installation: `--agent <name>`

**Commands** (210 total)
- Custom slash commands organized by category
- Stored in `cli-tool/components/commands/{category}/{name}.md`
- Installation: `--command <name>`

**Settings** (60 total)
- Claude Code configuration files
- Includes statuslines with accompanying Python scripts
- Stored in `cli-tool/components/settings/{category}/{name}.json`
- Installation: `--setting <name>`

**Hooks** (39 total)
- Event-driven automation triggers
- Stored in `cli-tool/components/hooks/{category}/{name}.md`
- Installation: `--hook <name>`

**MCPs** (55 total)
- Model Context Protocol integrations
- Stored in `cli-tool/components/mcps/{name}.json`
- Installation: `--mcp <name>`

**Templates** (14 total)
- Complete project configurations
- Organized by language and framework in `cli-tool/templates/`
- Installation: `--template <language>`

**Plugins** (10 total)
- Component bundles with marketplace metadata
- Defined in `.claude-plugin/marketplace.json`
- Installation: `--plugin <name>`

### Data Loading Strategy

The site implements a multi-stage loading strategy for optimal mobile performance:

1. **Initial Load**: Show loading indicator with progress bar
2. **Lazy Parsing**: Load components.json in chunks to avoid blocking
3. **Progressive Rendering**: Render visible cards first, lazy-load others
4. **Search Indexing**: Build search index in background
5. **Caching**: LocalStorage caching for repeat visits

### Search Functionality

Real-time search across all components:
- **Fuzzy Matching**: Tolerates typos and partial matches
- **Multi-field Search**: Searches name, description, category, type
- **Filter Integration**: Combines with type filters (agents/commands/etc)
- **Category Filtering**: Dynamic category chips based on active filter
- **Sorting**: Alphabetical or by download count

### Shopping Cart System

Batch installation builder:
- Add multiple components across types (agents, commands, settings, hooks, MCPs)
- Generates single NPX command for installation
- Supports sharing cart via URL parameters
- Social sharing to Twitter/Threads

### Plugin Marketplace

Plugin system for component bundles:
- Each plugin contains agents, commands, and MCPs
- Defined in marketplace.json with metadata
- Installation installs all plugin components
- Examples: `supabase-toolkit`, `nextjs-vercel-pro`, `ai-ml-toolkit`

### Download Analytics

Supabase-powered analytics:
- Tracks component installations via API endpoints
- Aggregates download counts by component and type
- Displays trending components and download stats
- Real-time updates with background refresh

## Important Implementation Patterns

### Component Data Structure

```javascript
// components.json structure
{
  "agents": [{
    "name": "agent-name",
    "category": "category-name",
    "content": "Full markdown content...",
    "path": "agents/category/agent-name.md",
    "url": "https://github.com/..."
  }],
  "commands": [...],
  "mcps": [...],
  "settings": [...],
  "hooks": [...],
  "templates": [...],
  "plugins": [...]
}
```

### Dynamic Component Loading

```javascript
// Loading pattern from data-loader.js
async function loadAllComponentsData() {
  const response = await fetch('components.json');
  const data = await response.json();
  componentsData = data;
  collectAvailableCategories();
  generateUnifiedComponentCards();
}
```

### Filter and Category System

```javascript
// Current filter state
let currentFilter = 'agents'; // or 'commands', 'mcps', etc.
let currentCategoryFilter = 'all'; // or specific category

// Update filters
function handleFilterClick(event, filter) {
  currentFilter = filter;
  updateCategorySubFilters();
  generateUnifiedComponentCards();
}
```

### Installation Command Generation

```javascript
// Pattern from cart-manager.js
function generateCartCommand(cart) {
  const flags = [];
  if (cart.agents.length) flags.push(...cart.agents.map(a => `--agent ${a}`));
  if (cart.commands.length) flags.push(...cart.commands.map(c => `--command ${c}`));
  // ... other types
  return `npx claude-code-templates@latest ${flags.join(' ')} --yes`;
}
```

## File Generation Workflow

### Updating Component Catalog

When components are added/modified in `cli-tool/components/`:

1. Run component generation script:
   ```bash
   cd /path/to/project/root
   python scripts/generate_components_json.py
   ```

2. This script:
   - Scans all directories in `cli-tool/components/`
   - Scans all templates in `cli-tool/templates/`
   - Fetches download stats from Supabase
   - Embeds file content inline
   - Excludes Python scripts from public listings (but includes them as dependencies)
   - Generates `docs/components.json`

3. Commit changes:
   ```bash
   git add docs/components.json
   git commit -m "Update component catalog"
   ```

### Testing Locally

Before committing:
1. Serve site locally: `python -m http.server 8000`
2. Test component loading and search
3. Verify filter functionality
4. Check responsive design on mobile
5. Test cart and installation command generation

## SEO and Metadata

### Structured Data
- Schema.org markup for SoftwareApplication
- Open Graph tags for social sharing
- Twitter Card metadata
- Sitemap.xml for search engines

### Performance Optimization
- Cache-busting query parameters for dynamic content
- Progressive loading for large JSON files
- LocalStorage caching for repeat visits
- Lazy loading for images and components below fold

## External Integrations

### GitHub API
- Fetches component files dynamically (legacy, now uses components.json)
- Links to source files on GitHub

### Supabase
- Tracks component downloads
- Aggregates download statistics
- Powers trending components

### Vercel
- Handles routing for SPA-style URLs
- Configured in `vercel.json`

### Analytics
- Hotjar for user behavior tracking
- Counter.dev for page view analytics

## Deployment Checklist

Before deploying to production:

1. **Component Data**: Run `python scripts/generate_components_json.py` to update components.json
2. **Test Locally**: Verify all pages load correctly
3. **Check Links**: Ensure GitHub links point to correct paths
4. **Verify Search**: Test search functionality with various queries
5. **Mobile Testing**: Check responsive design on multiple devices
6. **Cart Testing**: Verify installation commands are generated correctly
7. **Analytics**: Confirm tracking is working

## Common Development Tasks

### Adding New Component Type

1. Update `scripts/generate_components_json.py` to scan new component directory
2. Add new filter button in `index.html`
3. Add icon configuration in `js/script.js` typeConfig
4. Update cart-manager.js to handle new type
5. Regenerate components.json

### Modifying Search Behavior

Edit `js/search-functionality.js`:
- `performSearch()` - Main search logic
- `fuzzyMatch()` - Matching algorithm
- `highlightMatches()` - Result highlighting

### Updating Styles

CSS is modular:
- `css/styles.css` - Main styles and variables
- `css/components.css` - Component cards and grid
- `css/responsive.css` - Mobile breakpoints
- `css/modals.css` - Modal dialogs
- `css/cart.css` - Shopping cart sidebar

## Browser Compatibility

- Modern browsers (Chrome, Firefox, Safari, Edge)
- ES6+ JavaScript features (Fetch API, async/await, template literals)
- CSS Grid and Flexbox for layout
- No build step required (vanilla JavaScript)

## Performance Considerations

### Large File Handling
- `components.json` is ~2MB - implement progressive loading
- Use virtual scrolling for large component lists
- Debounce search input to avoid excessive filtering
- Cache parsed JSON in memory after initial load

### Mobile Optimization
- Lazy load images and component content
- Reduce initial bundle size
- Minimize re-renders during search/filter
- Use CSS animations sparingly

## Troubleshooting

### Components Not Loading
- Check browser console for fetch errors
- Verify components.json is accessible
- Ensure CORS is properly configured
- Check GitHub API rate limits (if using legacy loading)

### Search Not Working
- Verify search index is built correctly
- Check fuzzy match threshold in search-functionality.js
- Ensure component data includes searchable fields

### Cart Not Saving
- Check LocalStorage is enabled
- Verify cart data structure matches expected format
- Clear cache and reload if data structure changed

This website serves as the primary user interface for the Claude Code Templates ecosystem, providing an intuitive way to discover and install 500+ components through a terminal-themed, responsive web interface.

---

### Catalog Api Formalization (`docs/catalog-api-formalization.md`)

# Catalog JSON as a public API: audit and formalization proposal

Status: proposal for review. Nothing in this document has been implemented.
Audit date: 2026-10-21, against `main` at `08a04c6`.

Scope of this pass: read-only audit plus a proposal. The existing JSON URLs,
their schema and `scripts/generate_components_json.py` are unchanged.

---

## TL;DR

- There is not one catalog JSON but **seven public JSON surfaces**, served from
  two hosts (aitmpl.com and raw.githubusercontent.com). The two known external
  consumers read **different files on different hosts**: niche-db reads
  `docs/components.json` straight from GitHub, the `/aitmpl` mod reads the
  dashboard's per-type slices from www.aitmpl.com.
- The `/aitmpl` mod is not really third-party. It is **our own mod**
  (`cli-tool/components/mods/productivity/aitmpl`, added in #915 on
  2026-09-17); the abdullahdev38 repo is a plain fork carrying an older copy
  (v0.1.1, upstream is v0.4.0). Every user who ran `--mod productivity/aitmpl`
  has a frozen copy in `.claude/skills/aitmpl/` that we cannot update. That
  makes it the consumer most exposed to a format change, and one we own.
- Serving is already better than "informal" suggests: every catalog file on
  aitmpl.com has `Access-Control-Allow-Origin: *`, a 5 minute
  `Cache-Control`, and (inferred) a Cloudflare Pages ETag. `/openapi.json`
  (#1200) already describes five of the files. What is missing is a
  **version, a schema that is enforced, a stability policy, and a changelog**.
- The current shape has warts a contract should not freeze: a `type` of
  `"sandbo"`, a `security` object that is `validated: false` on all 1,922
  components, empty strings instead of nulls, a `componentsMarketplace` block
  with 8 stale agents, `templates`/`plugins` groups that are retired or empty,
  and a malformed timestamp in `trending-data.json`.
- **Recommendation: formalize**, with a new versioned surface
  (`/api/v1/catalog.json` + per-type slices + `schema.json` + a tiny
  `version.json` for cheap polling), generated alongside the legacy files,
  validated in CI. Legacy URLs keep working unchanged; they are declared
  internal to the site, not frozen. MVP is about 2 to 2.5 days of work.

---

# Phase 1: Audit

## 1. Where the catalog comes from

### Generation

| Step | What runs | Writes |
|---|---|---|
| Content refresh | `.github/workflows/update-component-content.yml` on every push to `main` touching `cli-tool/components/**` (or the generator). Runs `generate_components_json.py --skip-downloads`, commits, then dispatches `deploy.yml`. | all catalog files below |
| Daily refresh | `.github/workflows/update-json-data.yml`, cron `0 3 * * *` UTC. Runs `generate_components_json.py` (pulls download counts from Supabase `component_downloads`) and `generate_trending_data.py`, copies `docs/trending-data.json` to `dashboard/public/`, rebuilds its commit on fresh `main` if needed (#1141), dispatches `deploy.yml`. | all catalog files + trending |
| Deploy | `.github/workflows/deploy.yml`: `astro build` + `wrangler pages deploy dist --project-name=aitmpl-dashboard`. Runs no Python; the committed files are the only source. | www.aitmpl.com |

`scripts/generate_components_json.py` (1,084 lines) scans
`cli-tool/components/{type}/{category}/*`, parses frontmatter (YAML with a
line-parser fallback since #1070), merges download counts (full-table keyset
pagination since #1005), attaches SkillSpector results (#1204), then writes:

1. `dashboard/public/component-content/{type}/{category}/{name}.json` (per component, `content` + `files` for mods)
2. `docs/components.json` (full index minus `content`/`files`, keeps `security` and `skillspector.hash`, pretty-printed)
3. `dashboard/public/components.json` (same minus `security`, minus `skillspector.hash`, minified)
4. `dashboard/public/counts.json`
5. `dashboard/public/components/{type}.json` (one per top-level key of #3)
6. `dashboard/public/search-index.json`

`trending-data.json` comes from `scripts/generate_trending_data.py` (Supabase,
daily only).

**Update cadence in practice:** content changes several times a day (every
component merge), download counts and trending once a day after 03:00 UTC.
There is no fixed publication time and no "generated at" field in any
catalog file except `trending-data.json`.

### Public URLs, size, headers

Sizes are from the committed files at `08a04c6`; gzip sizes measured locally
with Python's `gzip` (Cloudflare may serve Brotli, which is smaller).

| URL | Source file | Raw | gzip | Who reads it |
|---|---|---|---|---|
| `https://www.aitmpl.com/components.json` | `dashboard/public/components.json` | 2.32 MB | 418 KB | dashboard SSR (`lib/data.ts`), `PUBLIC_COMPONENTS_JSON_URL` |
| `https://www.aitmpl.com/components/{type}.json` (11 files) | `dashboard/public/components/*.json` | agents 766 KB, skills 1.08 MB | agents 176 KB | `ComponentGrid.tsx`, WebMCP, **`/aitmpl` mod** |
| `https://www.aitmpl.com/counts.json` | `dashboard/public/counts.json` | 160 B | | `Sidebar.astro`, `llms.txt`, WebMCP, **`/aitmpl` mod** |
| `https://www.aitmpl.com/search-index.json` | `dashboard/public/search-index.json` | 1.17 MB | 308 KB | `SearchModal.tsx` |
| `https://www.aitmpl.com/component-content/{type}/{category}/{name}.json` | `dashboard/public/component-content/**` | per file | | detail pages, Send-to-repo |
| `https://www.aitmpl.com/trending-data.json` | `dashboard/public/trending-data.json` | 30 KB | 4 KB | `TrendingView.tsx`, home counters, WebMCP, **`/aitmpl` mod** |
| `https://raw.githubusercontent.com/davila7/claude-code-templates/main/docs/components.json` | `docs/components.json` | 3.32 MB | 476 KB | **niche-db**, `daily-component-discord.yml` (jq), legacy `docs/` site |
| `https://davila7.github.io/claude-code-templates/components.json` | `docs/components.json` via GitHub Pages | same | | legacy site only (as far as found) |
| `https://aitmpl.com/api/agents.json` | none on Cloudflare Pages | | | first-party CLI fallback, see §4 |

**Headers on aitmpl.com**, from `dashboard/public/_headers` (configured, not
observed: the container proxy blocks aitmpl.com, so no live request was made):

| Path | Cache-Control | CORS | Content-Type | ETag / Last-Modified |
|---|---|---|---|---|
| `/components.json`, `/counts.json`, `/components/*`, `/search-index.json`, `/component-content/*` | `public, max-age=300, stale-while-revalidate=3600` (since #1228) | `Access-Control-Allow-Origin: *`, `Access-Control-Allow-Methods: GET` | not set in `_headers`; inferred `application/json` from the extension (Pages default) | not set in `_headers`; **inferred**: Pages sends an `ETag` on static assets and answers `If-None-Match` with 304 (the `_headers` comment relies on this). No `Last-Modified` is expected. |
| `/trending-data.json` | `public, max-age=3600, stale-while-revalidate=300` | same | inferred | inferred |
| `/openapi.json` | `public, max-age=86400, ...` | same | `application/json; charset=utf-8` (explicit) | inferred |
| all paths (`/*`) | | | | plus `X-Content-Type-Options: nosniff`, HSTS, `X-Frame-Options: DENY` |

No `Access-Control-Expose-Headers`, so a browser consumer cannot read the
`ETag` from JS (the browser's own cache still revalidates with it).

**Headers on raw.githubusercontent.com** are GitHub's, not ours, and not
observed here: from general knowledge it serves `text/plain; charset=utf-8`,
`Cache-Control: max-age=300`, an `ETag`, and `Access-Control-Allow-Origin: *`.
We cannot add headers, versioning or deprecation notices to that URL.

### Existing machine-readable docs

- `/openapi.json` (#1200, `info.version: 1.0.0`) documents `/search-index.json`,
  `/components/{type}.json`, `/component-content/...`, `/counts.json`,
  `/trending-data.json`. It does **not** document `/components.json` or the
  GitHub `docs/components.json`. Its description says responses are "cached at
  the edge for up to 24 hours", which is stale since #1228 (5 minutes).
  Its `Component` schema lists 6 of the 12 fields actually served and marks
  none as required beyond `type`, `name`, `path`; `ComponentType` lists
  `sandbox` but not that its `type` value is `sandbo`.
- `/llms.txt` points agents at `/openapi.json`.
- `/api/*` is caught by `dashboard/src/pages/api/[...path].ts`, which returns a
  JSON 404 pointing at `/openapi.json`. This matters for the proposed
  `/api/v1/` path (§7).

## 2. Current schema

### `docs/components.json` and `dashboard/public/components.json`

Top-level object. Counts at `08a04c6`:

| Key | Type | Count | Notes |
|---|---|---|---|
| `agents` | `Component[]` | 422 | |
| `commands` | `Component[]` | 288 | |
| `mcps` | `Component[]` | 107 | |
| `settings` | `Component[]` | 77 | |
| `hooks` | `Component[]` | 63 | |
| `sandbox` | `Component[]` | 11 | entries are docs and config files (`README.md`, `package.json`, `tsconfig.json`), not components; `type` is `"sandbo"` |
| `skills` | `Component[]` | 891 | |
| `loops` | `Component[]` | 18 | |
| `mods` | `Component[]` | 45 | was `function-hooks` until #910 (2026-09-16) |
| `templates` | `Template[]` | 14 | different shape, no `path`; retired on the site |
| `plugins` | `Plugin[]` | 0 | always empty: the generator reads `.claude-plugin/marketplace.json`, which does not exist |
| `componentsMarketplace` | object | `{agents: [8]}` | copy of `cli-tool/components/.claude-plugin/marketplace.json`; 8 agents, unrelated to the 422 above |
| `marketplace` | object | absent | written only if `.claude-plugin/marketplace.json` exists |

Every group is sorted by `path` (templates and plugins by `name`). Order is
alphabetical, never by downloads or anything else.

**`Component`** (all 9 component groups):

| Field | Type | Present | Notes |
|---|---|---|---|
| `name` | string | always | equals the last path segment without extension (holds for all 1,922 today). **Not unique within a type**: 12 agent names, 16 skill names, 2 command names repeat across categories. |
| `path` | string | always | `{category}/{name}.md` (agents, commands, loops, sandbox), `{category}/{name}.json` (mcps, settings, hooks), `{category}/{name}` (skills, mods: directories). Unique within a type. **This is the only real key.** |
| `category` | string | always | equals the first path segment (holds for all today). Free-form directory name, no fixed list. |
| `type` | string | always | singular of the group key via `component_type[:-1]`, hence `sandbo`. |
| `description` | string | always | Verbatim frontmatter / JSON description. 129 agents and 53 commands keep surrounding quotes or literal `\n`; many agent descriptions embed `<example>` blocks of several KB; 73 are empty strings. |
| `author`, `repo`, `version`, `license` | string | always | `""` when unknown, which is the norm (author empty on 1,668 of 1,922, repo on 1,871). |
| `keywords` | string[] | always | usually `[]` |
| `downloads` | integer | always | total installs from Supabase, full-table since #1005 (2026-09-26); before that partial. Changes daily. |
| `security` | object | `docs/` only | `{validated, valid, score, errorCount, warningCount, lastValidated}`. **`validated: false, valid: null, score: null` on all 1,922 components**: the field is dead. |
| `skillspector` | object | always (since #1204, 2026-10-18) | `{score, severity: LOW\|MEDIUM\|HIGH\|CRITICAL, recommendation, issueCount, analysis: complete\|partial, findings[≤5], version, scannedAt, hash}`; `hash` only in `docs/`. Display-only by project rule. New and likely to change. |
| `references` | string[] | skills, mods | relative file list of the directory |
| `modules` | string[] | mods | hooks-module filenames |
| `userConfig` | object | mods | copy of `plugin.json` `userConfig` |

**`Template`**: `name, id, type: "template", subtype, category, language?
(8 of 14), description, files[] (docs only), installCommand, downloads`.

### `dashboard/public/components/{type}.json`

A bare JSON array, identical to the matching group of
`dashboard/public/components.json`. Files exist for all 11 list groups
(`plugins.json` is `[]`). No envelope, no version, no timestamp.

### `counts.json`

`{ "agents": 422, ..., "templates": 14, "plugins": 0 }`: one key per list
group of `components.json`. Includes `sandbox`, `templates` and `plugins`, so
its sum (1,936) is not the number of browsable components.

### `search-index.json`

Flat array of `{type, name, path, description, category}` across all groups,
templates included (with `path: null`).

### `component-content/{type}/{category}/{name}.json`

`{ content: string, files?: {relPath: string} }`. Slug is `path` with `.md`
/ `.json` stripped.

### `trending-data.json`

`{ lastUpdated, globalStats: {totalComponents, totalDownloads,
monthlyDownloads, weeklyDownloads, todayDownloads, totalCountries},
topCountries[], trending: {commands, mcps, agents, settings, hooks, templates,
skills, mods, loops, all: [...]}, chartData }`. Trending rows are
`{id: "{singular}-{name}", name, category, downloadsToday, downloadsWeek,
downloadsMonth, downloadsTotal}`. `lastUpdated` is malformed:
`2026-10-21T03:13:53.368524+00:00Z` (offset **and** `Z`), which strict
ISO 8601 parsers reject.

### Inconsistencies and things likely to change

1. Type naming has three spellings: plural group keys (`agents`), singular
   `type` values (`agent`, `sandbo`), and CLI flags (`--agent`, `--mcp`).
   Consumers rebuild the mapping themselves (both known consumers hard-code it).
2. `name` is not unique; consumers that key on `{type, name}` collide.
3. `security` is dead but still published in `docs/`; niche-db republishes
   it as `securityValidated: false` for every component.
4. `skillspector` is two days old, display-only, and its findings list and
   severity bands will evolve.
5. `sandbox`, `templates`, `plugins`, `componentsMarketplace` are leftovers.
6. Empty string vs missing vs null is not defined.
7. `docs/` is described in CLAUDE.md as the "legacy static site". Any cleanup
   that removes `docs/components.json` breaks niche-db with no warning.
8. Install commands and page URLs are not in the data; every consumer builds
   them from `type`, `category` and `name`.
9. Sponsored placements: **not in any catalog file.** They come only from
   `GET /api/ads/active` (`{ads: [{component_type, component_path,
   component_name, ends_at}]}`, empty while `PUBLIC_ADS_ENABLED` is unset)
   and are merged client-side by `dashboard/src/lib/ads.ts`. Good, and the
   formal contract should keep it that way explicitly (§6).

## 3. Known consumers

### 3a. `/aitmpl` mod (ours; forked copy at abdullahdev38/claude-code-templates)

Source: `cli-tool/components/mods/productivity/aitmpl/hooks/{register.tsx,catalog.ts}`
upstream (v0.4.0); the fork holds v0.1.1 from #915. Both versions read the
same URLs and fields. Installed copies on users' machines are frozen at
whatever version they installed (46 recorded downloads).

| Reads | Host | Fields / structure relied on |
|---|---|---|
| `{siteUrl}/counts.json` | www.aitmpl.com (option `siteUrl`) | top-level object of numbers keyed by plural type |
| `{siteUrl}/components/{type}.json` for `agents, commands, mcps, settings, hooks, skills, loops, mods` | www.aitmpl.com | **body must be an array** (throws otherwise); per row `name` (required, string), `path` (optional string), `category`, `description`, `downloads` (number). Sorts by `downloads` client-side. |
| `{siteUrl}/trending-data.json` | www.aitmpl.com | `globalStats.{totalComponents,totalDownloads,weeklyDownloads,totalCountries}`; `trending.all[]` rows with `id` = `{singular}-{name}`, `name`, `category`, `downloadsWeek`. Derives the type by stripping `-{name}` from `id` and matching `--{prefix}` to its CLI flag table. |
| `{siteUrl}/component/{type}/{category}/{name}` | www.aitmpl.com | the detail page route, opened in the browser |
| `npx claude-code-templates@latest --{flag} {category}/{name}` | npm | built from `path` minus extension, validated against `[A-Za-z0-9._-]` segments |

### 3b. niche-db (profullstack/niche-db)

Source: `packages/adapters/src/aitmpl.js`, added in 41d1592 (2026-09-25),
refactored in 3d6f803 (2026-10-04) into six adapters.

| Reads | Host | Fields / structure relied on |
|---|---|---|
| `https://raw.githubusercontent.com/davila7/claude-code-templates/main/docs/components.json`, fetched once per adapter (6 times per cycle, cadence 8 h for skills/agents, 12 h for the rest) | GitHub | top-level groups `skills, agents, commands, hooks, settings, loops, mods, mcps` (`index[group] ?? []`); per row `name` and `path` (row dropped if either is empty), `category`, `description` (strips quotes and whitespace), `keywords` (array, first 10), `author`, `repo`, `version`, `license` (empty string → null), `downloads` (`Number.isFinite`), `security.validated`, `security.score` |
| derived | | `externalId = aitmpl:{group}:{path}` (their dedupe key), source URL `github.com/.../blob/main/cli-tool/components/{group}/{path}`, install command `--{kind} {category}/{name}` with `mcp-config` mapped to `--mcp` |

They explicitly skip `sandbox` (citing the `sandbo` type) and `templates`
(no `path`), so they already work around two of our warts.

### 3c. Other consumers found

GitHub code search could not be used: this session's GitHub access is scoped
to our two repos, and grep.app is blocked by both the cloud proxy and the
proxy on Daniel's machine. Web search for the URLs found only our own docs.
**The external map is therefore incomplete**: it covers the two known
consumers plus first-party code. Cloudflare analytics on the catalog paths
(by User-Agent and Referer) is the practical way to find the rest (§9, step L4).

First-party consumers found in this repo, which a format change also breaks:

| Consumer | Reads |
|---|---|
| Dashboard islands (`ComponentGrid`, `SearchModal`, `Sidebar`, `TrendingView`, `SendToRepoModal`, `MyComponentsView`), SSR `lib/data.ts`, `llms.txt.ts`, `sitemap.xml.ts`, `home-stats.ts` | `/components.json`, `/components/{type}.json`, `/counts.json`, `/search-index.json`, `/component-content/**`, `/trending-data.json` |
| WebMCP tools (`dashboard/src/lib/webmcp.ts`), exposed to browser agents | `/components/{type}.json`, `/counts.json`, `/trending-data.json` |
| `.github/workflows/daily-component-discord.yml` | `jq` over `docs/components.json` groups `agents, commands, mcps, settings, hooks` |
| CLI `getAvailableAgentsFromGitHub()` (`cli-tool/src/index.js:1439`) | `../../docs/components.json`, which the npm package does not ship, then **`https://aitmpl.com/api/agents.json`, which does not exist on Cloudflare Pages** (it was `docs/api/agents.json` on the old Vercel/GitHub Pages site; today it hits the `/api/*` JSON 404), then the GitHub contents API (60 req/h unauthenticated). A dead URL in a released CLI, unrelated to this proposal but found by it. |
| `cli-tool/src/sandbox-server.js` | `../../docs/components.json` (same packaging gap) |

## 4. Risks: what breaks, for whom, and how loudly

"Silent" means the consumer keeps running and publishes wrong or empty data.

| Change | niche-db | `/aitmpl` mod (all installed copies) | Dashboard / WebMCP |
|---|---|---|---|
| Rename a group key (e.g. `mcps` → `mcp-servers`) | **silent**: `index[group] ?? []` gives 0 rows for that collection | URL `components/mcps.json` 404s: loud error in the pane | breaks until updated (same PR) |
| Rename `name` or `path` | **silent**: every row dropped (`toItem` returns null) | `name`: every row skipped, empty list (silent); `path`: falls back to `name`, wrong install arg | breaks |
| Change `path` format (drop extension, add type prefix) | **silent**: `externalId` changes, every row re-ingested as new and old rows orphaned; blob URLs may 404 | install arg and page URL wrong (silent until clicked) | breaks |
| `downloads` to string / object | **silent**: `null` | **silent**: 0, sort order lost | breaks |
| `keywords` not an array | silent: tags dropped | not read | |
| Remove `security` | none (already always false) | not read | none (dashboard strips it) |
| Change or remove `skillspector` | not read | not read | badge breaks |
| Wrap per-type arrays in an envelope | n/a (reads `docs/`) | **throws**: "catalog body is not an array", pane unusable | breaks |
| Change trending `id` format | n/a | **silent**: trending column empty | |
| Rename a CLI flag / type (as `--function-hook` → `--mod`) | install commands they publish stop working (silent) | install button fails (loud, in the terminal) | |
| Move or delete `docs/components.json` (e.g. retiring the legacy `docs/` site) | **loud on their side, invisible to us**: every pull fails | n/a | Discord daily workflow breaks |
| Move dashboard files (e.g. `/components/*` → `/data/*`) | n/a | loud error in pane | breaks until updated |
| Change `/component/{type}/...` route | n/a | open-in-browser 404s | internal links |
| File grows (1,922 components today, 3.3 MB) | 6 × 3.3 MB per cycle from GitHub | per-type file per pane open | |

In every case **we never find out**: neither consumer reports back, and
the mod copies on users' disks cannot be updated by us.

---

# Phase 2: Formalization proposal

## 5. Principles

1. **New surface, old surface untouched.** The site keeps reading its own
   files and they stay free to evolve with the site. External consumers get a
   separate, versioned, documented surface generated from the same data in
   the same run.
2. **The schema is enforced, not described.** The generator validates its v1
   output against the published JSON Schema in CI; an invalid catalog never
   ships.
3. **One envelope, one key, data instead of conventions.** v1 carries a stable
   `id`, the install arguments and the URLs, so consumers stop rebuilding them.
4. **No sponsorship in the catalog.** v1 never contains placement data, and
   its order is fixed and documented as alphabetical by `id`.

## 6. The v1 contract

### URLs

| URL | Content | Approx size |
|---|---|---|
| `https://www.aitmpl.com/api/v1/catalog.json` | every component, all types | ~2.9 MB raw, ~440 KB gzip (prototyped on today's data: 1,911 components) |
| `https://www.aitmpl.com/api/v1/catalog/{type}.json` | one type (`agents`, `commands`, `skills`, `hooks`, `mcps`, `settings`, `loops`, `mods`) | agents ~950 KB raw |
| `https://www.aitmpl.com/api/v1/version.json` | `{schemaVersion, generatedAt, sha256, counts}` for cheap polling | < 1 KB |
| `https://www.aitmpl.com/api/v1/schema.json` | JSON Schema (draft 2020-12), `$id` = its URL | |
| `https://www.aitmpl.com/developers/catalog-api` | docs page | |

`/api/v1/` is what you suggested. Caveat to verify in the first preview
deploy: `/api/*` is also matched by the `[...path].ts` catch-all function.
Static files under `dashboard/public/api/v1/` should win because the Astro
Cloudflare adapter excludes public assets in `_routes.json`, but that is
inferred, not tested. If the function shadows them, use `/v1/` or `/data/v1/`
instead; nothing else in the proposal changes.

### Envelope (both `catalog.json` and `catalog/{type}.json`)

```json
{
  "schemaVersion": "1.0.0",
  "generatedAt": "2026-10-21T03:13:53Z",
  "source": "https://github.com/davila7/claude-code-templates",
  "license": "MIT",
  "count": 1,
  "components": [
    {
      "id": "agents/development-team/frontend-developer",
      "type": "agents",
      "name": "frontend-developer",
      "category": "development-team",
      "path": "development-team/frontend-developer.md",
      "description": "Frontend development specialist for React applications...",
      "author": null,
      "repo": null,
      "version": null,
      "license": null,
      "keywords": ["frontend", "react"],
      "downloads": 52310,
      "install": {
        "command": "npx claude-code-templates@latest --agent development-team/frontend-developer",
        "args": ["--agent", "development-team/frontend-developer"]
      },
      "urls": {
        "page": "https://www.aitmpl.com/component/agents/development-team/frontend-developer",
        "source": "https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/agents/development-team/frontend-developer.md",
        "content": "https://www.aitmpl.com/component-content/agents/development-team/frontend-developer.json"
      },
      "files": null,
      "scan": {
        "tool": "skillspector",
        "toolVersion": "2.12.0",
        "severity": "LOW",
        "score": 0,
        "scannedAt": "2026-10-17T20:36:45Z"
      }
    }
  ]
}
```

(Values illustrative; `downloads` and the description are not the real ones.)

### Field rules

| Field | v1 rule | Differs from legacy |
|---|---|---|
| `id` | `{type}/{category}/{name}`, unique across the catalog, stable for the component's life. The key consumers should dedupe on. | new |
| `type` | plural group key, one of 8 values. Adding a type is a minor change. | was singular, `sandbo` |
| `name`, `category`, `path` | as today; v1 guarantees `name` = last path segment and `category` = first (true for all rows today) | guarantees are new |
| `description` | string, verbatim from the component; may be empty `""` | unchanged (cleaning it is a later, additive `summary` field) |
| `author`, `repo`, `version`, `license` | string or `null` | `""` → `null` |
| `keywords` | string[] (may be empty) | unchanged |
| `downloads` | integer ≥ 0, total recorded installs, refreshed daily | unchanged |
| `install` | `{command, args}`; `args` is safe to pass as argv | new |
| `urls` | `page`, `source`, `content` | new |
| `files` | string[] for skills and mods, else `null` | was `references`, present only on some types |
| `scan` | latest SkillSpector summary or `null`; display-only, documented as a risk hint, not a verdict | replaces `skillspector` (findings left out of v1.0) |
| — | `security`, `modules`, `userConfig`, `hash` not in v1.0 | dropped (dead, or type-specific internals; `userConfig` can return additively under a `mod` object) |

**Not in v1:** `sandbox` (docs files, not components), `templates`
(retired), `plugins` (empty), `componentsMarketplace` (stale), and any
sponsored or placement data. **Order:** `components` sorted by `id`
ascending, guaranteed. Consumers that want popularity sort by `downloads`
themselves.

### Serving (new `_headers` rules, static files only)

```
/api/v1/*
  Content-Type: application/json; charset=utf-8
  Cache-Control: public, max-age=300, stale-while-revalidate=3600
  Access-Control-Allow-Origin: *
  Access-Control-Allow-Methods: GET, HEAD, OPTIONS
  Access-Control-Expose-Headers: ETag
  X-Catalog-Schema-Version: 1
```

Conditional requests: rely on Pages' automatic `ETag` + `If-None-Match` →
304 (verify on the preview deploy with `curl -sI` and a second request with
`If-None-Match`). Pages does not set `Last-Modified` on static assets, and a
static `_headers` value cannot track deploys, so `generatedAt` in the body and
`version.json` replace it: a poller fetches `version.json` (< 1 KB) and only
downloads `catalog.json` when `sha256` changes. This also makes polling the
GitHub copy unnecessary.

### Stability policy (goes on the docs page)

- `schemaVersion` is semver. **Within major 1, changes are additive only**:
  new optional fields, new `type` values, new enum values in `scan.severity`,
  new files. Consumers must ignore unknown fields and unknown types.
- **Breaking changes** (remove or rename a field, change a type, change `id`
  format, remove a URL) only in a new major at a new path (`/api/v1/` →
  `/api/v2/`). The old major keeps being generated for at least **6 months**
  after the new one ships, with a `Deprecation` header and a
  `Link: </api/v2/...>; rel="successor-version"` header, and a CHANGELOG
  entry on day one.
- `id` is permanent for a component. If a component is renamed or moved, the
  old `id` disappears and a new one appears; v1 does not track moves (could be
  added later as an optional `aliases` field).
- `downloads` and `scan` values change daily; their meaning does not.
- Removal of a component is not a breaking change.

### CHANGELOG for the data format

`docs/catalog-api/CHANGELOG.md` (repo), rendered on the docs page and linked
from `schema.json` (`$comment`) and `/llms.txt`. Keep-a-Changelog style keyed
by `schemaVersion`, separate from the product `CHANGELOG.md`. Seed entry:
`1.0.0`, plus a short "pre-v1 history" section recording the changes consumers
may have hit: `function-hooks` → `mods` (#910, 2026-09-16), full-table
`downloads` (#1005, 2026-09-26), YAML frontmatter parsing (#1070,
2026-10-04), `skillspector` added (#1204, 2026-10-18).

### Legacy URLs

Not frozen and not redirected. A redirect would change their shape and break
the site; freezing would stop the site from evolving. Instead:

- They keep working with the shape they have today.
- `/openapi.json` marks them `deprecated: true` with "internal to the site, no
  stability guarantee, use /api/v1/", and fixes the stale "24 hours" text.
- Later (L1), `_headers` adds `Link: </api/v1/catalog.json>; rel="successor-version"`
  to them. That is a header only; bodies stay the same.
- `docs/components.json` on GitHub: keep generating it for at least the same
  6 months, and add a line to the top of `docs/README.md` and CLAUDE.md saying
  external code reads it, so a legacy-site cleanup does not delete it by
  accident.

## 7. Migration notes for known consumers

**niche-db.** Point `INDEX` at `https://www.aitmpl.com/api/v1/catalog.json`
(one fetch for all six adapters, or `/api/v1/catalog/{type}.json` per
adapter; poll `version.json` first to skip unchanged pulls). Map
`index[group]` to `components.filter(c => c.type === group)`; use `c.id` as
`externalId` (note: changing `externalId` re-ingests every row once, so they
may prefer to keep `aitmpl:{group}:{path}`, which is still derivable); use
`c.install.command` and `c.urls.source` instead of building them; drop
`security.*` (dead) and optionally read `c.scan`. `sandbox` and `templates`
are already absent, so their skip logic can go. Guarantee they get:
additive-only changes for major 1, at least 6 months' notice before v1 goes
away, a changelog to watch. Reaching them (issue or PR on their repo) is an
outbound message and needs your go-ahead.

**`/aitmpl` mod.** Ship a new mod version that reads
`{siteUrl}/api/v1/catalog/{type}.json` and `version.json`, uses `id`,
`install.args` (still validated) and `urls.page`. Copies already installed
keep reading the legacy files, so those files' current shape (bare array,
`name`/`path`/`category`/`description`/`downloads`, trending `id` format,
`counts.json` keys) should be treated as frozen-in-practice for the 6 month
window even though they are not part of the contract. The fork picks up the
change whenever its owner syncs with upstream.

**First-party.** Dashboard and WebMCP keep the legacy files (they deploy
together with the data, so they cannot drift). The CLI's dead
`aitmpl.com/api/agents.json` fallback can move to `/api/v1/catalog/agents.json`.

## 8. Plan

Estimates are agent working time including tests and a preview deploy, not
counting your review. Paths are relative to the repo root.

### MVP (one PR, ~2 to 2.5 days)

| # | Step | Touches | Effort |
|---|---|---|---|
| M1 | JSON Schema for v1 (envelope, component, `version.json`) | new `scripts/catalog_api/schema.v1.json` | 2–3 h |
| M2 | v1 writer: `write_catalog_api_v1(components_data)` called at the end of `generate_components_json()`, after every legacy file is written; builds `catalog.json`, `catalog/{type}.json`, `version.json`, copies `schema.json`. Legacy outputs must stay byte-identical (test asserts it). | `scripts/generate_components_json.py`, new `scripts/catalog_api/v1.py`, `scripts/test_generate_components_json.py` (or a new test file); outputs under `dashboard/public/api/v1/` | 4–6 h |
| M3 | CI validation: generator validates v1 output with `jsonschema` and exits non-zero on failure; add `jsonschema` to the pip install step of both workflows; add `dashboard/public/api/v1` to `DATA_PATHS` | `.github/workflows/update-component-content.yml`, `.github/workflows/update-json-data.yml`, `.github/workflows/generated-files-guard.yml` (new path in the guarded list), `.github/workflows/component-pr-welcome.yml` text | 2–3 h |
| M4 | Serving: `_headers` block for `/api/v1/*`; preview deploy to confirm the `[...path].ts` catch-all does not shadow the static files, `Content-Type`, CORS, `ETag`/304 | `dashboard/public/_headers` (fallback: path change in M2 if shadowed) | 1–2 h |
| M5 | Docs page: fields reference (generated from the schema at build time so the two cannot drift), minimal example, cadence, stability policy, migration note, changelog | new `dashboard/src/pages/developers/catalog-api.astro`, link from `about.astro`/footer | 3–4 h |
| M6 | CHANGELOG seed | new `docs/catalog-api/CHANGELOG.md` | 1 h |
| M7 | Machine-readable pointers: add v1 paths to `/openapi.json`, mark legacy paths `deprecated`, fix the "24 hours" text; add v1 to `/llms.txt`; CLAUDE.md section "Catalog API v1" with the rule that a v1-breaking change needs a v2 | `dashboard/public/openapi.json`, `dashboard/src/pages/llms.txt.ts` (or `lib/agent-readiness.ts`), `CLAUDE.md` | 1–2 h |

### Later steps

| # | Step | Touches | Effort |
|---|---|---|---|
| L1 | `Link: rel="successor-version"` on legacy catalog paths | `dashboard/public/_headers` | 30 min |
| L2 | Breaking-change guard: CI compares `schema.v1.json` with `main`'s and fails if a required field, type or enum value is removed while the major stays 1 | new `.github/workflows/catalog-api-compat.yml` + small script | 3–4 h |
| L3 | Migrate the `/aitmpl` mod to v1 (new version, tests) | `cli-tool/components/mods/productivity/aitmpl/**` | 3–4 h |
| L4 | Find unknown consumers: Cloudflare Web Analytics / Logpush on `/api/v1/*`, legacy catalog paths, grouped by User-Agent and Referer; ask consumers to send a `User-Agent` with a contact URL (docs page) | Cloudflare dashboard, docs page | 1–2 h setup |
| L5 | Outreach to niche-db with the migration note (needs your go-ahead) | external | 30 min |
| L6 | Additive fields: `summary` (cleaned one-line description), `scan.findings`, `mod.userConfig`, `addedAt`/`updatedAt` from git | v1 writer, schema, changelog | 2–4 h each |
| L7 | `/api/v1/content/{id}.json` as the contract for component bodies (today `component-content/**` is undocumented in v1) | v1 writer, schema | 3–4 h |
| L8 | Fix the CLI's dead `aitmpl.com/api/agents.json` fallback (independent bug; also `sandbox-server.js` reading an unshipped `docs/components.json`) | `cli-tool/src/index.js`, `cli-tool/src/sandbox-server.js` | 1–2 h, separate thread |
| L9 | Retire `docs/components.json` on GitHub after the 6 month window, only after L4 shows no traffic and niche-db has moved | generator, workflows | 1 h |

## 9. Open questions for your review

1. Path: `/api/v1/` (your suggestion, needs the catch-all check) or `/v1/`?
2. Include `scan` (SkillSpector summary) in v1.0, or keep it out until the
   scanner output settles? Proposal: include the summary, not the findings.
3. Deprecation window: 6 months proposed.
4. `id` format: `{type}/{category}/{name}` proposed (readable, matches page
   URLs). Alternative is an opaque hash, which survives nothing better and is
   harder to debug.

## 10. Recommendation

**Formalize as proposed, MVP first.**

Reasoning:

- The cost of staying informal is already being paid, just not by us: both
  known consumers carry workarounds for our data (`sandbo`, empty strings,
  quoted descriptions, rebuilding install commands and URLs), and the
  rename from `function-hooks` to `mods` one month ago was exactly the kind
  of change that breaks them silently. More renames are likely (CLAUDE.md
  already lists legacy-site cleanup and new component types).
- One of the two "external" consumers is our own mod, installed on users'
  machines where we cannot fix it. That alone justifies a stable surface:
  without one, every change to the site's internal JSON is a potential
  silent break for our own users.
- The MVP is small (about 2 to 2.5 days), additive, and leaves every
  existing URL and byte untouched. The serving side (CORS, cache, ETag) is
  already mostly in place; what is added is a version, an enforced schema,
  a policy and a changelog.
- The ongoing cost is one rule: a v1-breaking change needs a v2. CI (M3,
  later L2) enforces it, so it does not depend on remembering.
- It also gives the project's neutrality invariant a technical anchor: the
  public contract documents that the catalog contains no placement data and
  has a fixed, non-commercial order.

Keeping it informal knowingly would be reasonable only if we were willing to
treat today's legacy shapes as frozen forever, which constrains the site more
than a separate v1 does.

---

### Robots (`docs/robots.txt`)

User-agent: *
Allow: /

# Filter pages - high priority for crawling
Allow: /agents
Allow: /commands
Allow: /settings
Allow: /hooks
Allow: /mcps
Allow: /templates
Allow: /skills

# Blog content
Allow: /blog/

# Component pages
Allow: /component/

# Important pages
Allow: /trending.html

# Disallow temporary or admin files
Disallow: /node_modules/
Disallow: /.git/
Disallow: /.vercel/
Disallow: /dev-server.js

# Sitemap location (fixed: was pointing to GitHub Pages instead of aitmpl.com)
Sitemap: https://aitmpl.com/sitemap.xml

---

### Dashboard Docs Webmcp (`dashboard/docs/webmcp.md`)

# WebMCP Integration (V1)

Status: **V1 shipped** — read-only catalog tools, behind a build-time flag.

## What it is

[WebMCP](https://github.com/webmachinelearning/webmcp) is a W3C Web Machine
Learning CG proposal that lets a web page expose client-side functionality as
"tools" (name + description + JSON Schema + JS callback) that AI agents can
discover and invoke via `document.modelContext`. Think of it as an in-page MCP
server with no backend: tools reuse the page's own code, session, and data.

aitmpl.com registers a small set of **read-only** tools so browser agents
(Chrome 149+/Edge 150+ origin trials, ChatGPT Desktop, Brave Leo) can search
the component catalog and produce install commands without scraping the UI.

## Architecture

```
DashboardLayout.astro  ── bundled <script> ──►  initWebMCP()  (src/lib/webmcp.ts)
                                                    │
                              feature-detect document.modelContext
                              + PUBLIC_WEBMCP_ENABLED build flag
                                                    │
                                       registerTool() × 4 (read-only)
                                                    │
                          reuses src/lib/data.ts helpers and the static
                          JSON artifacts already served from public/
```

- **`dashboard/src/lib/webmcp.ts`** — the whole feature. Exports a single
  `initWebMCP()` that registers the tools. No new dependencies; minimal local
  typings instead of the `webmcp-types` package.
- **`dashboard/src/layouts/DashboardLayout.astro`** — calls `initWebMCP()`
  from a bundled `<script>`, so the tools are available on every page (all
  pages use this layout; Astro dedupes the script).
- **Data sources** (all existing, same-origin, edge-cached): `search-index.json`,
  `components/{type}.json`, `counts.json`, `trending-data.json`, via
  `fetchSearchIndex()`, `fetchComponentsByType()`, and `getInstallCommand()`
  from `src/lib/data.ts` (shared 5-min in-memory caches with the UI).

## Feature flag

`PUBLIC_WEBMCP_ENABLED` (build-time, same pattern as `PUBLIC_ADS_ENABLED`):

- `dashboard/wrangler.toml` `[vars]` — production value (`"true"`).
- `.github/workflows/deploy.yml` — passed to the CI build step.
- Anything other than the string `"true"` disables the feature entirely
  (`initWebMCP()` returns before touching `document.modelContext`).

Browsers without WebMCP support are unaffected: `initWebMCP()` feature-detects
`document.modelContext.registerTool` and no-ops. Registration failures
(`NotAllowedError` from Permissions Policy, `InvalidStateError` for duplicate
names) are swallowed and never break the page.

## Tools

All tools are read-only (`readOnlyHint: true`). Tools returning
community-authored component descriptions also set `untrustedContentHint: true`
so agents treat that text as data, not instructions (prompt-injection
mitigation).

### `search-components`
Free-text search over the flat search index (name, description, category),
optional `type` filter. Returns `{ total, results[] }` with at most 20 results:
`{ name, type, category, description, url, installCommand }`.

Input: `{ query: string, type?: "agent"|"command"|"mcp"|"setting"|"hook"|"skill"|"loop"|"template" }`

### `get-component-details`
Looks up one component by exact name or catalog path within its type file.
Returns the catalog entry plus `installCommand` and the component page `url`,
or `{ error }` when not found.

Input: `{ name: string, type: <same enum> }`

### `get-install-command`
Returns `{ installCommand }` — the exact
`npx claude-code-templates@latest --<type> <path>` string, built by the same
`getInstallCommand()` helper the UI uses.

Input: `{ name: string, type: <same enum> }`

### `get-catalog-stats`
No input. Returns `{ counts, downloads, lastUpdated }` from `counts.json` and
`trending-data.json` (`globalStats`). Each source degrades to `{}`/`null` on
fetch failure.

## Conventions inside `webmcp.ts`

- Types are normalized: tools accept singular or plural (`"agent"`/`"agents"`);
  URLs and catalog files use plural, install flags use singular.
- Component URLs follow the canonical detail route:
  `https://www.aitmpl.com/component/{type-plural}/{path-without-extension}`.
- All tool results are plain JSON-serializable objects.

## Testing

In a browser with WebMCP enabled (origin-trial build or supported agent),
`getTools()`/`executeTool()` are same-origin callable from DevTools:

```js
const tools = await document.modelContext.getTools();
await document.modelContext.executeTool(
  tools.find(t => t.name === 'search-components'),
  { query: 'react' }
);
```

In a normal browser, stub the API before load to verify registration:

```js
// paste in DevTools, then reload
document.modelContext = { registerTool: t => (console.log('registered', t.name), Promise.resolve()) };
```

## Out of scope for V1 / future work

- **Origin Trial tokens** — Chrome/Edge require registering www.aitmpl.com in
  their WebMCP origin trials and adding the `<meta http-equiv="origin-trial">`
  tag. Not needed for ChatGPT Desktop or Brave Leo.
- Declarative `<form>` tools, `exposedTo` cross-origin iframe exposure,
  service-worker tools.
- Write/consequential tools (cart, PR flow) — would need user-confirmation
  design first.

---

### Blog Worktree Skills Parallel Development (`docs/blog/worktree-skills-parallel-development.md`)

# Parallel Development with Git Worktrees: A Skill + Commands Pattern for Claude Code

Working on a single task at a time is fine -- until you have three bugs to fix, a feature to ship, and a PR review waiting. With git worktrees and Claude Code, you can work on all of them simultaneously in separate terminal panels, each with its own Claude instance.

## The Problem

Traditional git workflows force sequential development. You stash changes, switch branches, lose context, switch back. Every context switch costs time and mental energy.

Git worktrees solve this by letting you check out multiple branches simultaneously in separate directories. But managing worktrees manually -- creating branches, tracking tasks, cleaning up -- adds overhead.

## The Solution: 1 Skill + 4 Commands

We built a system that combines Claude Code's two extension models:

- **1 Skill** (`worktree-guide`) -- an interactive guide Claude can discover and suggest automatically
- **4 Commands** -- manual workflows for each lifecycle step

```
Architecture
──────────────────────────────────────
  SKILL: /worktree-guide
  (discoverable, interactive guide)

  Delegates to COMMANDS:
  ├── /worktree-init      Create worktrees
  ├── /worktree-check     Check status
  ├── /worktree-deliver   Commit + PR
  └── /worktree-cleanup   Clean up
──────────────────────────────────────
```

### Why this architecture?

Commands and Skills serve different purposes in Claude Code:

| | Commands | Skills |
|---|---------|--------|
| **Who triggers** | Only the user | User and/or Claude |
| **Best for** | Manual workflows with side effects | Discoverable knowledge and context |
| **Git operations** | Perfect (push, branch, PR) | Overkill |
| **Auto-discovery** | No | Yes |

The worktree operations create branches, push code, and delete things -- you want deterministic control over when that happens. But the guide that teaches you the workflow? That's perfect for a Skill that Claude can suggest when you mention "parallel development" or "multiple tasks."

## Installation

Copy the commands and the guide skill to your project:

```bash
# Commands (manual workflows)
cp .claude/commands/worktree-*.md your-project/.claude/commands/

# Skill (interactive guide)
cp -r .claude/skills/worktree-guide your-project/.claude/skills/
```

Or install globally for all projects:

```bash
cp .claude/commands/worktree-*.md ~/.claude/commands/
cp -r .claude/skills/worktree-guide ~/.claude/skills/
```

## Workflow: From Tasks to PRs

### Start with the guide

If it's your first time, just ask Claude:

```
How do I work on multiple tasks at once?
```

Claude will discover the `worktree-guide` skill and walk you through the full workflow interactively, including Ghostty keybindings and Lazygit integration.

Or invoke it directly:

```
/worktree-guide
```

### 1. Initialize Worktrees

Start in your main repo and describe your tasks separated by `|`:

```
/worktree-init fix login bug | add dark mode | update API docs
```

Claude creates 3 worktrees, each on its own `wt/*` branch:

```
| # | Task            | Branch             | Path                                |
|---|-----------------|--------------------|------------------------------------|
| 1 | fix login bug   | wt/fix-login-bug   | ../worktrees/repo/wt-fix-login-bug |
| 2 | add dark mode   | wt/add-dark-mode   | ../worktrees/repo/wt-add-dark-mode |
| 3 | update API docs | wt/update-api-docs | ../worktrees/repo/wt-update-api-docs|
```

Each worktree gets a `.worktree-task.md` file with the task context.

### 2. Open Parallel Panels

In Ghostty, split your terminal:

- `Cmd+D` -- split right
- `Cmd+Shift+D` -- split down

Navigate to each worktree and launch Claude:

```bash
# Panel 1
cd ../worktrees/repo/wt-fix-login-bug && claude

# Panel 2
cd ../worktrees/repo/wt-add-dark-mode && claude

# Panel 3
cd ../worktrees/repo/wt-update-api-docs && claude
```

Now you have 3 independent Claude instances, each working on a separate task with full git isolation.

### 3. Check Status

Inside any worktree, run:

```
/worktree-check
```

You get a clean status report:

```
Worktree Status
──────────────────────────────────
Branch:    wt/fix-login-bug
Task:      fix login bug
Commits:   3 ahead of main
Modified:  2 files
Staged:    0 files
Untracked: 0 files
──────────────────────────────────
```

### 4. Deliver Your Work

When a task is done, run:

```
/worktree-deliver
```

Claude will:
1. Show you all changes for review
2. Generate a conventional commit message
3. Push the branch
4. Create a PR with the task description as context

### 5. Clean Up

After your PRs are merged, go back to the main repo and run:

```
/worktree-cleanup --all
```

This removes all merged worktrees, deletes local and remote `wt/*` branches, and prunes stale references.

Use `--dry-run` to preview what would be cleaned up first:

```
/worktree-cleanup --dry-run
```

## The Pattern: Skill as Orchestrator, Commands as Executors

This architecture demonstrates a pattern you can apply to any complex workflow:

1. **Create Commands** for each discrete step that has side effects (git operations, file modifications, deployments)
2. **Create a Skill** that acts as an entry point, guide, and orchestrator -- referencing the commands
3. The Skill is **discoverable** -- Claude can suggest it when relevant
4. The Commands are **deterministic** -- only triggered by explicit user action

Other workflows that fit this pattern:
- **Database migrations**: Skill guide + commands for create, apply, rollback
- **Release management**: Skill guide + commands for bump, changelog, publish
- **Environment setup**: Skill guide + commands for provision, configure, validate

## Tips

- **Name your tasks clearly**: The task description becomes the branch name and PR context
- **One task per worktree**: Keep each worktree focused on a single deliverable
- **Don't cross-edit**: Each worktree is isolated. Changes in one don't affect others until merged
- **Install dependencies**: If your project uses npm/yarn/pnpm, run the install command in each new worktree
- **Works with any terminal**: While optimized for Ghostty panels, this workflow works with any terminal that supports split panes (iTerm2, tmux, Warp, etc.)
- **Use Lazygit**: Open it in a dedicated panel to monitor all worktrees visually

---

### Catalog Api CHANGELOG (`docs/catalog-api/CHANGELOG.md`)

# Catalog API changelog

Changes to the data format published under `https://www.aitmpl.com/api/v1/`
(`catalog.json`, `catalog/{type}.json`, `version.json`, `schema.json`). This
file is separate from the CLI's release notes in `/CHANGELOG.md`. Docs and
stability policy: https://www.aitmpl.com/developers/catalog-api

Within a major version every change is additive. A breaking change ships as a
new major at a new path, announced here on the day it ships, and the previous
major stays published for at least 6 months.

## [1.0.0] - 2026-10-21

First versioned release.

- `catalog.json` with every component; `catalog/{type}.json` per type
  (`agents`, `commands`, `mcps`, `settings`, `hooks`, `skills`, `loops`, `mods`).
- `version.json` (`schemaVersion`, `generatedAt`, `sha256`, `count`, `counts`) for cheap polling.
- `schema.json`, JSON Schema draft 2020-12.
- Component fields: `id`, `type`, `name`, `category`, `path`, `description`,
  `author`, `repo`, `version`, `license`, `keywords`, `downloads`,
  `install.{command,args}`, `urls.{page,source,content}`, `files`, `scan`.
- Compared with the site's internal `components.json`: `type` is the plural
  group key (the internal file says `agent`, and `sandbo` for sandbox); unknown
  values are `null` instead of `""`; `security` (never populated) is dropped;
  `skillspector` becomes the smaller `scan`; `references` becomes `files` for
  skills and mods only; `sandbox`, `templates`, `plugins` and
  `componentsMarketplace` are not published.

## Before 1.0.0 (unversioned files)

There was no contract before 1.0.0, but these changes to the site's internal
files are listed for anyone who was reading them:

- 2026-10-18: `skillspector` object added to every component (#1204).
- 2026-10-04: frontmatter parsed as YAML, so `author`, `version` and `keywords`
  appear for skills that keep them under `metadata` (#1070).
- 2026-09-26: `downloads` counts every recorded install; before, it was a
  partial count (#1005).
- 2026-09-16: `function-hooks` group renamed to `mods`, CLI flag
  `--function-hook` renamed to `--mod` (#910).

---

### Guides Claude Jobs (`docs/guides/claude-jobs.md`)

# Claude Jobs Scraper

Script para encontrar trabajos relacionados con Claude Code y Anthropic Claude utilizando múltiples fuentes y APIs profesionales.

## 🎯 Características

- **APIs Profesionales**: RapidAPI Jobs, Google Jobs (SerpAPI)
- **Scraping Tradicional**: GitHub, YCombinator, WeWorkRemotely (fallback)
- **Filtrado Estricto**: Solo trabajos que mencionen "Claude" explícitamente
- **Datos Estructurados**: JSON compatible con la web existente
- **Rate Limiting**: Manejo responsable de APIs

## 📋 Requisitos

### Opción 1: APIs Profesionales (Recomendado)

1. **RapidAPI Jobs API** - Acceso a 200M+ trabajos de LinkedIn, Indeed, Glassdoor
   - Regístrate en: https://rapidapi.com/letscrape-6bRBa3QguO5/api/jobs-search-realtime-data-api/
   - Plan gratuito: 100 requests/mes
   - Plan pagado: Desde $10/mes

2. **SerpAPI (Google Jobs)** - Búsqueda semántica avanzada
   - Regístrate en: https://serpapi.com/
   - Plan gratuito: 100 búsquedas/mes
   - Plan pagado: Desde $50/mes

### Opción 2: Solo Scraping Gratuito

- No requiere APIs pagadas
- Resultados limitados debido a restricciones de sitios web

## ⚙️ Configuración

1. **Copia el archivo de configuración**:
   ```bash
   cp .env.example .env
   ```

2. **Agrega tus API keys en `.env`**:
   ```bash
   # Para mejores resultados
   RAPIDAPI_KEY=tu_clave_rapidapi
   SERPAPI_KEY=tu_clave_serpapi
   
   # Opcional
   GITHUB_TOKEN=tu_token_github
   ```

3. **Instala dependencias**:
   ```bash
   pip install requests python-dotenv
   ```

## 🚀 Uso

```bash
python generate_claude_jobs.py
```

### Flujo de Funcionamiento:

1. **APIs Profesionales** (si están configuradas)
   - RapidAPI: Busca en LinkedIn, Indeed, Glassdoor, etc.
   - Google Jobs: Búsqueda semántica avanzada
   
2. **Scraping Tradicional** (fallback si no hay APIs)
   - GitHub Issues/Discussions
   - YCombinator Who's Hiring
   - WeWorkRemotely RSS

3. **Generación del JSON**:
   - Archivo: `docs/claude-jobs.json`
   - Estructura compatible con la web existente

## 📊 Datos Generados

Cada trabajo incluye:

```json
{
  "company": "Anthropic",
  "company_icon": "https://anthropic.com/favicon.ico",
  "location": "Remote",
  "description": "Senior AI Developer to enhance Claude Code capabilities...",
  "job_link": "https://anthropic.com/careers/claude-developer",
  "source": "RapidAPI Jobs",
  "date_posted": "2025-09-10T10:00:00Z",
  "salary": 150000
}
```

## 🔧 Filtros Aplicados

El script usa filtrado **ultra-estricto**:

- **Debe mencionar "Claude"** explícitamente
- Términos específicos: `claude code`, `anthropic claude`, `claude ai`, etc.
- Validación de contexto laboral: `hiring`, `position`, `engineer`, etc.

## 📈 Resultados Esperados

Dado que Claude Code es muy nuevo (2025), los resultados serán limitados pero precisos:

- **Con APIs**: 5-20 trabajos relevantes potenciales
- **Solo Scraping**: 0-5 trabajos (debido a restricciones)
- **Calidad**: 100% relevantes (menciones específicas de Claude)

## 🔄 Automatización

Para ejecutar periódicamente:

```bash
# Cron job diario a las 9 AM
0 9 * * * cd /path/to/project && python generate_claude_jobs.py

# GitHub Actions (recomendado)
# Ver ejemplo en .github/workflows/
```

## ⚠️ Limitaciones

1. **Claude Code es nuevo**: Pocas ofertas laborales específicas aún
2. **APIs pagadas**: Mejores resultados requieren suscripciones
3. **Rate limits**: Respetar límites de APIs para evitar bloqueos
4. **Falsos positivos**: Filtrado estricto puede omitir trabajos relevantes

## 🆘 Troubleshooting

### Sin resultados:
- ✅ Verifica API keys en `.env`
- ✅ Revisa límites de rate en las APIs
- ✅ Claude Code es muy específico - resultados limitados son normales

### Errores de API:
- ✅ Verifica saldo en RapidAPI/SerpAPI
- ✅ Revisa formato de API keys
- ✅ Usa VPN si hay restricciones geográficas

## 🔮 Futuro

A medida que Claude Code se popularice (2025-2026):
- Más trabajos específicos aparecerán
- Términos de búsqueda se pueden expandir
- APIs especializadas en AI jobs pueden surgir

---

**Resultado**: JSON estructurado en `docs/claude-jobs.json` listo para consumo por la web.

---

### Guides Deployment (`docs/guides/deployment.md`)

# 🚀 Deployment Guide

This project is configured for automatic deployment to Vercel from the `main` branch.

## GitHub Actions Setup

### Required Secrets

Add these secrets to your GitHub repository settings:

1. **VERCEL_TOKEN**: Your Vercel account token
   - Go to [Vercel Account Settings](https://vercel.com/account/tokens)
   - Create a new token with appropriate permissions
   - Add as `VERCEL_TOKEN` in GitHub Secrets

2. **VERCEL_ORG_ID**: Your Vercel organization ID
   - Run `vercel link` in your project
   - Copy the `orgId` from `.vercel/project.json`
   - Add as `VERCEL_ORG_ID` in GitHub Secrets

3. **VERCEL_PROJECT_ID**: Your Vercel project ID
   - Run `vercel link` in your project
   - Copy the `projectId` from `.vercel/project.json`
   - Add as `VERCEL_PROJECT_ID` in GitHub Secrets

### Getting the IDs

Run these commands in your project root:

```bash
# Link to Vercel project
vercel link

# Get your IDs from the generated file
cat .vercel/project.json
```

## Deployment Flow

- ✅ **Push to main** → Automatic production deploy to aitmpl.com
- ✅ **Other branches** → Manual deploy only (no auto-deploy)
- ✅ **Pull Requests** → No deployment

## Manual Deployment

For testing other branches:

```bash
# Deploy current branch to preview URL
vercel

# Deploy current branch to production
vercel --prod
```

## Domain Configuration

The main branch deploys to the custom domain: **aitmpl.com**

Configured in Vercel dashboard under Project Settings → Domains.

---

### Guides Discord Bot Setup (`docs/guides/discord-bot-setup.md`)

# Discord Bot Setup - Vercel Serverless

Discord bot para claude-code-templates integrado con Vercel Functions usando webhooks. Este enfoque es más eficiente que mantener un bot tradicional con conexión persistente.

## 🚀 Ventajas de la Arquitectura Serverless

- ✅ **Sin servidor permanente**: Solo se ejecuta cuando hay interacciones
- ✅ **Escalabilidad automática**: Vercel maneja el scaling
- ✅ **Integrado con tu infraestructura**: Mismo proyecto, mismo deployment
- ✅ **Costo reducido**: Solo pagas por ejecuciones reales
- ✅ **Cache inteligente**: Reutiliza datos entre invocaciones

## 📋 Comandos Disponibles

### Comandos Básicos (Fase 1)

1. **`/search <query> [type]`** - Buscar componentes
2. **`/info <name> [type]`** - Información detallada
3. **`/install <name> [type]`** - Comando de instalación
4. **`/popular <type> [limit]`** - Componentes más populares
5. **`/random <type>`** - Descubre componentes aleatorios

## 🛠️ Setup Paso a Paso

### 1. Crear Discord Application

1. Ve a [Discord Developer Portal](https://discord.com/developers/applications)
2. Click "New Application" y dale un nombre
3. En la sección "General Information":
   - Copia el **Application ID** → Esto es tu `DISCORD_APP_ID`
4. Ve a la sección "Bot":
   - Click "Add Bot"
   - Copia el **Bot Token** → Esto es tu `DISCORD_BOT_TOKEN`
   - Habilita "Message Content Intent" si lo necesitas
5. En "General Information" nuevamente:
   - Copia el **Public Key** → Esto es tu `DISCORD_PUBLIC_KEY`

### 2. Configurar Variables de Entorno

#### En Local (para testing)

Crea/actualiza tu archivo `.env`:

```bash
# Discord Bot Configuration
DISCORD_APP_ID=123456789012345678
DISCORD_BOT_TOKEN=MTIzNDU2Nzg5MDEyMzQ1Njc4.AbCdEf.GhIjKlMnOpQrStUvWxYz
DISCORD_PUBLIC_KEY=abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890
DISCORD_GUILD_ID=987654321098765432  # Opcional, para testing en un server específico

# API Configuration
COMPONENTS_API_URL=https://aitmpl.com/components.json
```

#### En Vercel (para producción)

1. Ve a tu proyecto en Vercel Dashboard
2. Settings → Environment Variables
3. Agrega estas variables:
   - `DISCORD_APP_ID`
   - `DISCORD_BOT_TOKEN`
   - `DISCORD_PUBLIC_KEY`
   - `COMPONENTS_API_URL` (opcional, por defecto usa aitmpl.com)

### 3. Instalar Dependencias

```bash
npm install
```

Esto instalará:
- `discord-interactions` - Para verificar requests de Discord
- `axios` - Para cargar components.json
- `dotenv` - Para variables de entorno

### 4. Registrar Comandos con Discord

```bash
npm run discord:register
```

Output esperado:
```
📦 Registering Discord slash commands...

   Registering to guild: 987654321098765432

✅ Successfully registered 5 commands!

📝 Registered commands:
   1. /search - Search for components by keyword
   2. /info - Get detailed information about a specific component
   3. /install - Get the installation command for a component
   4. /popular - View the most popular components by download count
   5. /random - Discover a random component
```

### 5. Deploy a Vercel

```bash
vercel --prod
```

O usa el deployment automático de GitHub si lo tienes configurado.

Después del deploy, copia tu URL de producción:
```
https://your-project.vercel.app
```

### 6. Configurar Interactions Endpoint en Discord

1. Ve a Discord Developer Portal → Tu aplicación
2. Ve a "General Information"
3. En **Interactions Endpoint URL**, pega:
   ```
   https://your-project.vercel.app/api/discord/interactions
   ```
4. Click "Save Changes"

Discord intentará verificar la URL enviando un PING. Si todo está bien configurado, verás un ✅.

### 7. Invitar el Bot a tu Servidor

1. En Discord Developer Portal → OAuth2 → URL Generator
2. Selecciona scopes:
   - ✅ `bot`
   - ✅ `applications.commands`
3. Selecciona permisos del bot:
   - ✅ Send Messages
   - ✅ Embed Links
   - ✅ Read Message History
4. Copia la URL generada y ábrela en tu navegador
5. Selecciona tu servidor y autoriza

## 🧪 Testing Local

Para testear localmente antes de hacer deploy:

```bash
# 1. Instala Vercel CLI si no lo tienes
npm i vercel

# 2. Inicia el servidor de desarrollo
vercel dev
```

Esto correrá en `http://localhost:3000`

Para que Discord pueda enviar webhooks a tu localhost, necesitas un túnel:

```bash
# Opción 1: ngrok
ngrok http 3000

# Opción 2: Vercel dev con --listen
vercel dev --listen 3000
```

Usa la URL pública del túnel en Discord Interactions Endpoint.

## 📁 Estructura del Proyecto

```
api/
└── discord/
    ├── interactions.js         # Endpoint principal de webhooks
    ├── register-commands.js    # Script para registrar comandos
    ├── handlers/              # Handlers de cada comando
    │   ├── search.js
    │   ├── info.js
    │   ├── install.js
    │   ├── popular.js
    │   └── random.js
    └── utils/                 # Utilidades compartidas
        ├── componentsLoader.js  # Cache de components.json
        └── embedBuilder.js      # Generador de embeds
```

## 🔍 Cómo Funciona

### Flujo de una Interacción

1. Usuario ejecuta `/search security` en Discord
2. Discord envía POST a `https://your-domain.vercel.app/api/discord/interactions`
3. Vercel ejecuta `api/discord/interactions.js`
4. El handler verifica la firma (seguridad)
5. Identifica el comando y llama al handler correspondiente
6. Handler carga components.json (desde cache si existe)
7. Ejecuta la búsqueda y genera un embed
8. Retorna respuesta a Discord
9. Discord muestra el resultado al usuario

### Cache de Componentes

El sistema mantiene `components.json` en memoria por 5 minutos:
- Primera request: Descarga desde aitmpl.com
- Siguientes requests (< 5 min): Usa cache
- Después de 5 min: Actualiza automáticamente

Esto reduce latencia y requests a la API.

## 🐛 Troubleshooting

### Error: "Invalid request signature"

**Causa**: La PUBLIC_KEY no está configurada o es incorrecta

**Solución**:
1. Verifica que `DISCORD_PUBLIC_KEY` esté en las variables de entorno de Vercel
2. Asegúrate de copiar la Public Key correcta del Developer Portal
3. Redeploy después de cambiar variables de entorno

### Error: Discord no puede verificar la URL

**Causa**: El endpoint no responde correctamente al PING

**Solución**:
1. Verifica que el deployment fue exitoso
2. Prueba manualmente: `curl https://your-domain.vercel.app/api/discord/interactions`
3. Revisa los logs en Vercel Dashboard → Functions

### Comandos no aparecen en Discord

**Causa**: No se registraron o falta scope

**Solución**:
1. Ejecuta `npm run discord:register` nuevamente
2. Si usaste `DISCORD_GUILD_ID`, los comandos solo aparecen en ese server
3. Quita el bot del server y vuelve a invitarlo con el scope `applications.commands`
4. Espera unos minutos (comandos globales pueden tardar hasta 1 hora)

### Bot no responde

**Causa**: Error en el handler o falta de permisos

**Solución**:
1. Revisa logs en Vercel Dashboard → Functions
2. Verifica que el bot tenga permisos de "Send Messages" y "Embed Links"
3. Prueba con un comando simple como `/random`

### "Components data not loaded"

**Causa**: No puede acceder a components.json

**Solución**:
1. Verifica que `https://aitmpl.com/components.json` sea accesible
2. Revisa la variable `COMPONENTS_API_URL` si usas una URL custom
3. Chequea los logs de Vercel para ver el error específico

## 📊 Monitoreo

### Vercel Dashboard

Ve a tu proyecto en Vercel → Functions para ver:
- Invocaciones totales
- Errores
- Tiempo de respuesta
- Logs en tiempo real

### Discord Logs

Cada comando registra en consola:
```
🔹 Command received: /search
✅ Components data loaded
```

Revisa estos logs en Vercel Functions.

## 🚀 Próximos Pasos

### Fase 2: Comandos Interactivos
- `/stats` - Estadísticas de la plataforma
- `/new` - Componentes recientes
- `/daily` - Componente del día

### Fase 3: Botones y Menús
- Agregar botones de acción a los embeds
- Select menus para filtros avanzados
- Modal forms para búsqueda compleja

### Fase 4: Integración Avanzada
- Tracking de instalaciones vía Discord
- Notificaciones automáticas de releases
- Sistema de votación y reviews

## 💡 Tips y Mejores Prácticas

1. **Testing**: Usa `DISCORD_GUILD_ID` para testing rápido en tu server
2. **Production**: Quita `DISCORD_GUILD_ID` para comandos globales
3. **Cache**: Ajusta `CACHE_DURATION` en `componentsLoader.js` según tus necesidades
4. **Errores**: Todos los errores retornan embeds ephemeral (solo visibles para el usuario)
5. **Logs**: Los logs en Vercel te ayudan a debuggear problemas en producción

## 📚 Recursos

- [Discord Developer Portal](https://discord.com/developers/applications)
- [Discord Interactions Documentation](https://discord.com/developers/docs/interactions/receiving-and-responding)
- [Vercel Functions Documentation](https://vercel.com/docs/functions)
- [discord-interactions npm](https://www.npmjs.com/package/discord-interactions)

## 🤝 Soporte

Si tienes problemas:
1. Revisa los logs en Vercel Dashboard
2. Verifica todas las variables de entorno
3. Prueba los endpoints manualmente con curl
4. Abre un issue en GitHub con los logs relevantes

---

**¡Listo!** Tu bot de Discord está corriendo en Vercel Functions 🎉

---

### Guides Growth Kit Pr (`docs/guides/growth-kit-pr.md`)

# Growth Kit - Content Marketing Automation Commands

## Overview

This PR adds **Growth Kit** - a comprehensive content marketing automation toolkit that helps developers distribute blog content across social media platforms with a single command.

Built by [Kanaeru Labs](https://www.kanaeru.ai) while building Kanaeru AI, these commands solve the time-consuming problem of manually converting blog posts into platform-specific content.

## What's Included

### Marketing Commands (5 new commands)

**New Category:** `commands/marketing/`

1. **`publisher-x.md`** - X/Twitter Thread Generator
   - Generates copy-pastable X threads from any content source
   - **3 format options**: Thread (5-8 posts), Single Long, Single Short
   - Supports multi-language (EN/JA)
   - Creates interactive HTML preview with copy buttons
   - Auto-opens X.com for posting

2. **`publisher-linkedin.md`** - LinkedIn Post Generator
   - Creates professional LinkedIn posts via API
   - Automatic media attachment (images/PDFs)
   - Handles OAuth flow automatically
   - Works with zero dependencies (bash + curl only)

3. **`publisher-medium.md`** - Medium Article Converter
   - Converts blog posts to Medium-ready HTML
   - Image upload markers with file paths
   - One-click copy from HTML preview
   - Opens Medium editor automatically

4. **`publisher-devto.md`** - Dev.to RSS Generator
   - Generates complete RSS feed from all blog posts
   - One-time setup for automatic syndication
   - All future posts auto-import to Dev.to

5. **`publisher-all.md`** - All-Platform Generator
   - Runs all 4 publishers in one command
   - Saves ~2 hours of manual work per post
   - Opens all previews in browser tabs

### Setup Commands (1 new command)

**Existing Category:** `commands/setup/`

6. **`vercel-analytics.md`** - Vercel Analytics Setup
   - Auto-installs @vercel/analytics and @vercel/speed-insights
   - Configures React/Vite apps
   - Creates vercel.json for SPA routing
   - Fixes 404 errors on Vercel deployment

## Key Features

✅ **Universal Input Support**
- Blog post slugs (e.g., `2025-10-06-my-post`)
- File paths (markdown, PDF, HTML, text)
- URLs (fetches and converts)

✅ **Zero Dependencies**
- Works in ANY repo type (Python, Rust, Go, JavaScript, etc.)
- Uses only Claude's built-in tools (Read, Write, Bash, Glob, WebFetch)
- No Node.js/npm required (except for Vercel Analytics)

✅ **Multi-Language Support**
- English and Japanese (EN/JA)
- Auto-detects language from content/path
- Platform-specific tone and formatting

✅ **Production-Ready**
- Tested at Kanaeru Labs in production
- Handles LinkedIn API authentication
- Proper character counting for X/Twitter
- HTML preview files with copy buttons

## Use Cases

**For Blog Authors:**
```bash
# Distribute a blog post across all platforms
/publisher-all my-latest-post

# Generate just an X thread
/publisher-x my-latest-post

# Create LinkedIn post with custom image
/publisher-linkedin my-latest-post en diagram.png
```

**For Content Marketers:**
```bash
# Convert any URL to X thread
/publisher-x https://competitor.com/article

# Generate Medium article from PDF
/publisher-medium whitepaper.pdf

# Set up Dev.to auto-syndication
/publisher-devto
```

**For Developers:**
```bash
# Add analytics to React app
/vercel-analytics
```

## Testing

All commands have been:
- ✅ Tested in production at Kanaeru Labs
- ✅ Validated across multiple blog structures
- ✅ Verified to work in Python, Rust, Go, and JavaScript repos
- ✅ Tested with both English and Japanese content

## Benefits to the Community

**Time Savings:**
- X thread generation: ~30 minutes → 2 minutes
- All platforms: ~2 hours → 5 minutes
- One-time Dev.to setup enables automatic future syndication

**Developer-Friendly:**
- No configuration required (auto-detects blog structure)
- Works universally (any repo type, any framework)
- Clear error messages and helpful prompts

**Production Quality:**
- Proper API authentication handling
- Character limit validation
- Multi-language support
- HTML previews for easy copying

## Integration Notes

**File Locations:**
- Marketing commands: `cli-tool/components/commands/marketing/`
- Analytics command: `cli-tool/components/commands/setup/`

**Frontmatter Format:**
All commands include proper frontmatter:
```yaml
---
allowed-tools: Read, Write, Bash, Glob, WebFetch
argument-hint: <input> [lang]
description: [Clear description]
---
```

**Auto-Discovery:**
Commands will be automatically discovered by the `scripts/generate_components_json.py` script when scanning the commands directory.

## Screenshots

Available at: https://github.com/kanaerulabs/growth-kit

See the Growth Kit README for visual examples of:
- X thread preview with 3 format tabs
- LinkedIn post with PDF attachment
- Medium article preview
- Dev.to RSS feed structure

## Attribution

**Author:** Kanaeru Labs (https://www.kanaeru.ai)
**Source Repository:** https://github.com/kanaerulabs/growth-kit
**License:** MIT
**Contact:** support@kanaeru.ai

## Related Resources

- Growth Kit Documentation: https://github.com/kanaerulabs/growth-kit
- Example Blog Posts: See Growth Kit repo for real examples
- LinkedIn API Setup: https://www.linkedin.com/developers/apps

---

## Why This Matters

Content distribution is a major bottleneck for developer bloggers and technical content creators. These commands solve real pain points we experienced while building Kanaeru AI:

- **Manual X thread creation** - repetitive and time-consuming
- **Platform-specific formatting** - each platform has different requirements
- **Character counting** - easy to exceed limits
- **Media attachment** - LinkedIn API complexity
- **Syndication setup** - Dev.to RSS configuration

Growth Kit automates all of this with Claude Code's built-in capabilities.

---

**We believe these commands will be valuable to the Claude Code community and help developers share their technical content more effectively.**

---

### Static Favicon About (`docs/static/favicon/about.txt`)

This favicon was generated using the following font:

- Font Title: Leckerli One
- Font Author: undefined
- Font Source: https://fonts.gstatic.com/s/leckerlione/v21/V8mCoQH8VCsNttEnxnGQ-1itLZxcBtItFw.ttf
- Font License: undefined)

---

### Cli Tool Components Skills Document Processing Doc SKILL (`cli-tool/components/skills/document-processing/doc/SKILL.md`)

---
name: "doc"
description: "Use when the task involves reading, creating, or editing `.docx` documents, especially when formatting or layout fidelity matters; prefer `python-docx` plus the bundled `scripts/render_docx.py` for visual checks."
author: openai
---


# DOCX Skill

## When to use
- Read or review DOCX content where layout matters (tables, diagrams, pagination).
- Create or edit DOCX files with professional formatting.
- Validate visual layout before delivery.

## Workflow
1. Prefer visual review (layout, tables, diagrams).
   - If `soffice` and `pdftoppm` are available, convert DOCX -> PDF -> PNGs.
   - Or use `scripts/render_docx.py` (requires `pdf2image` and Poppler).
   - If these tools are missing, install them or ask the user to review rendered pages locally.
2. Use `python-docx` for edits and structured creation (headings, styles, tables, lists).
3. After each meaningful change, re-render and inspect the pages.
4. If visual review is not possible, extract text with `python-docx` as a fallback and call out layout risk.
5. Keep intermediate outputs organized and clean up after final approval.

## Temp and output conventions
- Use `tmp/docs/` for intermediate files; delete when done.
- Write final artifacts under `output/doc/` when working in this repo.
- Keep filenames stable and descriptive.

## Dependencies (install if missing)
Prefer `uv` for dependency management.

Python packages:
```
uv pip install python-docx pdf2image
```
If `uv` is unavailable:
```
python3 -m pip install python-docx pdf2image
```
System tools (for rendering):
```
# macOS (Homebrew)
brew install libreoffice poppler

# Ubuntu/Debian
sudo apt-get install -y libreoffice poppler-utils
```

If installation isn't possible in this environment, tell the user which dependency is missing and how to install it locally.

## Environment
No required environment variables.

## Rendering commands
DOCX -> PDF:
```
soffice -env:UserInstallation=file:///tmp/lo_profile_$$ --headless --convert-to pdf --outdir $OUTDIR $INPUT_DOCX
```

PDF -> PNGs:
```
pdftoppm -png $OUTDIR/$BASENAME.pdf $OUTDIR/$BASENAME
```

Bundled helper:
```
python3 scripts/render_docx.py /path/to/file.docx --output_dir /tmp/docx_pages
```

## Quality expectations
- Deliver a client-ready document: consistent typography, spacing, margins, and clear hierarchy.
- Avoid formatting defects: clipped/overlapping text, broken tables, unreadable characters, or default-template styling.
- Charts, tables, and visuals must be legible in rendered pages with correct alignment.
- Use ASCII hyphens only. Avoid U+2011 (non-breaking hyphen) and other Unicode dashes.
- Citations and references must be human-readable; never leave tool tokens or placeholder strings.

## Final checks
- Re-render and inspect every page at 100% zoom before final delivery.
- Fix any spacing, alignment, or pagination issues and repeat the render loop.
- Confirm there are no leftovers (temp files, duplicate renders) unless the user asks to keep them.

---

### Cli Tool Components Skills Ai Research Loki Mode Docs COMPETITIVE ANALYSIS (`cli-tool/components/skills/ai-research/loki-mode/docs/COMPETITIVE-ANALYSIS.md`)

# Loki Mode Competitive Analysis

*Last Updated: 2026-01-05*

## Executive Summary

Loki Mode has **unique differentiation** in business operations automation but faces significant gaps in benchmarks, community adoption, and enterprise security features compared to established competitors.

---

## Factual Comparison Table

| Feature | Loki Mode | Claude-Flow | MetaGPT | CrewAI | Cursor Agent | Devin |
|---------|-----------|-------------|---------|--------|--------------|-------|
| **GitHub Stars** | 349 | 10,700 | 62,400 | 25,000+ | N/A (Commercial) | N/A (Commercial) |
| **Agent Count** | 37 types | 64+ agents | 5 roles | Unlimited | 8 parallel | 1 autonomous |
| **Parallel Execution** | Yes (100+) | Yes (swarms) | Sequential | Yes (crews) | Yes (8 worktrees) | Yes (fleet) |
| **Published Benchmarks** | **98.78% HumanEval (multi-agent)** | None | 85.9-87.7% HumanEval | None | ~250 tok/s | 15% complex tasks |
| **SWE-bench Score** | **99.67% patch gen (299/300)** | Unknown | Unknown | Unknown | Unknown | 15% complex |
| **Full SDLC** | Yes (8 phases) | Yes | Partial | Partial | No | Partial |
| **Business Ops** | **Yes (8 agents)** | No | No | No | No | No |
| **Enterprise Security** | `--dangerously-skip-permissions` | MCP sandboxed | Sandboxed | Audit logs, RBAC | Staged autonomy | Sandboxed |
| **Cross-Project Learning** | No | AgentDB | No | No | No | Limited |
| **Observability** | Dashboard + STATUS.txt | Real-time tracing | Logs | Full tracing | Built-in | Full |
| **Pricing** | Free (OSS) | Free (OSS) | Free (OSS) | $25+/mo | $20-400/mo | $20-500/mo |
| **Production Ready** | Experimental | Production | Production | Production | Production | Production |
| **Resource Monitoring** | Yes (v2.18.5) | Unknown | No | No | No | No |
| **State Recovery** | Yes (checkpoints) | Yes (AgentDB) | Limited | Yes | Git worktrees | Yes |
| **Self-Verification** | Yes (RARV) | Unknown | Yes (SOP) | No | YOLO mode | Yes |

---

## Detailed Competitor Analysis

### Claude-Flow (10.7K Stars)
**Repository:** [ruvnet/claude-flow](https://github.com/ruvnet/claude-flow)

**Strengths:**
- 64+ agent system with hive-mind coordination
- AgentDB v1.3.9 with 96x-164x faster vector search
- 25 Claude Skills with natural language activation
- 100 MCP Tools for swarm orchestration
- Built on official Claude Agent SDK (v2.5.0)
- 50-100x speedup from in-process MCP + 10-20x from parallel spawning
- Enterprise features: compliance, scalability, Agile support

**Weaknesses:**
- No business operations automation
- Complex setup compared to single-skill approach
- Heavy infrastructure requirements

**What Loki Mode Can Learn:**
- AgentDB-style persistent memory across projects
- MCP protocol integration for tool orchestration
- Enterprise CLAUDE.MD templates (Agile, Enterprise, Compliance)

---

### MetaGPT (62.4K Stars)
**Repository:** [FoundationAgents/MetaGPT](https://github.com/FoundationAgents/MetaGPT)
**Paper:** ICLR 2024 Oral (Top 1.8%)

**Strengths:**
- 85.9-87.7% Pass@1 on HumanEval
- 100% task completion rate in evaluations
- Standard Operating Procedures (SOPs) reduce hallucinations
- Assembly line paradigm with role specialization
- Low cost: ~$1.09 per project completion
- Academic validation and peer review

**Weaknesses:**
- Sequential execution (not massively parallel)
- Python-focused benchmarks
- No real-time monitoring/dashboard
- No business operations

**What Loki Mode Can Learn:**
- SOP encoding into prompts (reduces cascading errors)
- Benchmark methodology for HumanEval/SWE-bench
- Token cost tracking per task

---

### CrewAI (25K+ Stars, $18M Raised)
**Repository:** [crewAIInc/crewAI](https://github.com/crewAIInc/crewAI)

**Strengths:**
- 5.76x faster than LangGraph
- 1.4 billion agentic automations orchestrated
- 100,000+ certified developers
- Enterprise customers: PwC, IBM, Capgemini, NVIDIA
- Full observability with tracing
- On-premise deployment options
- Audit logs and access controls

**Weaknesses:**
- Not Claude-specific (model agnostic)
- Scaling requires careful resource management
- Enterprise features require paid tier

**What Loki Mode Can Learn:**
- Flows architecture for production deployments
- Tracing and observability patterns
- Enterprise security features (audit logs, RBAC)

---

### Cursor Agent Mode (Commercial, $29B Valuation)
**Website:** [cursor.com](https://cursor.com)

**Strengths:**
- Up to 8 parallel agents via git worktrees
- Composer model: ~250 tokens/second
- YOLO mode for auto-applying changes
- `.cursor/rules` for agent constraints
- Staged autonomy with plan approval
- Massive enterprise adoption

**Weaknesses:**
- Commercial product ($20-400/month)
- IDE-locked (VS Code fork)
- No full SDLC (code editing focus)
- No business operations

**What Loki Mode Can Learn:**
- `.cursor/rules` equivalent for agent constraints
- Staged autonomy patterns
- Git worktree isolation for parallel work

---

### Devin AI (Commercial, $10.2B Valuation)
**Website:** [cognition.ai](https://cognition.ai)

**Strengths:**
- 25% of Cognition's own PRs generated by Devin
- 4x faster, 2x more efficient than previous year
- 67% PR merge rate (up from 34%)
- Enterprise adoption: Goldman Sachs pilot
- Excellent at migrations (SAS->PySpark, COBOL, Angular->React)

**Weaknesses:**
- Only 15% success rate on complex autonomous tasks
- Gets stuck on ambiguous requirements
- Requires clear upfront specifications
- $20-500/month pricing

**What Loki Mode Can Learn:**
- Fleet parallelization for repetitive tasks
- Migration-specific agent capabilities
- PR merge tracking as success metric

---

## Benchmark Results (Published 2026-01-05)

### HumanEval Results (Three-Way Comparison)

**Loki Mode Multi-Agent (with RARV):**

| Metric | Value |
|--------|-------|
| **Pass@1** | **98.78%** |
| Passed | 162/164 problems |
| Failed | 2 problems (HumanEval/32, HumanEval/50) |
| RARV Recoveries | 2 (HumanEval/38, HumanEval/132) |
| Avg Attempts | 1.04 |
| Model | Claude Opus 4.5 |
| Time | 45.1 minutes |

**Direct Claude (Single Agent Baseline):**

| Metric | Value |
|--------|-------|
| **Pass@1** | **98.17%** |
| Passed | 161/164 problems |
| Failed | 3 problems |
| Model | Claude Opus 4.5 |
| Time | 21.1 minutes |

**Three-Way Comparison:**

| System | HumanEval Pass@1 | Agent Type |
|--------|------------------|------------|
| **Loki Mode (multi-agent)** | **98.78%** | Architect->Engineer->QA->Reviewer |
| Direct Claude | 98.17% | Single agent |
| MetaGPT | 85.9-87.7% | Multi-agent (5 roles) |

**Key Finding:** RARV cycle recovered 2 problems that failed on first attempt, demonstrating the value of self-verification loops.

**Failed Problems (after RARV):** HumanEval/32, HumanEval/50

### SWE-bench Lite Results (Full 300 Problems)

**Direct Claude (Single Agent Baseline):**

| Metric | Value |
|--------|-------|
| **Patch Generation** | **99.67%** |
| Generated | 299/300 problems |
| Errors | 1 |
| Model | Claude Opus 4.5 |
| Time | 6.17 hours |

**Loki Mode Multi-Agent (with RARV):**

| Metric | Value |
|--------|-------|
| **Patch Generation** | **99.67%** |
| Generated | 299/300 problems |
| Errors/Timeouts | 1 |
| Model | Claude Opus 4.5 |
| Time | 3.5 hours |

**Three-Way Comparison:**

| System | SWE-bench Patch Gen | Notes |
|--------|---------------------|-------|
| **Direct Claude** | **99.67%** (299/300) | Single agent, minimal overhead |
| **Loki Mode (multi-agent)** | **99.67%** (299/300) | 4-agent pipeline with RARV |
| Devin | ~15% complex tasks | Commercial, different benchmark |

**Key Finding:** After timeout optimization (Architect: 60s->120s), the multi-agent RARV pipeline matches direct Claude's performance on SWE-bench. Both achieve 99.67% patch generation rate.

**Note:** Patches generated; full validation (resolve rate) requires running the Docker-based SWE-bench harness to apply patches and execute test suites.

---

## Critical Gaps to Address

### Priority 1: Benchmarks (COMPLETED)
- **Gap:** ~~No published HumanEval or SWE-bench scores~~ RESOLVED
- **Result:** 98.17% HumanEval Pass@1 (beats MetaGPT by 10.5%)
- **Result:** 99.67% SWE-bench Lite patch generation (299/300)
- **Next:** Run full SWE-bench harness for resolve rate validation

### Priority 2: Security Model (Critical for Enterprise)
- **Gap:** Relies on `--dangerously-skip-permissions`
- **Impact:** Enterprise adoption blocked
- **Solution:** Implement sandbox mode, staged autonomy, audit logs

### Priority 3: Cross-Project Learning (Differentiator)
- **Gap:** Each project starts fresh; no accumulated knowledge
- **Impact:** Repeats mistakes, no efficiency gains over time
- **Solution:** Implement learnings database like AgentDB

### Priority 4: Observability (Production Readiness)
- **Gap:** Basic dashboard, no tracing
- **Impact:** Hard to debug complex multi-agent runs
- **Solution:** Add OpenTelemetry tracing, agent lineage visualization

### Priority 5: Community/Documentation
- **Gap:** 349 stars vs. 10K-60K for competitors
- **Impact:** Limited trust and contribution
- **Solution:** More examples, video tutorials, case studies

---

## Loki Mode's Unique Advantages

### 1. Business Operations Automation (No Competitor Has This)
- Marketing agents (campaigns, content, SEO)
- Sales agents (outreach, CRM, pipeline)
- Finance agents (budgets, forecasts, reporting)
- Legal agents (contracts, compliance, IP)
- HR agents (hiring, onboarding, culture)
- Investor relations agents (pitch decks, updates)
- Partnership agents (integrations, BD)

### 2. Full Startup Simulation
- PRD -> Research -> Architecture -> Development -> QA -> Deploy -> Marketing -> Revenue
- Complete lifecycle, not just coding

### 3. RARV Self-Verification Loop
- Reason-Act-Reflect-Verify cycle
- 2-3x quality improvement through self-correction
- Mistakes & Learnings tracking

### 4. Resource Monitoring (v2.18.5)
- Prevents system overload from too many agents
- Self-throttling based on CPU/memory
- No competitor has this built-in

---

## Improvement Roadmap

### Phase 1: Credibility (Week 1-2)
1. Run HumanEval benchmark, publish results
2. Run SWE-bench Lite, publish results
3. Add benchmark badge to README
4. Create benchmark runner script

### Phase 2: Security (Week 2-3)
1. Implement sandbox mode (containerized execution)
2. Add staged autonomy (plan approval before execution)
3. Implement audit logging
4. Create reduced-permissions mode

### Phase 3: Learning System (Week 3-4)
1. Implement `.loki/learnings/` knowledge base
2. Cross-project pattern extraction
3. Mistake avoidance database
4. Success pattern library

### Phase 4: Observability (Week 4-5)
1. OpenTelemetry integration
2. Agent lineage visualization
3. Token cost tracking
4. Performance metrics dashboard

### Phase 5: Community (Ongoing)
1. Video tutorials
2. More example PRDs
3. Case study documentation
4. Integration guides (Vibe Kanban, etc.)

---

## Sources

- [Claude-Flow GitHub](https://github.com/ruvnet/claude-flow)
- [MetaGPT GitHub](https://github.com/FoundationAgents/MetaGPT)
- [MetaGPT Paper (ICLR 2024)](https://openreview.net/forum?id=VtmBAGCN7o)
- [CrewAI GitHub](https://github.com/crewAIInc/crewAI)
- [CrewAI Framework 2025 Review](https://latenode.com/blog/ai-frameworks-technical-infrastructure/crewai-framework/crewai-framework-2025-complete-review-of-the-open-source-multi-agent-ai-platform)
- [Cursor AI Review 2025](https://skywork.ai/blog/cursor-ai-review-2025-agent-refactors-privacy/)
- [Cursor 2.0 Features](https://cursor.com/changelog/2-0)
- [Devin 2025 Performance Review](https://cognition.ai/blog/devin-annual-performance-review-2025)
- [Devin AI Real Tests](https://trickle.so/blog/devin-ai-review)
- [SWE-bench Verified Leaderboard](https://llm-stats.com/benchmarks/swe-bench-verified)
- [SWE-bench Official](https://www.swebench.com/)
- [Claude Code Best Practices](https://www.anthropic.com/engineering/claude-code-best-practices)

---

--- METRICS ---
- Files Extracted: 18
- Estimated Token Budget: ~30666 tokens
- Canonical Reference: https://codewiki.google/github.com/davila7/claude-code-templates
