Logo de Cache Audit

Cache Audit

Comunidade
ussumant
cache-audit

Audit your Claude Code setup against prompt caching best practices. Checks ordering, tool stability, dynamic content handling, and hook injection patterns. Returns a scored report with specific fixes.

Visão geral

Publicado porussumant
Repositóriocache-audit
Nome da habilidadecache-audit
Estrelas
60
Forks
7
Arquivos incluídos
Somente instruções
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Completa em si mesma

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por ussumant no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Cache Audit no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/ussumant/cache-audit/tree/main/cache-audit
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ussumant/cache-audit.git /tmp/cache-audit
mkdir -p .claude/skills
cp -r /tmp/cache-audit/cache-audit .claude/skills/cache-audit
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Cache Audit em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Cache Audit automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Cache Audit não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Prompt Cache Audit Skill

Trigger: /cache-audit or "audit my caching" or "check my cache setup" or "am I breaking the cache?"

What it does: Reads your live Claude Code configuration and checks it against the 6 prompt caching rules from Anthropic's engineering team. Returns a scored report with specific, actionable fixes.

Reference: Based on Thariq Shihipar's thread "Lessons from Building Claude Code: Prompt Caching Is Everything"


When Invoked

Run all checks automatically. Do not ask for confirmation. Read the relevant files and produce the full report in one pass.


The 6 Checks

Check 1 — Prompt Ordering (Static Before Dynamic)

Read: ~/.claude/settings.json, all active CLAUDE.md files in the project hierarchy

What to look for:

  • Does the system prompt load in the right order? Rule: static content first, dynamic content last
  • Correct order: System prompt → Tools → CLAUDE.md → Session context → Messages
  • Flag: Any dynamic content (timestamps, git status, current date, user stats) appearing in the system prompt itself
  • Flag: CLAUDE.md files that include session-specific or time-sensitive data
  • Pass: CLAUDE.md files that are purely static instructions, conventions, and file references

Scoring:

  • PASS: System prompt is fully static, dynamic data injected via messages
  • WARNING: Some dynamic data in system prompt but low-frequency change
  • FAIL: High-churn dynamic content (timestamps, file contents) in system prompt

Check 2 — Dynamic Updates via Messages (not System Prompt Edits)

Read: All hook files listed under SessionStart and UserPromptSubmit in ~/.claude/settings.json

What to look for:

  • Hooks should output dynamic data as additionalContext in their JSON response (which becomes a <system-reminder> message) — not by modifying the system prompt
  • Check each hook's output format: does it use hookSpecificOutput.additionalContext? ✅
  • Flag: Any hook that writes to a system prompt file, modifies CLAUDE.md, or injects into the static prefix
  • Pass: Hooks that return JSON with additionalContext key

Also check:

  • Is currentDate injected via message (memory.md context) or hardcoded in system prompt?
  • Is git status coming from a hook → message, or somewhere static?

Scoring:

  • PASS: All hooks use additionalContext pattern
  • FAIL: Any hook modifies system prompt or CLAUDE.md mid-session

Check 3 — Tool Set Stability (No Add/Remove Mid-Session)

