feat: refactor 30+ skills to Anthropic progressive disclosure pattern

- All SKILL.md files now <500 lines (avg reduction 69%)
- Detailed content extracted to references/ subdirectories
- Frontmatter standardised: only name + description (Anthropic standard)
- New skills: brand-guidelines, spec-coauthor, report-templates, skill-creator
- Design skills: anti-slop guidelines, premium-proposals reference
- Removed non-standard frontmatter fields (triggers, version, author, category)

Plugins affected: infraestrutura, marketing, dev-tools, crm-ops, gestao,
core-tools, negocio, perfex-dev, wordpress, design-media

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-12 15:05:03 +00:00
parent 9404af7ac9
commit 6b3a6f2698
397 changed files with 67154 additions and 17257 deletions

View File

@@ -1,91 +1,68 @@
---
name: metrics
description: >
Performance metrics dashboard for skills and agents with quantitative telemetry. Automatic tracking, temporal trending, degradation alerts, Dify KB impact analysis and ROI calculation per client/project.
Use when analyzing performance, tracking improvements, validating PDCA cycles, calculating ROI, or when user mentions
"metrics", "performance", "dashboard", "analytics", "trending", "degradation", "baseline", "improvement", "roi calculation".
author: Descomplicar® Crescimento Digital
version: 1.3.0
user_invocable: true
tags: [metrics, pdca, performance, dashboard, dify-kb, analytics, roi]
desk_project: 65
desk_task: 1637
allowed-tools: mcp__desk-crm-v3__get_skill_metrics, mcp__desk-crm-v3__log_skill_metric, Read
category: infra
quality_score: 85
updated: "2026-02-04T18:00:00Z"
description: Dashboard de metricas de performance de skills e agentes com telemetria quantitativa, trending temporal, alertas de degradacao e calculo de ROI.
---
# SKILL: Performance Metrics Dashboard
**Trigger:** `/metrics`
## Proposito
---
Dashboard interactivo de performance de skills e agents com metricas quantitativas automaticas gravadas em Desk DB.
## Propósito
Dashboard interactivo de performance de skills e agents com métricas quantitativas automáticas gravadas em Desk DB.
**Complementa:**
- `/reflect` (qualitativo) com dados quantitativos
- `/worklog` com métricas objectivas
- PDCA com decisões data-driven
Complementa `/reflect` (qualitativo) com dados quantitativos, `/worklog` com metricas objectivas, e PDCA com decisoes data-driven.
---
## Quando Usar
- Ver performance de skills/agents
- Identificar degradações de performance
- Identificar degradacoes de performance
- Validar melhorias PDCA
- Análise ROI de optimizações
- Dashboard executivo de automação
- Analise ROI de optimizacoes
- Dashboard executivo de automacao
---
## Capabilities
## Comandos
### Tipos de Análise
| Comando | Função |
| Comando | Funcao |
|---------|--------|
| `/metrics` | Overview geral (30 dias) |
| `/metrics <skill-name>` | Detalhes de skill específica |
| `/metrics --project <id>` | Métricas por projecto |
| `/metrics <skill-name>` | Detalhes de skill especifica |
| `/metrics --project <id>` | Metricas por projecto |
| `/metrics --trend` | Trending temporal |
| `/metrics --compare` | Comparação vs baseline |
| `/metrics --kb` | **NOVO v1.2**tricas Dify KB |
| `/metrics --roi` | **NOVO v1.2** ROI por cliente/projecto |
| `/metrics --export` | **NOVO v1.2** Exportar JSON/CSV |
| `/metrics --alerts` | **NOVO v1.2** Listar alertas activos |
| `/metrics --compare` | Comparacao vs baseline |
| `/metrics --kb` | Metricas Dify KB |
| `/metrics --roi` | ROI por cliente/projecto |
| `/metrics --export` | Exportar JSON/CSV |
| `/metrics --alerts` | Listar alertas activos |
### Agregações Disponíveis
### Agregacoes Disponiveis
1. **avg** - Médias de performance (padrão)
1. **avg** - Medias de performance (padrao)
2. **count** - Contagens por status
3. **trend** - Evolução temporal (semanal)
4. **compare** - Comparação com baseline
3. **trend** - Evolucao temporal (semanal)
4. **compare** - Comparacao com baseline
5. **detailed** - Listagem detalhada
---
## Execução
## Execucao
### 1. Verificar Tools MCP Disponíveis
### 1. Verificar Tools MCP
```javascript
// Tools necessários (MCP desk-crm-v3)
// Tools necessarios (MCP desk-crm-v3)
const REQUIRED_TOOLS = [
'mcp__desk-crm-v3__log_skill_metric',
'mcp__desk-crm-v3__get_skill_metrics'
];
// Se tools não disponíveis → query SQL directa como fallback
// Se tools nao disponiveis -> query SQL directa como fallback
```
### 2. Query Métricas (Via MCP ou SQL)
### 2. Query Metricas
**Opção A: Via MCP (preferencial)**
**Via MCP (preferencial):**
```javascript
const metrics = await mcp__desk_crm_v3__get_skill_metrics({
@@ -95,53 +72,22 @@ const metrics = await mcp__desk_crm_v3__get_skill_metrics({
});
```
**Opção B: Fallback SQL Directo**
```sql
-- Via MCP desk-crm-v3 SQL directo se tools metrics não disponíveis
SELECT
name,
type,
COUNT(*) as executions,
AVG(duration_ms) as avg_ms,
(SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) / COUNT(*) * 100) as error_rate
FROM tblskill_agent_metrics
WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY name, type
ORDER BY executions DESC
LIMIT 10;
```
**Fallback SQL:** Ver [references/sql-queries.md](references/sql-queries.md)
### 3. Formatar Output
**Template Dashboard:**
```
📊 Performance Overview (últimos {days} dias)
Performance Overview (ultimos {days} dias)
Top Skills/Agents:
┌─────────────────────┬────────┬──────────┬────────┬────────┐
│ Nome │ Usos │ Avg Time │ Trend │ Status │
├─────────────────────┼────────┼──────────┼────────┼────────┤
/orcamento │ 45 │ 18min │ -12% ✓ │ ✅ │
│ /lead-approach 38 │ 22min │ +5% ⚠ │ ⚠️
│ wp-plugin-developer │ 32 │ 47min │ -8% ✓ │ ✅ │
└─────────────────────┴────────┴──────────┴────────┴────────┘
⚠️ Alertas de Degradação:
{se houver degradação >15%}
🎯 Dify KB Impact:
- Coverage: {skills_com_dify}/{total_skills} ({pct}%)
- Avg time reduction: {reducao_tempo}%
- Cache hit rate: {cache_hit_rate}%
📈 Dashboard completo: https://plan-eal.descomplicar.pt/metrics
| Nome | Usos | Avg Time | Trend | Status |
|----------------|------|----------|-------|--------|
| /orcamento | 45 | 18min | -12% | OK |
| /lead-approach | 38 | 22min | +5% | Alerta |
| wp-plugin-dev | 32 | 47min | -8% | OK |
```
### 4. Análise Específica
Se utilizador pedir skill específica:
### 4. Analise Especifica
```javascript
const details = await get_skill_metrics({
@@ -150,52 +96,21 @@ const details = await get_skill_metrics({
aggregate: 'detailed'
});
// Calcular estatísticas
const baseline = await query("SELECT baseline_duration_ms FROM tblskill_agent_baselines WHERE name = ?", [skill_name]);
const baseline = await query(
"SELECT baseline_duration_ms FROM tblskill_agent_baselines WHERE name = ?",
[skill_name]
);
const improvement = ((baseline - current_avg) / baseline * 100);
```
**Output Detalhado:**
```
📊 {skill_name} - Análise Detalhada
Performance (30 dias):
- Execuções: {count}
- Tempo médio: {avg_ms}ms ({format_time})
- Baseline: {baseline_ms}ms
- Melhoria: {improvement}% {icon}
- Error rate: {error_rate}%
- Success rate: {success_rate}%
Dify KB:
- Consultas: {kb_consulted_count}/{total} ({pct}%)
- Com KB: {avg_with_kb}ms
- Sem KB: {avg_without_kb}ms
- Cache hit: {cache_hit_rate}%
Trending (últimas 4 semanas):
Semana 1: {w1_avg}ms ({w1_count} usos)
Semana 2: {w2_avg}ms ({w2_count} usos)
Semana 3: {w3_avg}ms ({w3_count} usos)
Semana 4: {w4_avg}ms ({w4_count} usos) {trend_icon}
Últimas 5 execuções:
1. {timestamp} - {duration}ms - {status}
2. ...
```
---
## Alertas Automáticos
### Detectar Degradação
## Alertas Automaticos
```javascript
// Query comparação com baseline
const degraded = await get_skill_metrics({
aggregate: 'compare',
days: 7 // última semana
days: 7
});
const alerts = degraded.results.filter(r =>
@@ -203,31 +118,11 @@ const alerts = degraded.results.filter(r =>
);
if (alerts.length > 0) {
// Output alertas
for (const alert of alerts) {
console.log(`⚠️ ${alert.name}: +${alert.degradation_pct}% vs baseline`);
}
// Sugerir acção
console.log("\n💡 Sugestão: Executar /reflect para investigar causas");
// Output alertas e sugerir /reflect para investigar
}
```
---
## Integração com Outros Sistemas
### Link para Desk CRM
```
Ver métricas no Desk CRM:
https://desk.descomplicar.pt/admin/projects/view/65
Relatório personalizado:
Reports → Stack Performance
```
### Trigger Reflect se Degradação
### Trigger Reflect se Degradacao
```javascript
if (degradation_pct > 15) {
@@ -236,356 +131,47 @@ if (degradation_pct > 15) {
subagent_type: 'reflect-agent',
background: true,
model: 'sonnet',
prompt: `
PERFORMANCE DEGRADATION DETECTED
Component: ${name}
Baseline: ${baseline}ms
Current: ${current}ms
Degradation: ${degradation_pct}%
Analyze root cause and suggest fixes.
`
prompt: `PERFORMANCE DEGRADATION: ${name} +${degradation_pct}%`
});
}
```
---
## Queries SQL Úteis (Fallback)
### Top 10 Skills
```sql
SELECT
name,
COUNT(*) as uses,
AVG(duration_ms)/60000 as avg_min,
(SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) / COUNT(*) * 100) as error_rate
FROM tblskill_agent_metrics
WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND type = 'skill'
GROUP BY name
ORDER BY uses DESC
LIMIT 10;
```
### ROI por Projecto
```sql
WITH skill_savings AS (
SELECT
m.project_id,
m.name,
COUNT(*) as uses,
(b.baseline_duration_ms - AVG(m.duration_ms))/60000 as saved_per_use_min
FROM tblskill_agent_metrics m
JOIN tblskill_agent_baselines b ON b.name = m.name
WHERE m.status = 'success'
GROUP BY m.project_id, m.name
)
SELECT
p.name as project,
c.company as client,
s.name as skill,
s.uses,
ROUND(s.uses * s.saved_per_use_min/60, 1) as hours_saved,
ROUND((s.uses * s.saved_per_use_min/60) * 50, 2) as value_eur
FROM skill_savings s
JOIN tblprojects p ON p.id = s.project_id
JOIN tblclients c ON c.userid = p.clientid
WHERE s.saved_per_use_min > 0
ORDER BY hours_saved DESC;
```
### Trending Semanal
```sql
SELECT
name,
DATE_FORMAT(created_at, '%Y-W%u') as week,
COUNT(*) as executions,
AVG(duration_ms) as avg_ms
FROM tblskill_agent_metrics
WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY name, week
ORDER BY name, week DESC;
```
---
## Exemplo de Uso
```bash
# Dashboard geral
> /metrics
📊 Performance Overview (últimos 30 dias)
Top Skills:
┌─────────────────────┬────────┬──────────┬────────┐
│ Skill │ Usos │ Avg Time │ Trend │
├─────────────────────┼────────┼──────────┼────────┤
│ /orcamento │ 45 │ 18min │ -12% ✓ │
│ /lead-approach │ 38 │ 22min │ +5% ⚠ │
│ /wp-dev │ 32 │ 47min │ -8% ✓ │
└─────────────────────┴────────┴──────────┴────────┘
⚠️ 1 alerta detectado
🎯 Dify KB: 35/43 skills (81%)
# Análise específica
> /metrics /orcamento
📊 /orcamento - Análise Detalhada
Performance: 18min avg (vs 30min baseline) → -40% ✓
Execuções: 45 (última semana: 12)
Success: 96% | Errors: 4%
Trending: ↓ Melhoria constante
```
---
## Notas Técnicas
### Tools MCP Status
**Estado:** Implementados em `/opt/desk-crm-v3/src/tools/core/metrics.ts`
**Compilados:**`/opt/desk-crm-v3/dist/tools/core/metrics.js`
**Serviço:** ✅ desk-crm.service reiniciado (249 tools)
**Disponibilidade:** Podem precisar de refresh Claude Code para serem descobertos
### Fallback Strategy
Se tools MCP não disponíveis:
1. Usar queries SQL directas via `sql_direct` tool
2. Funcionalidade completa mantém-se
3. Performance ligeiramente inferior mas aceitável
### Tabelas DB
- `tblskill_agent_metrics` - Telemetria
- `tblskill_agent_baselines` - Baselines
- `tblskill_agent_pdca_cycles` - PDCA histórico
---
---
## NOVO v1.2.0: Métricas Dify KB
### /metrics --kb
Dashboard específico de performance Dify Knowledge Base.
```
┌──────────────────────────────────────────────────────────────┐
│ DIFY KB PERFORMANCE DASHBOARD │
│ 2026-02-03 │
├──────────────────────────────────────────────────────────────┤
│ │
│ CACHE PERFORMANCE │
│ ════════════════════════════════════════════════════════ │
│ Hit Rate: ████░░░░░░░░░░░░░░░░ 6.3% (target: 40%+) │
│ │
│ Cache Breakdown: │
│ ┌────────────────┬────────┬────────┬────────┐ │
│ │ Skill │ Queries│ Hits │ Hit % │ │
│ ├────────────────┼────────┼────────┼────────┤ │
│ │ /orcamento │ 5 │ 1 │ 20% │ │
│ │ /lead-approach │ 3 │ 0 │ 0% │ │
│ │ /wp-dev │ 4 │ 0 │ 0% │ │
│ │ /seo-content │ 2 │ 0 │ 0% │ │
│ └────────────────┴────────┴────────┴────────┘ │
│ │
│ QUERY RELEVANCE (avg score) │
│ ════════════════════════════════════════════════════════ │
│ SEO: █████████████████░░░ 0.85 ⭐ │
│ Perfex: ████████████████░░░░ 0.79 │
│ Elementor: ██████████████░░░░░░ 0.70 │
│ Marketing: █████████████░░░░░░░ 0.66 │
│ Vendas: █████████░░░░░░░░░░░ 0.46 ⚠️ │
│ │
│ IMPACT ON PERFORMANCE │
│ ════════════════════════════════════════════════════════ │
│ Com Dify KB: 18 min avg │
│ Sem Dify KB: 30 min avg (baseline) │
│ Improvement: -40% ✓ │
│ │
│ GAPS DETECTED │
│ ════════════════════════════════════════════════════════ │
│ ⚠️ Vendas dataset: score 0.46 (queries mal formuladas) │
Cache hit baixo: requer mais uso para acumular │
│ │
└──────────────────────────────────────────────────────────────┘
```
### /metrics --roi
ROI detalhado por cliente/projecto.
```
┌──────────────────────────────────────────────────────────────┐
│ ROI POR CLIENTE/PROJECTO │
│ Últimos 30 dias │
├──────────────────────────────────────────────────────────────┤
│ │
│ TOP CLIENTES POR VALOR GERADO │
│ ════════════════════════════════════════════════════════ │
│ ┌────────────────────┬────────┬────────┬──────────────┐ │
│ │ Cliente │ Horas │ Skills │ Valor (€) │ │
│ ├────────────────────┼────────┼────────┼──────────────┤ │
│ │ SFV-360 │ 24h │ 45 │ €1.200,00 │ │
│ │ Descomplicar │ 18h │ 32 │ €900,00 │ │
│ │ INTERNAL │ 12h │ 28 │ €600,00 │ │
│ └────────────────────┴────────┴────────┴──────────────┘ │
│ │
│ TOTAL PERÍODO: 54 horas poupadas = €2.700,00 │
│ Custo hora interno: €50,00 │
│ │
│ BREAKDOWN POR SKILL │
│ ════════════════════════════════════════════════════════ │
│ /orcamento: 12h poupadas (baseline 30min→18min) │
│ /wp-dev: 8h poupadas (baseline 4h→2h) │
│ /lead-approach: 6h poupadas (baseline 25min→12min) │
│ │
└──────────────────────────────────────────────────────────────┘
```
### /metrics --export
Exportar métricas para integração.
```
Formatos disponíveis:
1. JSON - ~/.claude/skills/_metrics-export-YYYYMMDD.json
2. CSV - ~/.claude/skills/_metrics-export-YYYYMMDD.csv
3. Markdown - Para colar em documentos
Campos exportados:
- name, type, executions, avg_ms, baseline_ms
- improvement_pct, error_rate, kb_consulted
- cache_hit_rate, project_id, client_name
```
### /metrics --alerts
Sistema de alertas inteligentes.
```
┌──────────────────────────────────────────────────────────────┐
│ ALERTAS ACTIVOS │
├──────────────────────────────────────────────────────────────┤
│ │
│ ⚠️ DEGRADAÇÃO (>15% vs baseline) │
│ ─────────────────────────────────────────────────────── │
│ /lead-approach: +22% (baseline 12min → actual 15min) │
│ Última ocorrência: 2026-02-02 │
│ Afecta: 3 projectos │
│ Acção: Executar /reflect para investigar │
│ │
LOW CACHE HIT (<30%) │
│ ─────────────────────────────────────────────────────── │
│ Cache hit rate: 6.3% │
│ Target: 40% │
│ Causa: Sistema recente, acumular com uso │
│ Acção: Continuar monitorização │
│ │
│ ✅ MELHORIAS DETECTADAS │
│ ─────────────────────────────────────────────────────── │
│ /orcamento: -40% (era 30min, agora 18min) │
│ /wp-dev: -50% (era 4h, agora 2h) │
│ │
└──────────────────────────────────────────────────────────────┘
Configurar alertas:
- Degradação threshold: 15% (padrão)
- Cache hit minimum: 30% (padrão)
- Error rate maximum: 10% (padrão)
```
---
## ASCII Charts Library
Templates reutilizáveis para visualização.
### Progress Bar
```javascript
function progressBar(value, max, width=20) {
const filled = Math.round((value / max) * width);
const empty = width - filled;
return '█'.repeat(filled) + '░'.repeat(empty);
}
// Exemplo: progressBar(40, 100, 20) → "████████░░░░░░░░░░░░"
```
### Trending Arrow
```javascript
function trendIcon(pct) {
if (pct < -10) return '↓↓ ✓'; // Grande melhoria
if (pct < 0) return '↓ ✓'; // Melhoria
if (pct === 0) return '→'; // Estável
if (pct < 10) return '↑ ⚠'; // Pequena degradação
return '↑↑ ⚠️'; // Grande degradação
}
```
### Mini Sparkline
```javascript
function sparkline(values) {
const chars = '▁▂▃▄▅▆▇█';
const min = Math.min(...values);
const max = Math.max(...values);
const range = max - min || 1;
return values.map(v => chars[Math.floor((v - min) / range * 7)]).join('');
}
// Exemplo: sparkline([10, 15, 8, 20, 12]) → "▃▅▁█▄"
```
---
## Integração com /taskforce kb-health
O comando `/metrics --kb` complementa `/taskforce kb-health`:
## Integracao com Outros Sistemas
| Comando | Foco | Quando Usar |
|---------|------|-------------|
| `/taskforce kb-health` | Saúde sistema KB (coverage, gaps) | Visão arquitectural |
| `/metrics --kb` | Performance queries KB | Análise operacional |
| `/metrics --roi` | Valor económico gerado | Justificação investimento |
| `/taskforce kb-health` | Saude sistema KB | Visao arquitectural |
| `/metrics --kb` | Performance queries KB | Analise operacional |
| `/metrics --roi` | Valor economico gerado | Justificacao investimento |
**Workflow recomendado:**
1. `/taskforce kb-health` - Verificar gaps e coverage
2. `/metrics --kb` - Analisar performance queries
3. `/metrics --roi` - Calcular ROI para stakeholders
---
## Changelog
### v1.2.0 (2026-02-03)
- **NOVO:** `/metrics --kb` - Dashboard Dify KB
- **NOVO:** `/metrics --roi` - ROI por cliente/projecto
- **NOVO:** `/metrics --export` - Export JSON/CSV
- **NOVO:** `/metrics --alerts` - Sistema alertas
- **NOVO:** ASCII Charts Library
- **MELHORIA:** Integração com `/taskforce kb-health`
- Frontmatter YAML standard
### v1.0.0 (2026-02-03)
- Versão inicial
- Dashboard overview
- Análise por skill
- Trending temporal
- Comparação baseline
Link Desk CRM: `https://desk.descomplicar.pt/admin/projects/view/65`
---
**Skill:** /metrics v1.2.0 | **Autor:** Descomplicar®
**Parte de:** Sistema de Métricas Quantitativas
**Desk CRM:** Projecto #65 | Task #1637
## Notas Tecnicas
**Tabelas DB:** `tblskill_agent_metrics` (telemetria), `tblskill_agent_baselines` (baselines), `tblskill_agent_pdca_cycles` (PDCA historico)
**Tools:** Implementados em `/opt/desk-crm-v3/src/tools/core/metrics.ts`
**Fallback:** Se tools MCP nao disponiveis, usar queries SQL directas via `sql_direct`.
---
## Conteudo Detalhado
| Referencia | Conteudo |
|------------|----------|
| [references/sql-queries.md](references/sql-queries.md) | Queries SQL completas (top 10, ROI, trending) |
| [references/dashboards-templates.md](references/dashboards-templates.md) | Templates visuais KB, ROI, alertas, export, ASCII charts |
---
**Desk CRM:** Projecto #65, Task #1637

