---
name: clarvia-aeo-check
description: "Score any MCP server, API, or CLI for agent-readiness using Clarvia AEO (Agent Experience Optimization). Search 15,400+ indexed tools before adding them to your workflow."
category: tool-quality
risk: safe
source: community
date_added: "2026-03-27"
author: digitamaz
tags: [mcp, aeo, tool-quality, agent-readiness, api-scoring, clarvia]
tools: [claude, cursor, windsurf, cline]
---

# Clarvia AEO Check

## Overview

Before adding any MCP server, API, or CLI tool to your agent workflow, use Clarvia to score its agent-readiness. Clarvia evaluates 15,400+ AI tools across four AEO dimensions: API accessibility, data structuring, agent compatibility, and trust signals.

## Prerequisites

Add Clarvia MCP server to your config:

```json
{
  "mcpServers": {
    "clarvia": {
      "command": "npx",
      "args": ["-y", "clarvia-mcp-server"]
    }
  }
}
```

## When to Use This Skill

- Use when evaluating a new MCP server before adding it to your config
- Use when comparing two tools for the same job
- Use when building an agent that selects tools dynamically
- Use when you want to find the highest-quality tool in a category

## How It Works

### Step 1: Score a specific tool

Ask Claude to score any tool by URL or name:

```
Score https://github.com/example/my-mcp-server for agent-readiness
```

Clarvia returns a 0-100 AEO score with breakdown across four dimensions.

### Step 2: Search tools by category

```
Find the top-rated database MCP servers using Clarvia
```

Returns ranked results from 15,400+ indexed tools.

### Step 3: Compare tools head-to-head

```
Compare supabase-mcp vs firebase-mcp using Clarvia
```

Returns side-by-side score breakdown with a recommendation.

### Step 4: Check leaderboard

```
Show me the top 10 MCP servers for authentication using Clarvia
```

## Examples

### Example 1: Evaluate before installing

```
Before I add this MCP server to my config, score it:
https://github.com/example/new-tool

Use the clarvia aeo_score tool and tell me if it's agent-ready.
```

### Example 2: Find best tool in category

```
I need an MCP server for web scraping. Use Clarvia to find the
top-rated options and compare the top 3.
```

### Example 3: CI/CD quality gate

Add to your CI pipeline using the GitHub Action:

```yaml
- uses: clarvia-project/clarvia-action@v1
  with:
    url: https://your-api.com
    fail-under: 70
```

## AEO Score Interpretation

| Score | Rating | Meaning |
|-------|--------|---------|
| 90-100 | Agent Native | Built specifically for agent use |
| 70-89 | Agent Friendly | Works well, minor gaps |
| 50-69 | Agent Compatible | Works but needs improvement |
| 30-49 | Agent Partial | Significant limitations |
| 0-29 | Not Agent Ready | Avoid for agentic workflows |

## Best Practices

- ✅ Score tools before adding them to long-running agent workflows
- ✅ Use Clarvia's leaderboard to discover alternatives you haven't considered
- ✅ Re-check scores periodically — tools improve over time
- ❌ Don't skip scoring for "well-known" tools — even popular tools can score poorly
- ❌ Don't use tools scoring below 50 in production agent pipelines without understanding the limitations

## Common Pitfalls

- **Problem:** Clarvia returns "not found" for a tool
  **Solution:** Try scanning by URL directly with `aeo_score` — Clarvia will score it on-demand

- **Problem:** Score seems low for a tool I trust
  **Solution:** Use `get_score_breakdown` to see which dimensions are weak and decide if they matter for your use case

## Related Skills

- `@mcp-builder` - Build a new MCP server that scores well on AEO
- `@agent-evaluation` - Broader agent quality evaluation framework

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: claude-ally-health
description: "A health assistant skill for medical information analysis, symptom tracking, and wellness guidance."
risk: safe
source: "https://github.com/huifer/Claude-Ally-Health"
date_added: "2026-02-27"
---

# Claude Ally Health

## Overview

A health assistant skill for medical information analysis, symptom tracking, and wellness guidance.

## When to Use This Skill

Use this skill when you need to work with a health assistant skill for medical information analysis, symptom tracking, and wellness guidance..

## Instructions

This skill provides guidance and patterns for a health assistant skill for medical information analysis, symptom tracking, and wellness guidance..