Read: ~/.claude/settings.json, ~/.claude/skills/*.md, MCP server configurations

What to look for:

  • Tools should be identical at every turn of the conversation
  • Check: Do any skills explicitly add new tools when invoked? (tool definitions that only appear after a skill runs)
  • Check: Are MCP tools using defer_loading: true stubs rather than full schemas loaded conditionally?
  • Flag: Any skill that modifies the available tool set
  • Pass: MCP tools present as lightweight stubs in every request, full schemas only loaded on demand via ToolSearch

Note: The ToolSearch tool itself is the correct pattern — it lets the model discover tools without adding/removing from the base set.

Scoring:

  • PASS: Tool set is fixed at session start, all MCP tools deferred
  • WARNING: Some conditional tool loading that may cause cache misses
  • FAIL: Skills or hooks that add/remove tools mid-conversation

Check 4 — No Mid-Session Model Switches

Read: ~/.claude/settings.json, ~/.claude/skills/*.md, any agent/team configurations

What to look for:

  • The model field in settings.json should be set and stable
  • Check: Do any skills switch models in the same conversation thread? (e.g., running a quick haiku query inline)
  • Pass: Model switches are done via subagents with handoff messages — the Explore/Plan agent types running on Haiku are separate conversations, not inline switches
  • Flag: Any pattern where the main conversation calls a different model mid-turn

Scoring:

  • PASS: Single model per conversation, subagents used for model delegation
  • FAIL: Inline model switching in same conversation thread

Check 5 — Dynamic Content Size

Read: Hook files, git status injection, session-reminder outputs

What to measure:

  • Estimate the size of dynamic content injected per session/turn
  • Check the git status hook output — measure the typical size of the injected git diff/status
  • Check streak/quota hook output size
  • Check if granola meeting sync injects large content per turn

Thresholds:

  • < 2k chars injected per turn: ✅ PASS
  • 2k–10k chars: ⚠️ WARNING (still correct pattern, just expensive)
  • 10k chars: ❌ FLAG — consider trimming

Known issue to flag:

  • Git status with hundreds of untracked files (like the personalOS repo) can easily exceed 40k chars per session start. This is injected correctly via messages, but the raw token cost is high. Recommend: trim to branch name + changed file count + modified file list only.

Suggested fix for large git status:

bash
# Instead of full git status, inject only:
git branch --show-current
git diff --stat HEAD | tail -5
git status --short | grep "^[^?]" | head -20  # only tracked changes, no untracked

Check 6 — Fork Safety (Compaction & Subagent Calls)

Read: Any compaction configuration, skill invocations that fork context

What to look for:

  • When Claude Code runs compaction (context window fills), does the summary request reuse the same system prompt + tools as the parent?
  • When skills fork a subagent, do they pass through the same prefix?
  • This is partially an Anthropic infrastructure concern — Claude Code handles it correctly by default

Scoring:

  • PASS: Using Claude Code's built-in compaction (handled correctly)
  • MANUAL CHECK: Custom compaction or summarization flows — verify they use identical system prompt + tool definitions as parent

Output Format

After running all checks, output this report:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  PROMPT CACHE AUDIT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Score: X/6

✅ / ⚠️ / ❌  Rule 1 — Ordering: [PASS/WARNING/FAIL]
   → [Specific finding or "All good"]

✅ / ⚠️ / ❌  Rule 2 — Message injection: [PASS/WARNING/FAIL]
   → [Specific hooks checked and their pattern]

✅ / ⚠️ / ❌  Rule 3 — Tool stability: [PASS/WARNING/FAIL]
   → [MCP tool count, defer status]

✅ / ⚠️ / ❌  Rule 4 — Model switching: [PASS/WARNING/FAIL]
   → [Model in settings, any inline switches found]

✅ / ⚠️ / ❌  Rule 5 — Dynamic content size: [PASS/WARNING/FAIL]
   → [Estimated chars/turn for each injection point]

✅ / ⚠️ / ❌  Rule 6 — Fork safety: [PASS/MANUAL CHECK]
   → [Compaction pattern used]

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  TOP FIX
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
[Single most impactful change with exact code/config to implement]

If everything passes: say so clearly and note the estimated cost savings from the current setup vs. a naive implementation.


Reference: The 6 Rules (Quick Cheatsheet)

RuleDoDon't
1. OrderingStatic system prompt → CLAUDE.md → messagesDynamic data in system prompt
2. UpdatesInject via <system-reminder> in messagesEdit system prompt mid-session
3. ToolsFixed tool set + deferred stubsAdd/remove tools per turn
4. ModelsOne model per conversation, subagents for switchesInline model switching
5. SizeTrim dynamic injections to minimum neededDump full git status (40k chars)
6. ForksSame prefix for compaction/subagentsDifferent system prompt for summary calls

Perguntas frequentes

O que a habilidade de IA Cache Audit faz?

Audit your Claude Code setup against prompt caching best practices. Checks ordering, tool stability, dynamic content handling, and hook injection patterns. Returns a scored report with specific fixes.

Por que usar Cache Audit no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Cache Audit é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Cache Audit no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/ussumant/cache-audit/tree/main/cache-audit. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Cache Audit?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Cache Audit?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Cache Audit com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Cache Audit é gratuita?

A habilidade é publicada no GitHub por ussumant. Consulte os termos de licenciamento no repositório. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