View File

@@ -0,0 +1,126 @@
# Metrics - Templates de Dashboards
## Dashboard KB Performance
```
DIFY KB PERFORMANCE DASHBOARD
CACHE PERFORMANCE
Hit Rate: [barra progresso] X% (target: 40%+)
Cache Breakdown:
| Skill | Queries | Hits | Hit % |
|----------------|---------|------|-------|
| /orcamento | 5 | 1 | 20% |
| /lead-approach | 3 | 0 | 0% |
| /wp-dev | 4 | 0 | 0% |
QUERY RELEVANCE (avg score)
SEO: 0.85
Perfex: 0.79
Elementor: 0.70
Marketing: 0.66
Vendas: 0.46 (alerta)
IMPACT ON PERFORMANCE
Com Dify KB: 18 min avg
Sem Dify KB: 30 min avg (baseline)
Improvement: -40%
```
## Dashboard ROI por Cliente/Projecto
```
ROI POR CLIENTE/PROJECTO (ultimos 30 dias)
TOP CLIENTES POR VALOR GERADO
| Cliente | Horas | Skills | Valor (EUR) |
|--------------|-------|--------|-------------|
| SFV-360 | 24h | 45 | 1.200,00 |
| Descomplicar | 18h | 32 | 900,00 |
| INTERNAL | 12h | 28 | 600,00 |
TOTAL PERIODO: 54 horas poupadas = 2.700,00 EUR
Custo hora interno: 50,00 EUR
BREAKDOWN POR SKILL
/orcamento: 12h poupadas (baseline 30min->18min)
/wp-dev: 8h poupadas (baseline 4h->2h)
/lead-approach: 6h poupadas (baseline 25min->12min)
```
## Dashboard Alertas
```
ALERTAS ACTIVOS
DEGRADACAO (>15% vs baseline)
/lead-approach: +22% (baseline 12min -> actual 15min)
Ultima ocorrencia: 2026-02-02
Afecta: 3 projectos
Accao: Executar /reflect para investigar
LOW CACHE HIT (<30%)
Cache hit rate: 6.3%
Target: 40%
Causa: Sistema recente, acumular com uso
MELHORIAS DETECTADAS
/orcamento: -40% (era 30min, agora 18min)
/wp-dev: -50% (era 4h, agora 2h)
Configurar alertas:
- Degradacao threshold: 15% (padrao)
- Cache hit minimum: 30% (padrao)
- Error rate maximum: 10% (padrao)
```
## Dashboard Export
```
Formatos disponiveis:
1. JSON - ~/.claude/skills/_metrics-export-YYYYMMDD.json
2. CSV - ~/.claude/skills/_metrics-export-YYYYMMDD.csv
3. Markdown - Para colar em documentos
Campos exportados:
- name, type, executions, avg_ms, baseline_ms
- improvement_pct, error_rate, kb_consulted
- cache_hit_rate, project_id, client_name
```
## ASCII Charts Library
### Progress Bar
```javascript
function progressBar(value, max, width=20) {
const filled = Math.round((value / max) * width);
const empty = width - filled;
return '#'.repeat(filled) + '-'.repeat(empty);
}
```
### Trending Arrow
```javascript
function trendIcon(pct) {
if (pct < -10) return 'melhoria significativa';
if (pct < 0) return 'melhoria';
if (pct === 0) return 'estavel';
if (pct < 10) return 'degradacao ligeira';
return 'degradacao significativa';
}
```
### Mini Sparkline
```javascript
function sparkline(values) {
const chars = '________';
const min = Math.min(...values);
const max = Math.max(...values);
const range = max - min || 1;
return values.map(v => chars[Math.floor((v - min) / range * 7)]).join('');
}
```