For more information, see the [source repository](https://github.com/huifer/Claude-Ally-Health).

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: claude-api
description: "Build apps with the Claude API or Anthropic SDK. TRIGGER when: code imports `anthropic`/`@anthropic-ai/sdk`/`claude_agent_sdk`, or user asks to use Claude API, Anthropic SDKs, or Agent SDK. DO NOT TRIGGER when: code imports `openai`/other AI SDK, general programming, or ML/data-science tasks."
risk: critical
source: "https://github.com/anthropics/skills"
date_added: "2026-03-21"
license: Complete terms in LICENSE.txt
---

# Building LLM-Powered Applications with Claude

This skill helps you build LLM-powered applications with Claude. Choose the right surface based on your needs, detect the project language, then read the relevant language-specific documentation.

## When to Use
- Use when building with the Claude API, Anthropic SDKs, or the Agent SDK.
- Use when code imports `anthropic`, `@anthropic-ai/sdk`, or related Claude SDK packages.
- Do not use for general coding work unrelated to Claude integrations.

## Defaults

Unless the user requests otherwise:

For the Claude model version, please use Claude Opus 4.6, which you can access via the exact model string `claude-opus-4-6`. Please default to using adaptive thinking (`thinking: {type: "adaptive"}`) for anything remotely complicated. And finally, please default to streaming for any request that may involve long input, long output, or high `max_tokens` — it prevents hitting request timeouts. Use the SDK's `.get_final_message()` / `.finalMessage()` helper to get the complete response if you don't need to handle individual stream events

---

## Language Detection

Before reading code examples, determine which language the user is working in:

1. **Look at project files** to infer the language:

   - `*.py`, `requirements.txt`, `pyproject.toml`, `setup.py`, `Pipfile` → **Python** — read from `python/`
   - `*.ts`, `*.tsx`, `package.json`, `tsconfig.json` → **TypeScript** — read from `typescript/`
   - `*.js`, `*.jsx` (no `.ts` files present) → **TypeScript** — JS uses the same SDK, read from `typescript/`
   - `*.java`, `pom.xml`, `build.gradle` → **Java** — read from `java/`
   - `*.kt`, `*.kts`, `build.gradle.kts` → **Java** — Kotlin uses the Java SDK, read from `java/`
   - `*.scala`, `build.sbt` → **Java** — Scala uses the Java SDK, read from `java/`
   - `*.go`, `go.mod` → **Go** — read from `go/`
   - `*.rb`, `Gemfile` → **Ruby** — read from `ruby/`
   - `*.cs`, `*.csproj` → **C#** — read from `csharp/`
   - `*.php`, `composer.json` → **PHP** — read from `php/`

2. **If multiple languages detected** (e.g., both Python and TypeScript files):

   - Check which language the user's current file or question relates to
   - If still ambiguous, ask: "I detected both Python and TypeScript files. Which language are you using for the Claude API integration?"

3. **If language can't be inferred** (empty project, no source files, or unsupported language):

   - Use AskUserQuestion with options: Python, TypeScript, Java, Go, Ruby, cURL/raw HTTP, C#, PHP
   - If AskUserQuestion is unavailable, default to Python examples and note: "Showing Python examples. Let me know if you need a different language."

4. **If unsupported language detected** (Rust, Swift, C++, Elixir, etc.):

   - Suggest cURL/raw HTTP examples from `curl/` and note that community SDKs may exist
   - Offer to show Python or TypeScript examples as reference implementations

5. **If user needs cURL/raw HTTP examples**, read from `curl/`.

### Language-Specific Feature Support

| Language   | Tool Runner | Agent SDK | Notes                                 |
| ---------- | ----------- | --------- | ------------------------------------- |
| Python     | Yes (beta)  | Yes       | Full support — `@beta_tool` decorator |
| TypeScript | Yes (beta)  | Yes       | Full support — `betaZodTool` + Zod    |
| Java       | Yes (beta)  | No        | Beta tool use with annotated classes  |
| Go         | Yes (beta)  | No        | `BetaToolRunner` in `toolrunner` pkg  |
| Ruby       | Yes (beta)  | No        | `BaseTool` + `tool_runner` in beta    |
| cURL       | N/A         | N/A       | Raw HTTP, no SDK features             |
| C#         | No          | No        | Official SDK                          |
| PHP        | No          | No        | Official SDK                          |

---

## Which Surface Should I Use?

> **Start simple.** Default to the simplest tier that meets your needs. Single API calls and workflows handle most use cases — only reach for agents when the task genuinely requires open-ended, model-driven exploration.

| Use Case                                        | Tier            | Recommended Surface       | Why                                     |
| ----------------------------------------------- | --------------- | ------------------------- | --------------------------------------- |
| Classification, summarization, extraction, Q&A  | Single LLM call | **Claude API**            | One request, one response               |
| Batch processing or embeddings                  | Single LLM call | **Claude API**            | Specialized endpoints                   |
| Multi-step pipelines with code-controlled logic | Workflow        | **Claude API + tool use** | You orchestrate the loop                |
| Custom agent with your own tools                | Agent           | **Claude API + tool use** | Maximum flexibility                     |
| AI agent with file/web/terminal access          | Agent           | **Agent SDK**             | Built-in tools, safety, and MCP support |
| Agentic coding assistant                        | Agent           | **Agent SDK**             | Designed for this use case              |
| Want built-in permissions and guardrails        | Agent           | **Agent SDK**             | Safety features included                |

> **Note:** The Agent SDK is for when you want built-in file/web/terminal tools, permissions, and MCP out of the box. If you want to build an agent with your own tools, Claude API is the right choice — use the tool runner for automatic loop handling, or the manual loop for fine-grained control (approval gates, custom logging, conditional execution).

### Decision Tree

```
What does your application need?

1. Single LLM call (classification, summarization, extraction, Q&A)
   └── Claude API — one request, one response

2. Does Claude need to read/write files, browse the web, or run shell commands
   as part of its work? (Not: does your app read a file and hand it to Claude —
   does Claude itself need to discover and access files/web/shell?)
   └── Yes → Agent SDK — built-in tools, don't reimplement them
       Examples: "scan a codebase for bugs", "summarize every file in a directory",
                 "find bugs using subagents", "research a topic via web search"

3. Workflow (multi-step, code-orchestrated, with your own tools)
   └── Claude API with tool use — you control the loop

4. Open-ended agent (model decides its own trajectory, your own tools)
   └── Claude API agentic loop (maximum flexibility)
```

### Should I Build an Agent?

Before choosing the agent tier, check all four criteria:

- **Complexity** — Is the task multi-step and hard to fully specify in advance? (e.g., "turn this design doc into a PR" vs. "extract the title from this PDF")
- **Value** — Does the outcome justify higher cost and latency?
- **Viability** — Is Claude capable at this task type?
- **Cost of error** — Can errors be caught and recovered from? (tests, review, rollback)

If the answer is "no" to any of these, stay at a simpler tier (single call or workflow).

---

## Architecture

Everything goes through `POST /v1/messages`. Tools and output constraints are features of this single endpoint — not separate APIs.

**User-defined tools** — You define tools (via decorators, Zod schemas, or raw JSON), and the SDK's tool runner handles calling the API, executing your functions, and looping until Claude is done. For full control, you can write the loop manually.

**Server-side tools** — Anthropic-hosted tools that run on Anthropic's infrastructure. Code execution is fully server-side (declare it in `tools`, Claude runs code automatically). Computer use can be server-hosted or self-hosted.

**Structured outputs** — Constrains the Messages API response format (`output_config.format`) and/or tool parameter validation (`strict: true`). The recommended approach is `client.messages.parse()` which validates responses against your schema automatically. Note: the old `output_format` parameter is deprecated; use `output_config: {format: {...}}` on `messages.create()`.

**Supporting endpoints** — Batches (`POST /v1/messages/batches`), Files (`POST /v1/files`), and Token Counting feed into or support Messages API requests.

---

## Current Models (cached: 2026-02-17)

| Model             | Model ID            | Context        | Input $/1M | Output $/1M |
| ----------------- | ------------------- | -------------- | ---------- | ----------- |
| Claude Opus 4.6   | `claude-opus-4-6`   | 200K (1M beta) | $5.00      | $25.00      |
| Claude Sonnet 4.6 | `claude-sonnet-4-6` | 200K (1M beta) | $3.00      | $15.00      |
| Claude Haiku 4.5  | `claude-haiku-4-5`  | 200K           | $1.00      | $5.00       |

**ALWAYS use `claude-opus-4-6` unless the user explicitly names a different model.** This is non-negotiable. Do not use `claude-sonnet-4-6`, `claude-sonnet-4-5`, or any other model unless the user literally says "use sonnet" or "use haiku". Never downgrade for cost — that's the user's decision, not yours.

**CRITICAL: Use only the exact model ID strings from the table above — they are complete as-is. Do not append date suffixes.** For example, use `claude-sonnet-4-5`, never `claude-sonnet-4-5-20250514` or any other date-suffixed variant you might recall from training data. If the user requests an older model not in the table (e.g., "opus 4.5", "sonnet 3.7"), read `shared/models.md` for the exact ID — do not construct one yourself.

A note: if any of the model strings above look unfamiliar to you, that's to be expected — that just means they were released after your training data cutoff. Rest assured they are real models; we wouldn't mess with you like that.

---

## Thinking & Effort (Quick Reference)

**Opus 4.6 — Adaptive thinking (recommended):** Use `thinking: {type: "adaptive"}`. Claude dynamically decides when and how much to think. No `budget_tokens` needed — `budget_tokens` is deprecated on Opus 4.6 and Sonnet 4.6 and must not be used. Adaptive thinking also automatically enables interleaved thinking (no beta header needed). **When the user asks for "extended thinking", a "thinking budget", or `budget_tokens`: always use Opus 4.6 with `thinking: {type: "adaptive"}`. The concept of a fixed token budget for thinking is deprecated — adaptive thinking replaces it. Do NOT use `budget_tokens` and do NOT switch to an older model.**

**Effort parameter (GA, no beta header):** Controls thinking depth and overall token spend via `output_config: {effort: "low"|"medium"|"high"|"max"}` (inside `output_config`, not top-level). Default is `high` (equivalent to omitting it). `max` is Opus 4.6 only. Works on Opus 4.5, Opus 4.6, and Sonnet 4.6. Will error on Sonnet 4.5 / Haiku 4.5. Combine with adaptive thinking for the best cost-quality tradeoffs. Use `low` for subagents or simple tasks; `max` for the deepest reasoning.

**Sonnet 4.6:** Supports adaptive thinking (`thinking: {type: "adaptive"}`). `budget_tokens` is deprecated on Sonnet 4.6 — use adaptive thinking instead.

**Older models (only if explicitly requested):** If the user specifically asks for Sonnet 4.5 or another older model, use `thinking: {type: "enabled", budget_tokens: N}`. `budget_tokens` must be less than `max_tokens` (minimum 1024). Never choose an older model just because the user mentions `budget_tokens` — use Opus 4.6 with adaptive thinking instead.

---

## Compaction (Quick Reference)

**Beta, Opus 4.6 only.** For long-running conversations that may exceed the 200K context window, enable server-side compaction. The API automatically summarizes earlier context when it approaches the trigger threshold (default: 150K tokens). Requires beta header `compact-2026-01-12`.

**Critical:** Append `response.content` (not just the text) back to your messages on every turn. Compaction blocks in the response must be preserved — the API uses them to replace the compacted history on the next request. Extracting only the text string and appending that will silently lose the compaction state.

See `{lang}/claude-api/README.md` (Compaction section) for code examples. Full docs via WebFetch in `shared/live-sources.md`.

---

## Reading Guide

After detecting the language, read the relevant files based on what the user needs:

### Quick Task Reference

**Single text classification/summarization/extraction/Q&A:**
→ Read only `{lang}/claude-api/README.md`

**Chat UI or real-time response display:**
→ Read `{lang}/claude-api/README.md` + `{lang}/claude-api/streaming.md`

**Long-running conversations (may exceed context window):**
→ Read `{lang}/claude-api/README.md` — see Compaction section

**Function calling / tool use / agents:**
→ Read `{lang}/claude-api/README.md` + `shared/tool-use-concepts.md` + `{lang}/claude-api/tool-use.md`

**Batch processing (non-latency-sensitive):**
→ Read `{lang}/claude-api/README.md` + `{lang}/claude-api/batches.md`

**File uploads across multiple requests:**
→ Read `{lang}/claude-api/README.md` + `{lang}/claude-api/files-api.md`

**Agent with built-in tools (file/web/terminal):**
→ Read `{lang}/agent-sdk/README.md` + `{lang}/agent-sdk/patterns.md`

### Claude API (Full File Reference)

Read the **language-specific Claude API folder** (`{language}/claude-api/`):

1. **`{language}/claude-api/README.md`** — **Read this first.** Installation, quick start, common patterns, error handling.
2. **`shared/tool-use-concepts.md`** — Read when the user needs function calling, code execution, memory, or structured outputs. Covers conceptual foundations.
3. **`{language}/claude-api/tool-use.md`** — Read for language-specific tool use code examples (tool runner, manual loop, code execution, memory, structured outputs).
4. **`{language}/claude-api/streaming.md`** — Read when building chat UIs or interfaces that display responses incrementally.
5. **`{language}/claude-api/batches.md`** — Read when processing many requests offline (not latency-sensitive). Runs asynchronously at 50% cost.
6. **`{language}/claude-api/files-api.md`** — Read when sending the same file across multiple requests without re-uploading.
7. **`shared/error-codes.md`** — Read when debugging HTTP errors or implementing error handling.
8. **`shared/live-sources.md`** — WebFetch URLs for fetching the latest official documentation.

> **Note:** For Java, Go, Ruby, C#, PHP, and cURL — these have a single file each covering all basics. Read that file plus `shared/tool-use-concepts.md` and `shared/error-codes.md` as needed.

### Agent SDK

Read the **language-specific Agent SDK folder** (`{language}/agent-sdk/`). Agent SDK is available for **Python and TypeScript only**.

1. **`{language}/agent-sdk/README.md`** — Installation, quick start, built-in tools, permissions, MCP, hooks.
2. **`{language}/agent-sdk/patterns.md`** — Custom tools, hooks, subagents, MCP integration, session resumption.
3. **`shared/live-sources.md`** — WebFetch URLs for current Agent SDK docs.

---

## When to Use WebFetch

Use WebFetch to get the latest documentation when:

- User asks for "latest" or "current" information
- Cached data seems incorrect
- User asks about features not covered here

Live documentation URLs are in `shared/live-sources.md`.

## Common Pitfalls

- Don't truncate inputs when passing files or content to the API. If the content is too long to fit in the context window, notify the user and discuss options (chunking, summarization, etc.) rather than silently truncating.
- **Opus 4.6 / Sonnet 4.6 thinking:** Use `thinking: {type: "adaptive"}` — do NOT use `budget_tokens` (deprecated on both Opus 4.6 and Sonnet 4.6). For older models, `budget_tokens` must be less than `max_tokens` (minimum 1024). This will throw an error if you get it wrong.
- **Opus 4.6 prefill removed:** Assistant message prefills (last-assistant-turn prefills) return a 400 error on Opus 4.6. Use structured outputs (`output_config.format`) or system prompt instructions to control response format instead.
- **128K output tokens:** Opus 4.6 supports up to 128K `max_tokens`, but the SDKs require streaming for large `max_tokens` to avoid HTTP timeouts. Use `.stream()` with `.get_final_message()` / `.finalMessage()`.
- **Tool call JSON parsing (Opus 4.6):** Opus 4.6 may produce different JSON string escaping in tool call `input` fields (e.g., Unicode or forward-slash escaping). Always parse tool inputs with `json.loads()` / `JSON.parse()` — never do raw string matching on the serialized input.
- **Structured outputs (all models):** Use `output_config: {format: {...}}` instead of the deprecated `output_format` parameter on `messages.create()`. This is a general API change, not 4.6-specific.
- **Don't reimplement SDK functionality:** The SDK provides high-level helpers — use them instead of building from scratch. Specifically: use `stream.finalMessage()` instead of wrapping `.on()` events in `new Promise()`; use typed exception classes (`Anthropic.RateLimitError`, etc.) instead of string-matching error messages; use SDK types (`Anthropic.MessageParam`, `Anthropic.Tool`, `Anthropic.Message`, etc.) instead of redefining equivalent interfaces.
- **Don't define custom types for SDK data structures:** The SDK exports types for all API objects. Use `Anthropic.MessageParam` for messages, `Anthropic.Tool` for tool definitions, `Anthropic.ToolUseBlock` / `Anthropic.ToolResultBlockParam` for tool results, `Anthropic.Message` for responses. Defining your own `interface ChatMessage { role: string; content: unknown }` duplicates what the SDK already provides and loses type safety.
- **Report and document output:** For tasks that produce reports, documents, or visualizations, the code execution sandbox has `python-docx`, `python-pptx`, `matplotlib`, `pillow`, and `pypdf` pre-installed. Claude can generate formatted files (DOCX, PDF, charts) and return them via the Files API — consider this for "report" or "document" type requests instead of plain stdout text.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: claude-code-expert
description: "Especialista profundo em Claude Code - CLI da Anthropic. Maximiza produtividade com atalhos, hooks, MCPs, configuracoes avancadas, workflows, CLAUDE.md, memoria, sub-agentes, permissoes e integracao com ecossistemas."
risk: none
source: community
date_added: '2026-03-06'
author: renat
tags:
- claude-code
- productivity
- cli
- configuration
tools:
- claude-code
- antigravity
- cursor
- gemini-cli
- codex-cli
---

# CLAUDE CODE EXPERT - Potencia Maxima

## Overview

Especialista profundo em Claude Code - CLI da Anthropic. Maximiza produtividade com atalhos, hooks, MCPs, configuracoes avancadas, workflows, CLAUDE.md, memoria, sub-agentes, permissoes e integracao com ecossistemas. Ativar para: configurar Claude Code, criar hooks, otimizar CLAUDE.md, usar MCPs, criar sub-agentes, resolver erros do CLI, workflows avancados, duvidas sobre qualquer feature.

## When to Use This Skill

- When you need specialized assistance with this domain

## Do Not Use This Skill When

- The task is unrelated to claude code expert
- A simpler, more specific tool can handle the request
- The user needs general-purpose assistance without domain expertise

## How It Works

Voce e o especialista definitivo em Claude Code. Seu objetivo e transformar
cada sessao em uma experiencia 10x mais poderosa, rapida e inteligente.

---

## 1. Fundamentos Do Claude Code

Claude Code e a CLI oficial da Anthropic para usar Claude como agente de codigo
diretamente no terminal. Diferente do Claude.ai web, o Claude Code:
- Acessa seu filesystem diretamente
- Executa comandos bash, git, npm, etc.
- Persiste contexto via CLAUDE.md e memory files
- Suporta MCP servers (extensoes de ferramentas)
- Suporta hooks (automacoes pre/pos-acao)
- Pode criar e orquestrar sub-agentes via Task tool

## Instalacao E Setup

```bash
npm install -g @anthropic-ai/claude-code
claude                    # iniciar sessao interativa
claude "sua tarefa aqui"  # modo nao-interativo
claude --help             # ver todos os flags
```

## Flags Essenciais

```bash
claude -p "prompt"              # print mode, ideal para scripts
claude --model claude-opus-4    # especificar modelo
claude --max-tokens 8192        # limite de tokens
claude --no-stream              # sem streaming
claude --output-format json     # saida em JSON
claude --allowed-tools "Bash,Read,Write"  # limitar ferramentas
claude --dangerously-skip-permissions     # pular confirmacoes (cuidado!)
claude --max-turns 50                     # maximo de turnos autonomos
```

---

## 2. Claude.Md - O Cerebro Do Projeto

O arquivo CLAUDE.md na raiz do projeto e carregado automaticamente em TODA sessao.
E a forma mais poderosa de dar contexto e instrucoes persistentes ao Claude Code.

## Hierarquia De Claude.Md

1. ~/.claude/CLAUDE.md          global, carregado em todo projeto
2. /projeto/CLAUDE.md           nivel de projeto
3. /projeto/subpasta/CLAUDE.md  nivel de subpasta, carregado ao navegar

## Estrutura Recomendada

```markdown

## Contexto

O que e este projeto, tecnologias, arquitetura

## Comandos Essenciais

Scripts mais usados: npm run dev, pytest, etc.

## Convencoes De Codigo

Estilo, naming, patterns obrigatorios

## Arquitetura

Estrutura de pastas, responsabilidades de cada modulo

## Regras De Negocio Criticas

O que NUNCA fazer, invariantes do sistema

## Agentes E Skills Disponiveis

Lista de skills, quando usar cada uma

## Protocolo Pre-Tarefa

Sempre rodar orchestrator antes de responder
```

## Dicas De Claude.Md De Elite

- Use secao Protocolo Pre-Tarefa para garantir que o Claude sempre use orchestrator
- Adicione secao Erros Conhecidos com solucoes para problemas recorrentes
- Use secao Memoria como indice para arquivos de memoria detalhados
- Adicione exemplos concretos de output esperado
- Referencie paths absolutos para scripts criticos

---

## Localizacao Dos Arquivos De Memoria

```
~/.claude/projects/<hash-do-path>/memory/
├── MEMORY.md          # indice e contexto rapido (max 200 linhas)
├── ai-personas.md     # detalhes de personas e skills ativas
├── project-X.md       # contexto de projetos especificos
└── decisions.md       # decisoes tecnicas importantes
```

## Memoria Ativa (Em Claude.Md)

Carregar antes de qualquer tarefa: memory/MEMORY.md
Para projetos ativos: memory/ai-personas.md

## Instrucao De Salvamento Automatico:

Ao final de sessoes longas, execute:
python context-agent/scripts/context_manager.py save
```

## Context Guardian - Prevenir Perda De Contexto

O context-guardian skill monitora compactacao automatica e salva snapshots.
Ativar no inicio de sessoes longas ou criticas.

---

## 4. Hooks - Automacao Poderosa

Hooks executam comandos automaticamente em eventos do Claude Code.

## Localizacao Dos Hooks

- Global: ~/.claude/settings.json
- Por projeto: .claude/settings.json (na raiz do projeto)

## Tipos De Hooks Disponiveis

| Hook | Quando Dispara |
|------|----------------|
| PreToolUse | Antes de qualquer ferramenta ser usada |
| PostToolUse | Apos qualquer ferramenta ser usada |
| Notification | Ao receber notificacao do sistema |
| Stop | Quando o agente para de responder |
| SubagentStop | Quando sub-agente para |

## Exemplo: Hook De Beep Ao Terminar

```json
{
  "hooks": {
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "powershell -c \\"[Console]::Beep(800,300)\\""
          }
        ]
      }
    ]
  }
}
```

## Exemplo: Hook De Log De Acoes Bash

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "echo dated-action >> ~/.claude/action_log.txt"
          }
        ]
      }
    ]
  }
}
```

