feat(core-tools): adiciona plugin core-tools (agents, skills, knowledge e metadados do projeto)
This commit is contained in:
@@ -0,0 +1,184 @@
|
||||
---
|
||||
name: metrics
|
||||
description: Dashboard de metricas de performance de skills e agentes com telemetria quantitativa, trending temporal, alertas de degradacao e calculo de ROI.
|
||||
layer: wiki
|
||||
---
|
||||
|
||||
# SKILL: Performance Metrics Dashboard
|
||||
|
||||
## Proposito
|
||||
|
||||
Dashboard interactivo de performance de skills e agents com metricas quantitativas automaticas gravadas em Desk DB.
|
||||
|
||||
Complementa `/reflect` (qualitativo) com dados quantitativos, `/worklog` com metricas objectivas, e PDCA com decisoes data-driven.
|
||||
|
||||
---
|
||||
|
||||
## Quando Usar
|
||||
|
||||
- Ver performance de skills/agents
|
||||
- Identificar degradacoes de performance
|
||||
- Validar melhorias PDCA
|
||||
- Analise ROI de optimizacoes
|
||||
- Dashboard executivo de automacao
|
||||
|
||||
---
|
||||
|
||||
## Comandos
|
||||
|
||||
| Comando | Funcao |
|
||||
|---------|--------|
|
||||
| `/metrics` | Overview geral (30 dias) |
|
||||
| `/metrics <skill-name>` | Detalhes de skill especifica |
|
||||
| `/metrics --project <id>` | Metricas por projecto |
|
||||
| `/metrics --trend` | Trending temporal |
|
||||
| `/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 |
|
||||
| `/metrics --tools` | **Telemetria local de tool calls (ver secção Local Tool Telemetry)** |
|
||||
|
||||
---
|
||||
|
||||
## Local Tool Telemetry (G3.1-B)
|
||||
|
||||
Desde 08-04-2026 há captura universal de **todas** as tool calls do Claude Code via hook PostToolUse (`~/.claude/hooks/telemetry-posttool-hook.sh`). Complementa a telemetria Desk CRM com dados locais imediatos.
|
||||
|
||||
**Ficheiro:** `~/.claude-work/tool-invocations.jsonl` (1 linha por tool call: ts, session, tool_use_id, tool_name, success, error)
|
||||
|
||||
**Agregador:** `/media/ealmeida/Dados/Dev/ClaudeDev/tool-metrics.py`
|
||||
|
||||
```bash
|
||||
# Overview últimas 24h
|
||||
python3 /media/ealmeida/Dados/Dev/ClaudeDev/tool-metrics.py
|
||||
|
||||
# Só hoje
|
||||
python3 /media/ealmeida/Dados/Dev/ClaudeDev/tool-metrics.py --today
|
||||
|
||||
# Últimos 7 dias
|
||||
python3 /media/ealmeida/Dados/Dev/ClaudeDev/tool-metrics.py --last 7d
|
||||
|
||||
# Filtrar por sessão
|
||||
python3 /media/ealmeida/Dados/Dev/ClaudeDev/tool-metrics.py --session <session_id>
|
||||
|
||||
# Output JSON (para pipeline/grafos)
|
||||
python3 /media/ealmeida/Dados/Dev/ClaudeDev/tool-metrics.py --json
|
||||
```
|
||||
|
||||
**Output:** total de invocations, sessões únicas, top 20 tools (contagem + %), falhas por tool com amostras de erro, top 5 sessões por volume.
|
||||
|
||||
**Limitações conhecidas:**
|
||||
- Duration não é capturada (harness não entrega duration no hook payload). Apenas contagem e success/failure.
|
||||
- Tokens não capturáveis via hooks (não estão no payload).
|
||||
- Só captura tool calls que chegam ao PostToolUse — tool calls bloqueados por hooks PreToolUse não aparecem.
|
||||
|
||||
Ver `04-Stack/CHANGELOG.md` bloco 08-04-2026 sessão 2 para contexto do gap e decisão de scope.
|
||||
|
||||
### Agregacoes Disponiveis
|
||||
|
||||
1. **avg** - Medias de performance (padrao)
|
||||
2. **count** - Contagens por status
|
||||
3. **trend** - Evolucao temporal (semanal)
|
||||
4. **compare** - Comparacao com baseline
|
||||
5. **detailed** - Listagem detalhada
|
||||
|
||||
---
|
||||
|
||||
## Execucao
|
||||
|
||||
### 1. Verificar Tools MCP
|
||||
|
||||
```javascript
|
||||
// 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 nao disponiveis -> query SQL directa como fallback
|
||||
```
|
||||
|
||||
### 2. Query Metricas
|
||||
|
||||
**Via MCP (preferencial):**
|
||||
|
||||
```javascript
|
||||
const metrics = await mcp__desk_crm_v3__get_skill_metrics({
|
||||
days: 30,
|
||||
aggregate: 'avg',
|
||||
limit: 10
|
||||
});
|
||||
```
|
||||
|
||||
**Fallback SQL:** Ver [references/sql-queries.md](references/sql-queries.md)
|
||||
|
||||
### 3. Formatar Output
|
||||
|
||||
```
|
||||
Performance Overview (ultimos {days} dias)
|
||||
|
||||
Top Skills/Agents:
|
||||
| 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. Analise Especifica
|
||||
|
||||
```javascript
|
||||
const details = await get_skill_metrics({
|
||||
name: skill_name,
|
||||
days: 30,
|
||||
aggregate: 'detailed'
|
||||
});
|
||||
|
||||
const baseline = await query(
|
||||
"SELECT baseline_duration_ms FROM tblskill_agent_baselines WHERE name = ?",
|
||||
[skill_name]
|
||||
);
|
||||
const improvement = ((baseline - current_avg) / baseline * 100);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Alertas Automaticos
|
||||
|
||||
```javascript
|
||||
const degraded = await get_skill_metrics({
|
||||
aggregate: 'compare',
|
||||
days: 7
|
||||
});
|
||||
|
||||
const alerts = degraded.results.filter(r =>
|
||||
r.performance_status === 'DEGRADED'
|
||||
);
|
||||
|
||||
if (alerts.length > 0) {
|
||||
// Output alertas e sugerir /reflect para investigar
|
||||
}
|
||||
```
|
||||
|
||||
### Trigger Reflect se Degradacao
|
||||
|
||||
```javascript
|
||||
if (degradation_pct > 15) {
|
||||
// AUTO: Invocar reflect-agent em background
|
||||
Task({
|
||||
subagent_type: 'reflect-agent',
|
||||
background: true,
|
||||
model: 'sonnet',
|
||||
prompt: `PERFORMANCE DEGRADATION: ${name} +${degradation_pct}%`
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integracao com Outros Sistemas
|
||||
|
||||
| Comando | Foco | Quando Usar |
|
||||
|---------|------|-------------|
|
||||
| `/taskforce kb-health` | Saude sistema KB | Visao arquitectural |
|
||||
| `/metrics --kb` | Performance queries
|
||||
@@ -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('');
|
||||
}
|
||||
```
|
||||
@@ -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;
|
||||
```
|
||||
Reference in New Issue
Block a user