New plugins: core-tools New skills: auto-expense, ticket-triage, design, security-check, aiktop-tasks, daily-digest, imap-triage, index-update, mindmap, notebooklm, proc-creator, tasks-overview, validate-component, perfex-module, report, calendar-manager New agents: design-critic, design-generator, design-lead, design-prompt-architect, design-researcher, compliance-auditor, metabase-analyst, gitea-integration-specialist Updated: all plugin configs, knowledge datasets, existing skills Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
592 lines
22 KiB
Markdown
592 lines
22 KiB
Markdown
---
|
||
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"
|
||
---
|
||
|
||
# SKILL: Performance Metrics Dashboard
|
||
|
||
**Trigger:** `/metrics`
|
||
|
||
---
|
||
|
||
## 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
|
||
|
||
---
|
||
|
||
## Quando Usar
|
||
|
||
- Ver performance de skills/agents
|
||
- Identificar degradações de performance
|
||
- Validar melhorias PDCA
|
||
- Análise ROI de optimizações
|
||
- Dashboard executivo de automação
|
||
|
||
---
|
||
|
||
## Capabilities
|
||
|
||
### Tipos de Análise
|
||
|
||
| Comando | Função |
|
||
|---------|--------|
|
||
| `/metrics` | Overview geral (30 dias) |
|
||
| `/metrics <skill-name>` | Detalhes de skill específica |
|
||
| `/metrics --project <id>` | Métricas por projecto |
|
||
| `/metrics --trend` | Trending temporal |
|
||
| `/metrics --compare` | Comparação vs baseline |
|
||
| `/metrics --kb` | **NOVO v1.2** Mé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 |
|
||
|
||
### Agregações Disponíveis
|
||
|
||
1. **avg** - Médias de performance (padrão)
|
||
2. **count** - Contagens por status
|
||
3. **trend** - Evolução temporal (semanal)
|
||
4. **compare** - Comparação com baseline
|
||
5. **detailed** - Listagem detalhada
|
||
|
||
---
|
||
|
||
## Execução
|
||
|
||
### 1. Verificar Tools MCP Disponíveis
|
||
|
||
```javascript
|
||
// Tools necessários (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
|
||
```
|
||
|
||
### 2. Query Métricas (Via MCP ou SQL)
|
||
|
||
**Opção A: Via MCP (preferencial)**
|
||
|
||
```javascript
|
||
const metrics = await mcp__desk_crm_v3__get_skill_metrics({
|
||
days: 30,
|
||
aggregate: 'avg',
|
||
limit: 10
|
||
});
|
||
```
|
||
|
||
**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;
|
||
```
|
||
|
||
### 3. Formatar Output
|
||
|
||
**Template Dashboard:**
|
||
|
||
```
|
||
📊 Performance Overview (últimos {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
|
||
```
|
||
|
||
### 4. Análise Específica
|
||
|
||
Se utilizador pedir skill específica:
|
||
|
||
```javascript
|
||
const details = await get_skill_metrics({
|
||
name: skill_name,
|
||
days: 30,
|
||
aggregate: 'detailed'
|
||
});
|
||
|
||
// Calcular estatísticas
|
||
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
|
||
|
||
```javascript
|
||
// Query comparação com baseline
|
||
const degraded = await get_skill_metrics({
|
||
aggregate: 'compare',
|
||
days: 7 // última semana
|
||
});
|
||
|
||
const alerts = degraded.results.filter(r =>
|
||
r.performance_status === 'DEGRADED'
|
||
);
|
||
|
||
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");
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 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
|
||
|
||
```javascript
|
||
if (degradation_pct > 15) {
|
||
// AUTO: Invocar reflect-agent em background
|
||
Task({
|
||
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.
|
||
`
|
||
});
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 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`:
|
||
|
||
| 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 |
|
||
|
||
**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
|
||
|
||
---
|
||
|
||
**Skill:** /metrics v1.2.0 | **Autor:** Descomplicar®
|
||
**Parte de:** Sistema de Métricas Quantitativas
|
||
**Desk CRM:** Projecto #65 | Task #1637
|