## Exemplo: Hook Scanner De Seguranca Pre-Commit

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python C:/Users/renat/skills/cred-omega/scripts/secret_scanner.py --staged 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}
```

## Ver E Validar Hooks Ativos

```bash
cat ~/.claude/settings.json
python -m json.tool ~/.claude/settings.json   # valida o JSON
```

---

## 5. Mcp Servers - Extensoes De Ferramentas

MCP (Model Context Protocol) permite adicionar ferramentas externas ao Claude Code.
Cada MCP server expoe novas ferramentas que o Claude pode usar nas sessoes.

## Comandos Mcp

```bash
claude mcp add filesystem       # acesso expandido a arquivos
claude mcp add github           # integracao com GitHub (PRs, issues)
claude mcp add postgres         # queries SQL em banco Postgres
claude mcp add sqlite           # queries SQL em SQLite
claude mcp list                 # listar MCPs instalados
claude mcp get nome-servidor    # detalhes de um MCP especifico
claude mcp remove nome          # remover um MCP
```

## Mcps Mais Uteis

| MCP | Funcao Principal |
|-----|------------------|
| filesystem | Acesso expandido a arquivos alem do projeto |
| github | PRs, issues, commits, reviews via Claude |
| postgres / sqlite | Consultas SQL diretas sem sair do Claude |
| puppeteer / playwright | Automacao de browser e web scraping |
| slack | Notificacoes e mensagens em canais |
| fetch | HTTP requests diretos para APIs |

## Criar Mcp Server Customizado Em Node.Js

```javascript
// mcp-server.js
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new Server({ name: "meu-mcp", version: "1.0.0" });
server.setRequestHandler("tools/call", async (req) => {
  if (req.params.name === "minha_ferramenta") {
    return { content: [{ type: "text", text: "resultado" }] };
  }
});
const transport = new StdioServerTransport();
await server.connect(transport);
```

## Adicionar Mcp Customizado

```bash
claude mcp add meu-mcp node /caminho/para/mcp-server.js
```

---

## 6. Sub-Agentes - Paralelismo Total

O Claude Code pode criar sub-agentes via Task tool para trabalho paralelo.
Cada sub-agente roda de forma independente com seu proprio contexto.

## Padroes De Orquestracao

**Spawn paralelo (multiplas tarefas simultaneas):**
Use Task tool com run_in_background: true para cada tarefa independente.
Exemplo com 3 agentes em paralelo:
- Agente 1: analisa codigo existente
- Agente 2: pesquisa documentacao
- Agente 3: escreve casos de teste
Todos rodam simultaneamente. Resultado chega via TaskOutput.

**Tipos de sub-agente:**
- general-purpose: pesquisa, analise e codigo geral
- Bash: apenas execucao de comandos de terminal
- Explore: exploracao rapida de codebase
- Plan: arquitetura e planejamento de solucoes

**Isolation com git worktree:**
Use isolation: worktree para que o sub-agente trabalhe em branch isolada.
Ideal para: experimentos, refatoracoes arriscadas, POCs sem risco ao main.

## Boas Praticas Com Sub-Agentes

1. Sempre passar CONTEXTO COMPLETO no prompt (o sub-agente nao ve o historico)
2. Especificar exatamente onde salvar outputs (use paths absolutos)
3. Usar run_in_background: true para tarefas longas
4. Verificar resultado com TaskOutput apos conclusao
5. Passar o CLAUDE.md do projeto no contexto inicial do sub-agente

---

## Configurar Permissoes Por Projeto (.Claude/Settings.Json)

```json
{
  "permissions": {
    "allow": [
      "Bash(git *)",
      "Bash(npm *)",
      "Read(*)",
      "Write(src/**)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(sudo *)",
      "Bash(curl *remote-installer*)"
    ]
  }
}
```

## Flags De Permissao Em Linha De Comando

```bash
claude --dangerously-skip-permissions        # pula TODAS as confirmacoes
claude --allowed-tools "Read,Write,Bash"     # apenas estas ferramentas
claude --disallowed-tools "WebFetch"         # bloquear especificas
```

## Quando Usar --Dangerously-Skip-Permissions

Apenas em: CI/CD controlados, scripts automatizados, sandboxes isoladas.
NUNCA usar em: producao, repos com segredos, ambientes compartilhados.

---

## Workflow De Feature Completa (4 Fases)

```bash

## Fase 1: Briefing E Planejamento

claude -p "analise a feature X e crie um plano detalhado de implementacao"

## Fase 2: Implementacao

claude "implemente a feature X seguindo o plano gerado"

## Fase 3: Testes

claude "escreva testes completos para a feature X implementada"

## Fase 4: Code Review

claude "faca code review da feature X, identifique problemas e refine"
```

## Modo Autonomo Para Ciclos Longos

```bash
claude --max-turns 100 "complete o ciclo completo de desenvolvimento da feature X"
```

## Script De Inicio De Sessao Produtiva

```bash
#\!/bin/bash
echo "Carregando contexto do projeto..."
claude -p "leia memory/MEMORY.md e me da um briefing completo do estado atual"
```

## Pipeline Ci/Cd Com Claude Code

```yaml

## .Github/Workflows/Claude-Review.Yml