View File

@@ -0,0 +1,77 @@
# Metrics - Queries SQL (Fallback)
Queries para usar quando tools MCP nao estao disponiveis.
## Top 10 Skills
```sql
SELECT
name,
COUNT(*) as uses,
AVG(duration_ms)/60000 as avg_min,
(SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) / COUNT(*) * 100) as error_rate
FROM tblskill_agent_metrics
WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND type = 'skill'
GROUP BY name
ORDER BY uses DESC
LIMIT 10;
```
## ROI por Projecto
```sql
WITH skill_savings AS (
SELECT
m.project_id,
m.name,
COUNT(*) as uses,
(b.baseline_duration_ms - AVG(m.duration_ms))/60000 as saved_per_use_min
FROM tblskill_agent_metrics m
JOIN tblskill_agent_baselines b ON b.name = m.name
WHERE m.status = 'success'
GROUP BY m.project_id, m.name
)
SELECT
p.name as project,
c.company as client,
s.name as skill,
s.uses,
ROUND(s.uses * s.saved_per_use_min/60, 1) as hours_saved,
ROUND((s.uses * s.saved_per_use_min/60) * 50, 2) as value_eur
FROM skill_savings s
JOIN tblprojects p ON p.id = s.project_id
JOIN tblclients c ON c.userid = p.clientid
WHERE s.saved_per_use_min > 0
ORDER BY hours_saved DESC;
```
## Trending Semanal
```sql
SELECT
name,
DATE_FORMAT(created_at, '%Y-W%u') as week,
COUNT(*) as executions,
AVG(duration_ms) as avg_ms
FROM tblskill_agent_metrics
WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY name, week
ORDER BY name, week DESC;
```
## Query Basica via MCP
```sql
SELECT
name,
type,
COUNT(*) as executions,
AVG(duration_ms) as avg_ms,
(SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) / COUNT(*) * 100) as error_rate
FROM tblskill_agent_metrics
WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY name, type
ORDER BY executions DESC
LIMIT 10;
```