- name: Claude Code Review
  env:
    ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
  run: |
    claude -p "revise o diff deste PR, identifique bugs e problemas de seguranca" \n      --output-format json \n      --no-stream \n      --max-turns 5
```

---

## Tabela De Problemas Comuns

| Problema | Causa Provavel | Solucao |
|----------|----------------|----------|
| API key not found | ANTHROPIC_API_KEY nao configurada | export ANTHROPIC_API_KEY=sk-ant-... |
| Timeout em tarefas longas | max-turns insuficiente | Adicionar --max-turns 100 |
| Context window cheio | Muitos arquivos no contexto | Usar sub-agentes com contexto focado |
| Sub-agente nao acha arquivo | Path relativo errado | Usar path absoluto sempre |
| Hook nao executa | JSON invalido em settings.json | python -m json.tool ~/.claude/settings.json |
| MCP nao conecta | Servidor MCP nao iniciado | claude mcp list e checar status |
| Compactacao inesperada | Sessao muito longa | Usar context-guardian skill |
| Erro de permissao em Bash | Tool nao permitida | Adicionar ao allow em settings.json |

## Ver Logs E Historico De Sessoes

```bash
ls ~/.claude/projects/
ls ~/.claude/projects/<hash>/
cat ~/.claude/projects/<hash>/*.jsonl | python -m json.tool
```

---

## ~/.Claude/Settings.Json Completo E Recomendado

```json
{
  "theme": "dark",
  "verbose": false,
  "cleanupPeriodDays": 30,
  "hooks": {
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "powershell -c \\"[Console]::Beep(800,200); Start-Sleep -Milliseconds 100; [Console]::Beep(1000,200)\\""
          }
        ]
      }
    ]
  },
  "permissions": {
    "allow": [
      "Bash(git *)",
      "Bash(npm *)",
      "Bash(python *)",
      "Bash(powershell *)",
      "Read(*)",
      "Write(*)"
    ]
  }
}
```

## Variaveis De Ambiente Essenciais

```bash
export ANTHROPIC_API_KEY=sk-ant-SUA_CHAVE_AQUI
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=8192
export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1   # modo privado
```

---

## Como Claude Code Se Integra Com As Skills Auri

1. CLAUDE.md global lista todas as skills disponiveis e quando usar cada uma
2. agent-orchestrator e executado em toda solicitacao para identificar skills relevantes
3. task-intelligence enriquece tarefas moderadas/complexas com briefing pre-tarefa
4. context-agent salva e restaura estado entre sessoes
5. context-guardian previne perda de contexto em sessoes longas

## Comandos Rapidos Do Ecossistema

```bash
python agent-orchestrator/scripts/scan_registry.py           # atualizar registry
python agent-orchestrator/scripts/match_skills.py "tarefa"  # identificar skills
python task-intelligence/scripts/pre_task_check.py "tarefa" # briefing
python context-agent/scripts/context_manager.py save        # salvar contexto
python context-agent/scripts/context_manager.py load        # carregar contexto
```

## Quando Esta Skill E Ativada

Esta skill e ativada automaticamente quando o usuario quer:
- Configurar ou otimizar o Claude Code CLI
- Criar, debugar ou otimizar hooks
- Adicionar ou configurar MCP servers
- Criar sub-agentes e orquestracao paralela
- Entender qualquer feature do Claude Code
- Resolver erros ou comportamentos inesperados do CLI
- Otimizar CLAUDE.md e arquivos de memoria
- Configurar permissoes e seguranca

---

## 12. Slash Commands No Claude Code

| Comando | Acao |
|---------|------|
| /status | Ver estado atual da sessao e contexto |
| /clear | Limpar historico da conversa atual |
| /compact | Compactar contexto (Claude resume o historico) |
| /memory | Ver e editar arquivos de memoria |
| /hooks | Ver hooks configurados e ativos |
| /mcp | Ver MCPs conectados e seus status |
| /cost | Ver custo em tokens e USD da sessao |
| /model | Trocar modelo em uso (opus, sonnet, haiku) |
| /help | Ver todos os comandos e atalhos disponiveis |

---

## 13. Referencias Oficiais

- Documentacao principal: https://docs.anthropic.com/claude-code
- Referencia de hooks: https://docs.anthropic.com/claude-code/hooks
- Referencia de settings: https://docs.anthropic.com/claude-code/settings
- MCP SDK e exemplos: https://github.com/modelcontextprotocol/sdk
- Repositorio oficial: https://github.com/anthropics/claude-code
- Release notes: https://docs.anthropic.com/claude-code/changelog

## Best Practices

- Provide clear, specific context about your project and requirements
- Review all suggestions before applying them to production code
- Combine with other complementary skills for comprehensive analysis

## Common Pitfalls

- Using this skill for tasks outside its domain expertise
- Applying recommendations without understanding your specific context
- Not providing enough project context for accurate analysis

## Related Skills

- `007` - Complementary skill for enhanced analysis
- `matematico-tao` - Complementary skill for enhanced analysis

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: claude-code-guide
description: "To provide a comprehensive reference for configuring and using Claude Code (the agentic coding tool) to its full potential. This skill synthesizes best practices, configuration templates, and advanced usage patterns."
risk: critical
source: community
date_added: "2026-02-27"
---

# Claude Code Guide

## Purpose

To provide a comprehensive reference for configuring and using Claude Code (the agentic coding tool) to its full potential. This skill synthesizes best practices, configuration templates, and advanced usage patterns.

## Configuration (`CLAUDE.md`)

When starting a new project, create a `CLAUDE.md` file in the root directory to guide the agent.

### Template (General)

```markdown
# Project Guidelines

## Commands

- Run app: `npm run dev`
- Test: `npm test`
- Build: `npm run build`

## Code Style

- Use TypeScript for all new code.
- Functional components with Hooks for React.
- Tailwind CSS for styling.
- Early returns for error handling.

## Workflow

- Read `README.md` first to understand project context.
- Before editing, read the file content.
- After editing, run tests to verify.
```

## Advanced Features

### Thinking Keywords

Use these keywords in your prompts to trigger deeper reasoning from the agent:

- "Think step-by-step"
- "Analyze the root cause"
- "Plan before executing"
- "Verify your assumptions"

### Debugging

If the agent is stuck or behaving unexpectedly:

1. **Clear Context**: Start a new session or ask the agent to "forget previous instructions" if confused.
2. **Explicit Instructions**: Be extremely specific about paths, filenames, and desired outcomes.
3. **Logs**: Ask the agent to "check the logs" or "run the command with verbose output".

## Best Practices

1. **Small Contexts**: Don't dump the entire codebase into the context. Use `grep` or `find` to locate relevant files first.
2. **Iterative Development**: Ask for small changes, verify, then proceed.
3. **Feedback Loop**: If the agent makes a mistake, correct it immediately and ask it to "add a lesson" to its memory (if supported) or `CLAUDE.md`.

## Reference

Based on [Claude Code Guide by zebbern](https://github.com/zebbern/claude-code-guide).

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: claude-d3js-skill
description: "This skill provides guidance for creating sophisticated, interactive data visualisations using d3.js."
risk: critical
source: community
date_added: "2026-02-27"
---

# D3.js Visualisation

## Overview

This skill provides guidance for creating sophisticated, interactive data visualisations using d3.js. D3.js (Data-Driven Documents) excels at binding data to DOM elements and applying data-driven transformations to create custom, publication-quality visualisations with precise control over every visual element. The techniques work across any JavaScript environment, including vanilla JavaScript, React, Vue, Svelte, and other frameworks.

## When to use d3.js

**Use d3.js for:**
- Custom visualisations requiring unique visual encodings or layouts
- Interactive explorations with complex pan, zoom, or brush behaviours
- Network/graph visualisations (force-directed layouts, tree diagrams, hierarchies, chord diagrams)
- Geographic visualisations with custom projections
- Visualisations requiring smooth, choreographed transitions
- Publication-quality graphics with fine-grained styling control
- Novel chart types not available in standard libraries

**Consider alternatives for:**
- 3D visualisations - use Three.js instead

## Core workflow

### 1. Set up d3.js

Import d3 at the top of your script:

```javascript
import * as d3 from 'd3';
```

Or use the CDN version (7.x):

```html
<script src="https://d3js.org/d3.v7.min.js"></script>
```

All modules (scales, axes, shapes, transitions, etc.) are accessible through the `d3` namespace.

### 2. Choose the integration pattern

**Pattern A: Direct DOM manipulation (recommended for most cases)**
Use d3 to select DOM elements and manipulate them imperatively. This works in any JavaScript environment:

```javascript
function drawChart(data) {
  if (!data || data.length === 0) return;

  const svg = d3.select('#chart'); // Select by ID, class, or DOM element

  // Clear previous content
  svg.selectAll("*").remove();

  // Set up dimensions
  const width = 800;
  const height = 400;
  const margin = { top: 20, right: 30, bottom: 40, left: 50 };

  // Create scales, axes, and draw visualisation
  // ... d3 code here ...
}

// Call when data changes
drawChart(myData);
```

**Pattern B: Declarative rendering (for frameworks with templating)**
Use d3 for data calculations (scales, layouts) but render elements via your framework:

```javascript
function getChartElements(data) {
  const xScale = d3.scaleLinear()
    .domain([0, d3.max(data, d => d.value)])
    .range([0, 400]);

  return data.map((d, i) => ({
    x: 50,
    y: i * 30,
    width: xScale(d.value),
    height: 25
  }));
}

// In React: {getChartElements(data).map((d, i) => <rect key={i} {...d} fill="steelblue" />)}
// In Vue: v-for directive over the returned array
// In vanilla JS: Create elements manually from the returned data
```

Use Pattern A for complex visualisations with transitions, interactions, or when leveraging d3's full capabilities. Use Pattern B for simpler visualisations or when your framework prefers declarative rendering.

### 3. Structure the visualisation code

Follow this standard structure in your drawing function:

```javascript
function drawVisualization(data) {
  if (!data || data.length === 0) return;

  const svg = d3.select('#chart'); // Or pass a selector/element
  svg.selectAll("*").remove(); // Clear previous render

  // 1. Define dimensions
  const width = 800;
  const height = 400;
  const margin = { top: 20, right: 30, bottom: 40, left: 50 };
  const innerWidth = width - margin.left - margin.right;
  const innerHeight = height - margin.top - margin.bottom;

  // 2. Create main group with margins
  const g = svg.append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`);

  // 3. Create scales
  const xScale = d3.scaleLinear()
    .domain([0, d3.max(data, d => d.x)])
    .range([0, innerWidth]);

  const yScale = d3.scaleLinear()
    .domain([0, d3.max(data, d => d.y)])
    .range([innerHeight, 0]); // Note: inverted for SVG coordinates

  // 4. Create and append axes
  const xAxis = d3.axisBottom(xScale);
  const yAxis = d3.axisLeft(yScale);

  g.append("g")
    .attr("transform", `translate(0,${innerHeight})`)
    .call(xAxis);

  g.append("g")
    .call(yAxis);

  // 5. Bind data and create visual elements
  g.selectAll("circle")
    .data(data)
    .join("circle")
    .attr("cx", d => xScale(d.x))
    .attr("cy", d => yScale(d.y))
    .attr("r", 5)
    .attr("fill", "steelblue");
}

// Call when data changes
drawVisualization(myData);
```

### 4. Implement responsive sizing

Make visualisations responsive to container size:

```javascript
function setupResponsiveChart(containerId, data) {
  const container = document.getElementById(containerId);
  const svg = d3.select(`#${containerId}`).append('svg');

  function updateChart() {
    const { width, height } = container.getBoundingClientRect();
    svg.attr('width', width).attr('height', height);

    // Redraw visualisation with new dimensions
    drawChart(data, svg, width, height);
  }

  // Update on initial load
  updateChart();

  // Update on window resize
  window.addEventListener('resize', updateChart);

  // Return cleanup function
  return () => window.removeEventListener('resize', updateChart);
}

// Usage:
// const cleanup = setupResponsiveChart('chart-container', myData);
// cleanup(); // Call when component unmounts or element removed
```

Or use ResizeObserver for more direct container monitoring:

```javascript
function setupResponsiveChartWithObserver(svgElement, data) {
  const observer = new ResizeObserver(() => {
    const { width, height } = svgElement.getBoundingClientRect();
    d3.select(svgElement)
      .attr('width', width)
      .attr('height', height);

    // Redraw visualisation
    drawChart(data, d3.select(svgElement), width, height);
  });

  observer.observe(svgElement.parentElement);
  return () => observer.disconnect();
}
```

## Common visualisation patterns

### Bar chart

```javascript
function drawBarChart(data, svgElement) {
  if (!data || data.length === 0) return;

  const svg = d3.select(svgElement);
  svg.selectAll("*").remove();

  const width = 800;
  const height = 400;
  const margin = { top: 20, right: 30, bottom: 40, left: 50 };
  const innerWidth = width - margin.left - margin.right;
  const innerHeight = height - margin.top - margin.bottom;

  const g = svg.append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`);

  const xScale = d3.scaleBand()
    .domain(data.map(d => d.category))
    .range([0, innerWidth])
    .padding(0.1);

  const yScale = d3.scaleLinear()
    .domain([0, d3.max(data, d => d.value)])
    .range([innerHeight, 0]);

  g.append("g")
    .attr("transform", `translate(0,${innerHeight})`)
    .call(d3.axisBottom(xScale));

  g.append("g")
    .call(d3.axisLeft(yScale));

  g.selectAll("rect")
    .data(data)
    .join("rect")
    .attr("x", d => xScale(d.category))
    .attr("y", d => yScale(d.value))
    .attr("width", xScale.bandwidth())
    .attr("height", d => innerHeight - yScale(d.value))
    .attr("fill", "steelblue");
}

// Usage:
// drawBarChart(myData, document.getElementById('chart'));
```

### Line chart

```javascript
const line = d3.line()
  .x(d => xScale(d.date))
  .y(d => yScale(d.value))
  .curve(d3.curveMonotoneX); // Smooth curve

g.append("path")
  .datum(data)
  .attr("fill", "none")
  .attr("stroke", "steelblue")
  .attr("stroke-width", 2)
  .attr("d", line);
```

### Scatter plot

```javascript
g.selectAll("circle")
  .data(data)
  .join("circle")
  .attr("cx", d => xScale(d.x))
  .attr("cy", d => yScale(d.y))
  .attr("r", d => sizeScale(d.size)) // Optional: size encoding
  .attr("fill", d => colourScale(d.category)) // Optional: colour encoding
  .attr("opacity", 0.7);
```

### Chord diagram

A chord diagram shows relationships between entities in a circular layout, with ribbons representing flows between them:

```javascript
function drawChordDiagram(data) {
  // data format: array of objects with source, target, and value
  // Example: [{ source: 'A', target: 'B', value: 10 }, ...]

  if (!data || data.length === 0) return;

  const svg = d3.select('#chart');
  svg.selectAll("*").remove();

  const width = 600;
  const height = 600;
  const innerRadius = Math.min(width, height) * 0.3;
  const outerRadius = innerRadius + 30;

  // Create matrix from data
  const nodes = Array.from(new Set(data.flatMap(d => [d.source, d.target])));
  const matrix = Array.from({ length: nodes.length }, () => Array(nodes.length).fill(0));

  data.forEach(d => {
    const i = nodes.indexOf(d.source);
    const j = nodes.indexOf(d.target);
    matrix[i][j] += d.value;
    matrix[j][i] += d.value;
  });

  // Create chord layout
  const chord = d3.chord()
    .padAngle(0.05)
    .sortSubgroups(d3.descending);

  const arc = d3.arc()
    .innerRadius(innerRadius)
    .outerRadius(outerRadius);

  const ribbon = d3.ribbon()
    .source(d => d.source)
    .target(d => d.target);

  const colourScale = d3.scaleOrdinal(d3.schemeCategory10)
    .domain(nodes);

  const g = svg.append("g")
    .attr("transform", `translate(${width / 2},${height / 2})`);

  const chords = chord(matrix);

  // Draw ribbons
  g.append("g")
    .attr("fill-opacity", 0.67)
    .selectAll("path")
    .data(chords)
    .join("path")
    .attr("d", ribbon)
    .attr("fill", d => colourScale(nodes[d.source.index]))
    .attr("stroke", d => d3.rgb(colourScale(nodes[d.source.index])).darker());

  // Draw groups (arcs)
  const group = g.append("g")
    .selectAll("g")
    .data(chords.groups)
    .join("g");

  group.append("path")
    .attr("d", arc)
    .attr("fill", d => colourScale(nodes[d.index]))
    .attr("stroke", d => d3.rgb(colourScale(nodes[d.index])).darker());

  // Add labels
  group.append("text")
    .each(d => { d.angle = (d.startAngle + d.endAngle) / 2; })
    .attr("dy", "0.31em")
    .attr("transform", d => `rotate(${(d.angle * 180 / Math.PI) - 90})translate(${outerRadius + 30})${d.angle > Math.PI ? "rotate(180)" : ""}`)
    .attr("text-anchor", d => d.angle > Math.PI ? "end" : null)
    .text((d, i) => nodes[i])
    .style("font-size", "12px");
}
```

### Heatmap

A heatmap uses colour to encode values in a two-dimensional grid, useful for showing patterns across categories:

```javascript
function drawHeatmap(data) {
  // data format: array of objects with row, column, and value
  // Example: [{ row: 'A', column: 'X', value: 10 }, ...]

  if (!data || data.length === 0) return;

  const svg = d3.select('#chart');
  svg.selectAll("*").remove();

  const width = 800;
  const height = 600;
  const margin = { top: 100, right: 30, bottom: 30, left: 100 };
  const innerWidth = width - margin.left - margin.right;
  const innerHeight = height - margin.top - margin.bottom;

  // Get unique rows and columns
  const rows = Array.from(new Set(data.map(d => d.row)));
  const columns = Array.from(new Set(data.map(d => d.column)));

  const g = svg.append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`);

  // Create scales
  const xScale = d3.scaleBand()
    .domain(columns)
    .range([0, innerWidth])
    .padding(0.01);

  const yScale = d3.scaleBand()
    .domain(rows)
    .range([0, innerHeight])
    .padding(0.01);

  // Colour scale for values
  const colourScale = d3.scaleSequential(d3.interpolateYlOrRd)
    .domain([0, d3.max(data, d => d.value)]);

  // Draw rectangles
  g.selectAll("rect")
    .data(data)
    .join("rect")
    .attr("x", d => xScale(d.column))
    .attr("y", d => yScale(d.row))
    .attr("width", xScale.bandwidth())
    .attr("height", yScale.bandwidth())
    .attr("fill", d => colourScale(d.value));

  // Add x-axis labels
  svg.append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`)
    .selectAll("text")
    .data(columns)
    .join("text")
    .attr("x", d => xScale(d) + xScale.bandwidth() / 2)
    .attr("y", -10)
    .attr("text-anchor", "middle")
    .text(d => d)
    .style("font-size", "12px");

  // Add y-axis labels
  svg.append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`)
    .selectAll("text")
    .data(rows)
    .join("text")
    .attr("x", -10)
    .attr("y", d => yScale(d) + yScale.bandwidth() / 2)
    .attr("dy", "0.35em")
    .attr("text-anchor", "end")
    .text(d => d)
    .style("font-size", "12px");

  // Add colour legend
  const legendWidth = 20;
  const legendHeight = 200;
  const legend = svg.append("g")
    .attr("transform", `translate(${width - 60},${margin.top})`);

  const legendScale = d3.scaleLinear()
    .domain(colourScale.domain())
    .range([legendHeight, 0]);

  const legendAxis = d3.axisRight(legendScale)
    .ticks(5);

  // Draw colour gradient in legend
  for (let i = 0; i < legendHeight; i++) {
    legend.append("rect")
      .attr("y", i)
      .attr("width", legendWidth)
      .attr("height", 1)
      .attr("fill", colourScale(legendScale.invert(i)));
  }

  legend.append("g")
    .attr("transform", `translate(${legendWidth},0)`)
    .call(legendAxis);
}
```

### Pie chart

```javascript
const pie = d3.pie()
  .value(d => d.value)
  .sort(null);

const arc = d3.arc()
  .innerRadius(0)
  .outerRadius(Math.min(width, height) / 2 - 20);

const colourScale = d3.scaleOrdinal(d3.schemeCategory10);

const g = svg.append("g")
  .attr("transform", `translate(${width / 2},${height / 2})`);

g.selectAll("path")
  .data(pie(data))
  .join("path")
  .attr("d", arc)
  .attr("fill", (d, i) => colourScale(i))
  .attr("stroke", "white")
  .attr("stroke-width", 2);
```

### Force-directed network

```javascript
const simulation = d3.forceSimulation(nodes)
  .force("link", d3.forceLink(links).id(d => d.id).distance(100))
  .force("charge", d3.forceManyBody().strength(-300))
  .force("center", d3.forceCenter(width / 2, height / 2));

const link = g.selectAll("line")
  .data(links)
  .join("line")
  .attr("stroke", "#999")
  .attr("stroke-width", 1);

const node = g.selectAll("circle")
  .data(nodes)
  .join("circle")
  .attr("r", 8)
  .attr("fill", "steelblue")
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));

simulation.on("tick", () => {
  link
    .attr("x1", d => d.source.x)
    .attr("y1", d => d.source.y)
    .attr("x2", d => d.target.x)
    .attr("y2", d => d.target.y);

  node
    .attr("cx", d => d.x)
    .attr("cy", d => d.y);
});

function dragstarted(event) {
  if (!event.active) simulation.alphaTarget(0.3).restart();
  event.subject.fx = event.subject.x;
  event.subject.fy = event.subject.y;
}

function dragged(event) {
  event.subject.fx = event.x;
  event.subject.fy = event.y;
}

function dragended(event) {
  if (!event.active) simulation.alphaTarget(0);
  event.subject.fx = null;
  event.subject.fy = null;
}
```

## Adding interactivity

### Tooltips

```javascript
// Create tooltip div (outside SVG)
const tooltip = d3.select("body").append("div")
  .attr("class", "tooltip")
  .style("position", "absolute")
  .style("visibility", "hidden")
  .style("background-color", "white")
  .style("border", "1px solid #ddd")
  .style("padding", "10px")
  .style("border-radius", "4px")
  .style("pointer-events", "none");

// Add to elements
circles
  .on("mouseover", function(event, d) {
    d3.select(this).attr("opacity", 1);
    tooltip
      .style("visibility", "visible")
      .html(`<strong>${d.label}</strong><br/>Value: ${d.value}`);
  })
  .on("mousemove", function(event) {
    tooltip
      .style("top", (event.pageY - 10) + "px")
      .style("left", (event.pageX + 10) + "px");
  })
  .on("mouseout", function() {
    d3.select(this).attr("opacity", 0.7);
    tooltip.style("visibility", "hidden");
  });
```

### Zoom and pan

```javascript
const zoom = d3.zoom()
  .scaleExtent([0.5, 10])
  .on("zoom", (event) => {
    g.attr("transform", event.transform);
  });

svg.call(zoom);
```

### Click interactions

```javascript
circles
  .on("click", function(event, d) {
    // Handle click (dispatch event, update app state, etc.)
    console.log("Clicked:", d);

    // Visual feedback
    d3.selectAll("circle").attr("fill", "steelblue");
    d3.select(this).attr("fill", "orange");

    // Optional: dispatch custom event for your framework/app to listen to
    // window.dispatchEvent(new CustomEvent('chartClick', { detail: d }));
  });
```

## Transitions and animations

Add smooth transitions to visual changes:

```javascript
// Basic transition
circles
  .transition()
  .duration(750)
  .attr("r", 10);

// Chained transitions
circles
  .transition()
  .duration(500)
  .attr("fill", "orange")
  .transition()
  .duration(500)
  .attr("r", 15);

// Staggered transitions
circles
  .transition()
  .delay((d, i) => i * 50)
  .duration(500)
  .attr("cy", d => yScale(d.value));

// Custom easing
circles
  .transition()
  .duration(1000)
  .ease(d3.easeBounceOut)
  .attr("r", 10);
```

## Scales reference

### Quantitative scales

```javascript
// Linear scale
const xScale = d3.scaleLinear()
  .domain([0, 100])
  .range([0, 500]);

// Log scale (for exponential data)
const logScale = d3.scaleLog()
  .domain([1, 1000])
  .range([0, 500]);

// Power scale
const powScale = d3.scalePow()
  .exponent(2)
  .domain([0, 100])
  .range([0, 500]);

// Time scale
const timeScale = d3.scaleTime()
  .domain([new Date(2020, 0, 1), new Date(2024, 0, 1)])
  .range([0, 500]);
```

### Ordinal scales

```javascript
// Band scale (for bar charts)
const bandScale = d3.scaleBand()
  .domain(['A', 'B', 'C', 'D'])
  .range([0, 400])
  .padding(0.1);

// Point scale (for line/scatter categories)
const pointScale = d3.scalePoint()
  .domain(['A', 'B', 'C', 'D'])
  .range([0, 400]);

// Ordinal scale (for colours)
const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
```

### Sequential scales

```javascript
// Sequential colour scale
const colourScale = d3.scaleSequential(d3.interpolateBlues)
  .domain([0, 100]);

// Diverging colour scale
const divScale = d3.scaleDiverging(d3.interpolateRdBu)
  .domain([-10, 0, 10]);
```

## Best practices

### Data preparation

Always validate and prepare data before visualisation:

```javascript
// Filter invalid values
const cleanData = data.filter(d => d.value != null && !isNaN(d.value));

// Sort data if order matters
const sortedData = [...data].sort((a, b) => b.value - a.value);

// Parse dates
const parsedData = data.map(d => ({
  ...d,
  date: d3.timeParse("%Y-%m-%d")(d.date)
}));
```

### Performance optimisation

For large datasets (>1000 elements):

```javascript
// Use canvas instead of SVG for many elements
// Use quadtree for collision detection
// Simplify paths with d3.line().curve(d3.curveStep)
// Implement virtual scrolling for large lists
// Use requestAnimationFrame for custom animations
```

### Accessibility

Make visualisations accessible:

```javascript
// Add ARIA labels
svg.attr("role", "img")
   .attr("aria-label", "Bar chart showing quarterly revenue");

// Add title and description
svg.append("title").text("Quarterly Revenue 2024");
svg.append("desc").text("Bar chart showing revenue growth across four quarters");

// Ensure sufficient colour contrast
// Provide keyboard navigation for interactive elements
// Include data table alternative
```

### Styling

Use consistent, professional styling:

```javascript
// Define colour palettes upfront
const colours = {
  primary: '#4A90E2',
  secondary: '#7B68EE',
  background: '#F5F7FA',
  text: '#333333',
  gridLines: '#E0E0E0'
};

// Apply consistent typography
svg.selectAll("text")
  .style("font-family", "Inter, sans-serif")
  .style("font-size", "12px");

// Use subtle grid lines
g.selectAll(".tick line")
  .attr("stroke", colours.gridLines)
  .attr("stroke-dasharray", "2,2");
```

## Common issues and solutions

**Issue**: Axes not appearing
- Ensure scales have valid domains (check for NaN values)
- Verify axis is appended to correct group
- Check transform translations are correct

**Issue**: Transitions not working
- Call `.transition()` before attribute changes
- Ensure elements have unique keys for proper data binding
- Check that useEffect dependencies include all changing data

**Issue**: Responsive sizing not working
- Use ResizeObserver or window resize listener
- Update dimensions in state to trigger re-render
- Ensure SVG has width/height attributes or viewBox

**Issue**: Performance problems
- Limit number of DOM elements (consider canvas for >1000 items)
- Debounce resize handlers
- Use `.join()` instead of separate enter/update/exit selections
- Avoid unnecessary re-renders by checking dependencies

## Resources

### references/
Contains detailed reference materials:
- `d3-patterns.md` - Comprehensive collection of visualisation patterns and code examples
- `scale-reference.md` - Complete guide to d3 scales with examples
- `colour-schemes.md` - D3 colour schemes and palette recommendations

### assets/

Contains boilerplate templates:

- `chart-template.js` - Starter template for basic chart
- `interactive-template.js` - Template with tooltips, zoom, and interactions
- `sample-data.json` - Example datasets for testing

These templates work with vanilla JavaScript, React, Vue, Svelte, or any other JavaScript environment. Adapt them as needed for your specific framework.

To use these resources, read the relevant files when detailed guidance is needed for specific visualisation types or patterns.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: claude-delegate
description: Delegate coding tasks to a separate Claude Code CLI process or Claude
  session only when the user explicitly requests it, while the orchestrator retains
  review and landing responsibility.
risk: safe
category: agent-orchestration
source: https://github.com/amElnagdy/delegate-skills
source_repo: amElnagdy/delegate-skills
source_type: community
date_added: '2026-08-26'
license: MIT
license_source: https://github.com/amElnagdy/delegate-skills/blob/master/LICENSE
compatibility: Requires the `claude` CLI (Claude Code) installed and authenticated,
  Node 18+, and git. The orchestrating agent must be able to run shell commands and
  read files. Claude's shell sandbox requires macOS, Linux, or WSL2; native Windows
  launch is pending verification.
metadata:
  version: 0.5.0
---
# Claude Delegate

## When to Use

- You want to delegate a bounded coding task to a separate `claude` implementer (`Claude Code`) and then review its diff yourself.
- The user explicitly asked for delegation to this implementer.

You are the **orchestrator**. Delegate one bounded coding task to a separate **implementer** — a Claude
Code CLI session — then review what it produced and land it yourself. You write the brief and own the
judgment; the separate Claude session edits the working tree; you verify and commit.

This skill is not a signal for the current Claude to implement directly. Use it only after the human
explicitly asks for delegation to another Claude Code process or session.

## When not to use this

- The human asked the current agent to implement the task directly.
- The task is small enough to do inline and the human did not request delegation.
- The `claude` CLI is missing or unauthenticated (`claude auth status`).
- The task needs a stronger host boundary than Claude Code's tool permissions and shell-only sandbox
  provide. Use an isolated container or VM for that requirement.

## Prerequisites

1. `claude --version` succeeds.
2. `claude auth status` reports an authenticated session. On macOS the live credentials sit in the
   login Keychain; when the orchestrator's own sandbox blocks Keychain access (Codex's sandbox
   does), `claude` falls back to a possibly stale credentials file and reports `loggedIn: false`
   even though the login is valid. Re-run the check — and the dispatch itself — with that sandbox
   escalated or outside it before concluding the CLI is unauthenticated.
3. The target repository is the directory passed with `--cd`.
4. On Linux/WSL2, Claude's sandbox dependencies are installed. The normal relay profile is
   configured to fail when the sandbox is unavailable instead of silently running shell commands
   unsandboxed. Existing merged settings can still affect the effective boundary.

## The loop

### 1. Write the brief

The separate session has no orchestrator chat history. It receives the brief on stdin and can inspect
the target working tree.

Claude Code automatically discovers the target project's `CLAUDE.md` and normal local Claude
configuration because the relay does not use `--bare`. It does **not** generically auto-load
`AGENTS.md`. Read `AGENTS.md` yourself and copy every load-bearing constraint and the real gate
commands into the brief. Tell the implementer not to commit. Keep one task per brief.

Template and details: [references/writing-the-brief.md](references/writing-the-brief.md).

### 2. Dispatch

```bash
node "<skill-dir>/scripts/relay.mjs" --brief brief.txt --cd /path/to/repo
# review/diagnosis only:                 add --read-only
# continue the latest session:           add --resume-last
# continue the recorded session:         add --session <id>
# choose limits:                         add --max-turns 40 --max-budget-usd 10
# hard relay deadline:                   add --timeout 2h
# inspect every option:                  node .../relay.mjs --help
```

`<skill-dir>` is this installed skill directory, the folder containing this `SKILL.md`.

The relay runs `claude -p --output-format stream-json --verbose`, sends the brief through stdin, and
writes artifacts under the system temp directory by default. It never uses `--bg` or `--bare`, and it
never commits. See [references/dispatch-and-poll.md](references/dispatch-and-poll.md).

### 3. Wait

The relay blocks until Claude exits. Use the orchestrator's background-command facility, or run it in
the foreground and wait. Completion means the process exited and `result.json` exists.

- A pre-run usage error exits 2 and writes no `result.json`.
- A missing `claude` exits 127 and writes `status: "claude_unavailable"`.
- Timeout and caught relay signals terminate the whole implementer process tree and preserve an
  outcome artifact.

Read `finalMessage`, `touchedFiles`, `resultSubtype`, and the raw artifact paths from `result.json`.

### 4. Review

Treat the implementer's report and gate outcomes as claims:

- Review edits to existing tests before a green gate means anything.
- Re-run the project's actual gates yourself.
- Read the complete diff against the brief, starting with `touchedFiles`.
- Inspect untracked and staged content as well as the ordinary diff.
- Run relevant guard skills if installed.

Full checklist: [references/review-and-land.md](references/review-and-land.md).

### 5. Land

The **orchestrator commits** only after the gates pass and the diff holds. For rework, resume the same
Claude session with a delta brief:

```bash
echo "Keep the implementation, replace the mocked DB test with the migrated fixture, and remove the
unused import." | node "<skill-dir>/scripts/relay.mjs" --session <id> --cd /path/to/repo
```

Review a resumed run exactly like the first run.

## Permission profiles

The normal profile is deliberately explicit:

- `acceptEdits` permission mode.
- Built-in tools restricted to Read, Glob, Grep, Edit, Write, and the platform shell.
- On macOS, Linux, and WSL2, Claude's shell sandbox is enabled with startup failure on missing
  dependencies and no unsandboxed retry. Commands that stay sandboxed are auto-approved so ordinary
  gates can run headlessly. The sandbox governs shell processes and their children only; merged
  local or managed sandbox settings can add effective paths or exclusions.
- Configured MCP discovery and Claude.ai connectors are disabled, all MCP tools are denied, and
  skills, commands, and Claude's Agent tool are unavailable to the child. Project `CLAUDE.md`, hooks,
  normal authentication, session persistence, and other local settings still load.
- String rules deny common direct shell forms of `git commit`, `git push`, and nested `claude`, plus
  any command containing `claude-delegate`. Aliases, scripts, and wrappers can bypass them, so they
  are only a speed bump; the brief's no-commit instruction and orchestrator review remain the boundary.

Native Windows does not support Claude's shell sandbox. The relay restricts the tool surface and
pre-approves PowerShell so the run remains non-interactive, but that shell is not OS-isolated. Native
`claude.exe` and npm `claude.cmd` launch paths are implemented; Windows verification is pending.

`--read-only` uses `plan` mode with only Read, Glob, and Grep. It removes edit, write, and shell paths,
then compares parsed git porcelain and fingerprints the working-tree identity and index entries of
Git-visible paths that were already dirty.
`readOnlyViolation` is `true` when either signal proves a change, `false` when coverage is complete and
detects none, and `null` when coverage is incomplete. This is a reporting tripwire, not an OS boundary:
ignored paths and perfect restores are outside it, local hooks can write, and concurrent changes cannot
be attributed to Claude.

`--dangerously-skip-permissions` is an explicit opt-in to Claude's `bypassPermissions` mode. The
restricted tool surface, direct commit/push deny rules, and supported-platform shell sandbox remain,
but direct file tools can cross normal permission boundaries. Use it only with the human's explicit
acceptance.

## Complementary to native Claude features

Claude subagents, agent teams, and background sessions are useful when the current Claude environment
is already the orchestrator and native coordination is the goal. This skill is complementary: it
provides a cross-orchestrator contract — self-contained brief → dispatch → artifacts → review → land
— and keeps the commit with the orchestrator.

## References

- [references/writing-the-brief.md](references/writing-the-brief.md) — context, `CLAUDE.md` versus
  `AGENTS.md`, real gates, report contract, and delta briefs.
- [references/dispatch-and-poll.md](references/dispatch-and-poll.md) — flags, profiles, artifacts,
  `result.json`, polling, and failure recovery.
- [references/review-and-land.md](references/review-and-land.md) — generated-code review, the commit
  boundary, and session rework.
- [references/multi-task-queues.md](references/multi-task-queues.md) — sequential queues, progress
  tracking, constraint carry-forward, and final coherence.

## Limitations

- Docs-only import — executable `scripts/relay.mjs` not included; see upstream for full runtime. Requires `claude` CLI, Node 18+, git.
- Relay never commits — it only returns structured result JSON; you review and land the commit.

> Adapted from [amElnagdy/delegate-skills](https://github.com/amElnagdy/delegate-skills) (MIT) — docs-only, runtime not bundled.


---
name: claude-in-chrome-troubleshooting
description: Diagnose and fix Claude in Chrome MCP extension connectivity issues. Use when mcp__claude-in-chrome__* tools fail, return "Browser extension is not connected", or behave erratically.
risk: critical
source: community
---

# Claude in Chrome MCP Troubleshooting

Use this skill when Claude in Chrome MCP tools fail to connect or work unreliably.

## When to Use
- `mcp__claude-in-chrome__*` tools fail with "Browser extension is not connected"
- Browser automation works erratically or times out
- After updating Claude Code or Claude.app
- When switching between Claude Code CLI and Claude.app (Cowork)
- Native host process is running but MCP tools still fail

## When NOT to Use

- **Linux or Windows users** - This skill covers macOS-specific paths and tools (`~/Library/Application Support/`, `osascript`)
- General Chrome automation issues unrelated to the Claude extension
- Claude.app desktop issues (not browser-related)
- Network connectivity problems
- Chrome extension installation issues (use Chrome Web Store support)

## The Claude.app vs Claude Code Conflict (Primary Issue)

**Background:** When Claude.app added Cowork support (browser automation from the desktop app), it introduced a competing native messaging host that conflicts with Claude Code CLI.

### Two Native Hosts, Two Socket Formats

| Component | Native Host Binary | Socket Location |
|-----------|-------------------|-----------------|
| **Claude.app (Cowork)** | `/Applications/Claude.app/Contents/Helpers/chrome-native-host` | `/tmp/claude-mcp-browser-bridge-$USER/<PID>.sock` |
| **Claude Code CLI** | `~/.local/share/claude/versions/<version> --chrome-native-host` | `$TMPDIR/claude-mcp-browser-bridge-$USER` (single file) |

### Why They Conflict

1. Both register native messaging configs in Chrome:
   - `com.anthropic.claude_browser_extension.json` → Claude.app helper
   - `com.anthropic.claude_code_browser_extension.json` → Claude Code wrapper

2. Chrome extension requests a native host by name
3. If the wrong config is active, the wrong binary runs
4. The wrong binary creates sockets in a format/location the MCP client doesn't expect
5. Result: "Browser extension is not connected" even though everything appears to be running

### The Fix: Disable Claude.app's Native Host

**If you use Claude Code CLI for browser automation (not Cowork):**

```bash
# Disable the Claude.app native messaging config
mv ~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_browser_extension.json \
   ~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_browser_extension.json.disabled

# Ensure the Claude Code config exists and points to the wrapper
cat ~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json
```

**If you use Cowork (Claude.app) for browser automation:**

```bash
# Disable the Claude Code native messaging config
mv ~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json \
   ~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json.disabled
```

**You cannot use both simultaneously.** Pick one and disable the other.

### Toggle Script

Add this to `~/.zshrc` or run directly:

```bash
chrome-mcp-toggle() {
    local CONFIG_DIR=~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts
    local CLAUDE_APP="$CONFIG_DIR/com.anthropic.claude_browser_extension.json"
    local CLAUDE_CODE="$CONFIG_DIR/com.anthropic.claude_code_browser_extension.json"

    if [[ -f "$CLAUDE_APP" && ! -f "$CLAUDE_APP.disabled" ]]; then
        # Currently using Claude.app, switch to Claude Code
        mv "$CLAUDE_APP" "$CLAUDE_APP.disabled"
        [[ -f "$CLAUDE_CODE.disabled" ]] && mv "$CLAUDE_CODE.disabled" "$CLAUDE_CODE"
        echo "Switched to Claude Code CLI"
        echo "Restart Chrome and Claude Code to apply"
    elif [[ -f "$CLAUDE_CODE" && ! -f "$CLAUDE_CODE.disabled" ]]; then
        # Currently using Claude Code, switch to Claude.app
        mv "$CLAUDE_CODE" "$CLAUDE_CODE.disabled"
        [[ -f "$CLAUDE_APP.disabled" ]] && mv "$CLAUDE_APP.disabled" "$CLAUDE_APP"
        echo "Switched to Claude.app (Cowork)"
        echo "Restart Chrome to apply"
    else
        echo "Current state unclear. Check configs:"
        ls -la "$CONFIG_DIR"/com.anthropic*.json* 2>/dev/null
    fi
}
```

Usage: `chrome-mcp-toggle` then restart Chrome (and Claude Code if switching to CLI).

## Quick Diagnosis

```bash
# 1. Which native host binary is running?
ps aux | grep chrome-native-host | grep -v grep
# Claude.app: /Applications/Claude.app/Contents/Helpers/chrome-native-host
# Claude Code: ~/.local/share/claude/versions/X.X.X --chrome-native-host

# 2. Where is the socket?
# For Claude Code (single file in TMPDIR):
ls -la "$(getconf DARWIN_USER_TEMP_DIR)/claude-mcp-browser-bridge-$USER" 2>&1

# For Claude.app (directory with PID files):
ls -la /tmp/claude-mcp-browser-bridge-$USER/ 2>&1

# 3. What's the native host connected to?
lsof -U 2>&1 | grep claude-mcp-browser-bridge

# 4. Which configs are active?
ls ~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/com.anthropic*.json
```

## Critical Insight

**MCP connects at startup.** If the browser bridge wasn't ready when Claude Code started, the connection will fail for the entire session. The fix is usually: ensure Chrome + extension are running with correct config, THEN restart Claude Code.

## Full Reset Procedure (Claude Code CLI)

```bash
# 1. Ensure correct config is active
mv ~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_browser_extension.json \
   ~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_browser_extension.json.disabled 2>/dev/null

# 2. Update the wrapper to use latest Claude Code version
cat > ~/.claude/chrome/chrome-native-host << 'EOF'
#!/bin/bash
LATEST=$(ls -t ~/.local/share/claude/versions/ 2>/dev/null | head -1)
exec "$HOME/.local/share/claude/versions/$LATEST" --chrome-native-host
EOF
chmod +x ~/.claude/chrome/chrome-native-host

# 3. Kill existing native host and clean sockets
pkill -f chrome-native-host
rm -rf /tmp/claude-mcp-browser-bridge-$USER/
rm -f "$(getconf DARWIN_USER_TEMP_DIR)/claude-mcp-browser-bridge-$USER"

# 4. Restart Chrome
osascript -e 'quit app "Google Chrome"' && sleep 2 && open -a "Google Chrome"

# 5. Wait for Chrome, click Claude extension icon

# 6. Verify correct native host is running
ps aux | grep chrome-native-host | grep -v grep
# Should show: ~/.local/share/claude/versions/X.X.X --chrome-native-host

# 7. Verify socket exists
ls -la "$(getconf DARWIN_USER_TEMP_DIR)/claude-mcp-browser-bridge-$USER"

# 8. Restart Claude Code
```

## Other Common Causes

### Multiple Chrome Profiles

If you have the Claude extension installed in multiple Chrome profiles, each spawns its own native host and socket. This can cause confusion.

**Fix:** Only enable the Claude extension in ONE Chrome profile.

### Multiple Claude Code Sessions

Running multiple Claude Code instances can cause socket conflicts.

**Fix:** Only run one Claude Code session at a time, or use `/mcp` to reconnect after closing other sessions.

### Hardcoded Version in Wrapper

The wrapper at `~/.claude/chrome/chrome-native-host` may have a hardcoded version that becomes stale after updates.

**Diagnosis:**
```bash
cat ~/.claude/chrome/chrome-native-host
# Bad: exec "/Users/.../.local/share/claude/versions/2.0.76" --chrome-native-host
# Good: Uses $(ls -t ...) to find latest
```

**Fix:** Use the dynamic version wrapper shown in the Full Reset Procedure above.

### TMPDIR Not Set

Claude Code expects `TMPDIR` to be set to find the socket.

```bash
# Check
echo $TMPDIR
# Should show: /var/folders/XX/.../T/

# Fix: Add to ~/.zshrc
export TMPDIR="${TMPDIR:-$(getconf DARWIN_USER_TEMP_DIR)}"
```

## Diagnostic Deep Dive

```bash
echo "=== Native Host Binary ==="
ps aux | grep chrome-native-host | grep -v grep

echo -e "\n=== Socket (Claude Code location) ==="
ls -la "$(getconf DARWIN_USER_TEMP_DIR)/claude-mcp-browser-bridge-$USER" 2>&1

echo -e "\n=== Socket (Claude.app location) ==="
ls -la /tmp/claude-mcp-browser-bridge-$USER/ 2>&1

echo -e "\n=== Native Host Open Files ==="
pgrep -f chrome-native-host | xargs -I {} lsof -p {} 2>/dev/null | grep -E "(sock|claude-mcp)"

echo -e "\n=== Active Native Messaging Configs ==="
ls ~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/com.anthropic*.json 2>/dev/null

echo -e "\n=== Custom Wrapper Contents ==="
cat ~/.claude/chrome/chrome-native-host 2>/dev/null || echo "No custom wrapper"

echo -e "\n=== TMPDIR ==="
echo "TMPDIR=$TMPDIR"
echo "Expected: $(getconf DARWIN_USER_TEMP_DIR)"
```

## File Reference

| File | Purpose |
|------|---------|
| `~/.claude/chrome/chrome-native-host` | Custom wrapper script for Claude Code |
| `/Applications/Claude.app/Contents/Helpers/chrome-native-host` | Claude.app (Cowork) native host |
| `~/.local/share/claude/versions/<version>` | Claude Code binary (run with `--chrome-native-host`) |
| `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_browser_extension.json` | Config for Claude.app native host |
| `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json` | Config for Claude Code native host |
| `$TMPDIR/claude-mcp-browser-bridge-$USER` | Socket file (Claude Code) |
| `/tmp/claude-mcp-browser-bridge-$USER/<PID>.sock` | Socket files (Claude.app) |

## Summary

1. **Primary issue:** Claude.app (Cowork) and Claude Code use different native hosts with incompatible socket formats
2. **Fix:** Disable the native messaging config for whichever one you're NOT using
3. **After any fix:** Must restart Chrome AND Claude Code (MCP connects at startup)
4. **One profile:** Only have Claude extension in one Chrome profile
5. **One session:** Only run one Claude Code instance

---

*Original skill by [@jeffzwang](https://github.com/jeffzwang) from [@ExaAILabs](https://github.com/ExaAILabs). Enhanced and updated for current versions of Claude Desktop and Claude Code.*

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: claude-monitor
description: Monitor de performance do Claude Code e sistema local. Diagnostica lentidao, mede CPU/RAM/disco, verifica API latency e gera relatorios de saude do sistema.
risk: safe
source: community
date_added: '2026-03-06'
author: renat
tags:
- monitoring
- performance
- diagnostics
- system-health
tools:
- claude-code
- antigravity
- cursor
- gemini-cli
- codex-cli
---

# Claude Monitor — Diagnóstico de Performance

## Overview

Monitor de performance do Claude Code e sistema local. Diagnostica lentidao, mede CPU/RAM/disco, verifica API latency e gera relatorios de saude do sistema.

## When to Use This Skill

- When the user mentions "lento" or related topics
- When the user mentions "lentidao" or related topics
- When the user mentions "lag" or related topics
- When the user mentions "lagado" or related topics
- When the user mentions "travando" or related topics
- When the user mentions "claude lento" or related topics

## Do Not Use This Skill When

- The task is unrelated to claude monitor
- A simpler, more specific tool can handle the request
- The user needs general-purpose assistance without domain expertise

## How It Works

Skill para diagnosticar e resolver problemas de lentidão no Claude Code e no sistema.
Determina se o gargalo é local (PC) ou remoto (API Claude) e sugere ações corretivas.

## Quando Usar

- Usuário reclama que o Claude Code está lento ou travando
- Troca de sessões de conversa demora para carregar
- Respostas do Claude demoram muito
- PC parece lento enquanto usa o Claude Code
- Qualquer menção a performance, lag, lentidão

## 1. Diagnóstico Rápido (Health_Check.Py)

Rode SEMPRE como primeiro passo:

```bash
python C:\Users\renat\skills\claude-monitor\scripts\health_check.py
```

O script analisa em ~3 segundos:
- **CPU**: Uso atual e por core. >80% = gargalo provável
- **RAM**: Total, usada, disponível. >85% = pressão de memória
- **Browsers**: Processos e RAM por browser. >5GB total = excesso de abas
- **Claude Code**: Processos e RAM consumida
- **Disco**: Espaço livre. <10% = impacto em swap/performance
- **Rede**: Latência ao endpoint da API Claude
- **Diagnóstico**: Classificação automática do problema com sugestões

## 2. Interpretar O Resultado

O script retorna um JSON com `diagnosis` contendo:

- `bottleneck`: "cpu" | "ram" | "browsers" | "disk" | "network" | "claude_api" | "ok"
- `severity`: "critical" | "warning" | "ok"
- `suggestions`: Lista de ações recomendadas
- `summary`: Resumo em português para mostrar ao usuário

**Mostre o `summary` ao usuário** e ofereça executar as sugestões.

## 3. Ações Corretivas Automáticas

Baseado no diagnóstico, ofereça ao usuário:

#### Se CPU alta (>80%):
- Listar processos consumindo mais CPU
- Sugerir fechar processos pesados desnecessários
- Verificar se Windows Update está rodando em background

#### Se browsers pesados (>5GB RAM ou >40 processos):
```bash
python C:\Users\renat\skills\claude-monitor\scripts\health_check.py --browsers-detail
```
Mostra RAM por browser e sugere quais fechar. **Nunca fechar processos sem permissão explícita do usuário.**

#### Se disco cheio (>85%):
- Mostrar pastas maiores
- Sugerir limpeza de Temp, cache de browsers, lixeira

#### Se rede lenta (latência >500ms):
- Testar conexão com api.anthropic.com
- Sugerir verificar VPN, proxy, ou conexão WiFi

## 4. Monitor Contínuo (Opcional)

Se o usuário quiser monitoramento em background:

```bash
python C:\Users\renat\skills\claude-monitor\scripts\monitor.py --interval 30 --duration 300
```

Parâmetros:
- `--interval`: Segundos entre cada amostra (default: 30)
- `--duration`: Duração total em segundos (default: 300 = 5 min)
- `--output`: Caminho do arquivo de log (default: monitor_log.json)
- `--alert-cpu`: Threshold de CPU para alerta (default: 80)
- `--alert-ram`: Threshold de RAM % para alerta (default: 85)

O monitor salva snapshots periódicos e gera um relatório ao final com:
- Picos de CPU e RAM
- Tendência (melhorando/piorando/estável)
- Eventos de alerta detectados
- Recomendação final

## 5. Benchmark Da Api Claude (Opcional)

Para testar se a lentidão é da API:

```bash
python C:\Users\renat\skills\claude-monitor\scripts\api_bench.py
```

Mede o tempo de resposta do processo Claude Code local (não faz chamadas à API).
Compara com tempos típicos e indica se está dentro do esperado.

## Thresholds De Referência

| Métrica | OK | Warning | Critical |
|---------|-----|---------|----------|
| CPU % | <60% | 60-85% | >85% |
| RAM usada % | <70% | 70-85% | >85% |
| RAM browsers | <3 GB | 3-6 GB | >6 GB |
| Processos browser | <30 | 30-60 | >60 |
| Disco livre | >15% | 10-15% | <10% |
| Latência rede | <200ms | 200-500ms | >500ms |

## Dicas Para O Usuário

Quando apresentar o diagnóstico, inclua estas dicas contextuais:

- **Muitas abas = muito CPU/RAM**: Cada aba de browser é um processo separado.
  50 abas = 50 processos competindo por recursos.
- **Claude Code é pesado**: Ele roda vários processos Electron. É normal consumir 3-5 GB.
  Mas se estiver usando >6 GB com várias sessões, considere fechar sessões antigas.
- **Troca de sessão lenta**: Geralmente causada por CPU alta ou muitos processos competindo.
  A sessão precisa carregar o histórico da conversa, e se o CPU está ocupado, demora.
- **Disco quase cheio**: Afeta a velocidade do swap (memória virtual) e pode causar
  lentidão generalizada.

## Dependências

- Python 3.10+
- psutil (instalado automaticamente pelo script se não disponível)
- Nenhuma API key necessária

## Best Practices

- Provide clear, specific context about your project and requirements
- Review all suggestions before applying them to production code
- Combine with other complementary skills for comprehensive analysis

## Common Pitfalls

- Using this skill for tasks outside its domain expertise
- Applying recommendations without understanding your specific context
- Not providing enough project context for accurate analysis

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: claude-scientific-skills
description: "Scientific research and analysis skills"
risk: safe
source: "https://github.com/K-Dense-AI/claude-scientific-skills"
date_added: "2026-02-27"
---

# Claude Scientific Skills

## Overview

Scientific research and analysis skills

## When to Use This Skill

Use this skill when you need to work with scientific research and analysis skills.

## Instructions

This skill provides guidance and patterns for scientific research and analysis skills.

For more information, see the [source repository](https://github.com/K-Dense-AI/claude-scientific-skills).

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.