@luanpdd/kit-mcp 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -249,6 +249,160 @@ Upload events são quentes em custo (egress + storage) e em UX (lentidão de upl
249
249
 
250
250
  **Output adicionado:** seção "## Observability hooks" com snippet de upload/download wrapper.
251
251
 
252
+ ## Saturation signal — bucket size + quota
253
+
254
+ > Cross-ref canônico: [four-golden-signals](../skills/four-golden-signals/SKILL.md) (cap 6 do livro Google SRE — Monitoring Distributed Systems). Para retro-instrumentar storage existente com os 4 signals, delegar para [golden-signals-instrumenter](./golden-signals-instrumenter.md).
255
+
256
+ Storage tem o **recurso mais escasso explícito**: o quota do plano (Free 1 GB, Pro 100 GB, Team 1 TB, etc.). Sem signal de saturation, time descobre quota exhaustion via incident (uploads falham silenciosamente em UX) — **anti-pattern clássico** de white-box monitoring sem detecção precoce. O bloco `## Observabilidade integrada` acima cobre Latency / Traffic / Errors (3 signals); este bloco completa com **Saturation** — o 4º signal canônico.
257
+
258
+ ### Saturation = bucket size ÷ quota plan
259
+
260
+ | Plano | Quota total | Threshold ALERT (yellow) | Threshold PAGE (red) |
261
+ |---|---|---|---|
262
+ | Free | 1 GB | 80% (800 MB) | 95% (950 MB) |
263
+ | Pro | 100 GB | 80% (80 GB) | 95% (95 GB) |
264
+ | Team | 1 TB | 80% (800 GB) | 95% (950 GB) |
265
+ | Enterprise | custom | custom | custom |
266
+
267
+ ### Signal 1 — Gauge: bucket size atual (bytes)
268
+
269
+ `ObservableGauge` (push periódico via callback) mede tamanho real de cada bucket. Callback consulta `storage.objects` agregado:
270
+
271
+ ```ts
272
+ // PT-BR: 4º signal — saturation (gauge de bucket size em bytes)
273
+ import { metrics } from 'npm:@opentelemetry/api@1.9.0'
274
+ const meter = metrics.getMeter('supabase-storage')
275
+
276
+ meter.createObservableGauge('storage_bucket_bytes', {
277
+ description: 'Tamanho atual em bytes por bucket — saturation signal',
278
+ unit: 'bytes',
279
+ }).addCallback(async (result) => {
280
+ // PT-BR: query agregada (rodar via service-role client em cron)
281
+ const sizes = await supabaseAdmin.rpc('storage_bucket_sizes_bytes')
282
+ // expected: [{ bucket_id: 'avatars', total_bytes: 12345678 }, ...]
283
+ for (const row of sizes ?? []) {
284
+ result.observe(row.total_bytes, { 'bucket.id': row.bucket_id })
285
+ }
286
+ })
287
+
288
+ meter.createObservableGauge('storage_saturation_pct', {
289
+ description: 'Saturation = bucket size / quota plan — % do quota usado',
290
+ unit: '1', // ratio (0..1)
291
+ }).addCallback(async (result) => {
292
+ const sizes = await supabaseAdmin.rpc('storage_bucket_sizes_bytes')
293
+ const QUOTA_BYTES = Number(Deno.env.get('SUPABASE_PLAN_QUOTA_BYTES') ?? 1_000_000_000) // default Free
294
+ for (const row of sizes ?? []) {
295
+ result.observe(row.total_bytes / QUOTA_BYTES, { 'bucket.id': row.bucket_id })
296
+ }
297
+ })
298
+ ```
299
+
300
+ SQL helper para o callback:
301
+
302
+ ```sql
303
+ -- PT-BR: function que retorna bytes por bucket — chamada por callback OTel
304
+ create or replace function public.storage_bucket_sizes_bytes()
305
+ returns table (bucket_id text, total_bytes bigint)
306
+ language sql
307
+ security definer
308
+ set search_path = ''
309
+ as $$
310
+ select bucket_id, coalesce(sum((metadata->>'size')::bigint), 0) as total_bytes
311
+ from storage.objects
312
+ group by bucket_id;
313
+ $$;
314
+ ```
315
+
316
+ ### Signal 2 — Counter: quota near-exhaustion events
317
+
318
+ `Counter` incrementa a cada upload que **detecta** approach a quota threshold (80%, 95%). Permite contar eventos críticos para alerting:
319
+
320
+ ```ts
321
+ // PT-BR: counter incrementado em cada upload
322
+ const quotaWarnings = meter.createCounter('storage_quota_warnings_total', {
323
+ description: 'Counter de eventos onde upload aproxima quota — alimentar alert SLO',
324
+ })
325
+
326
+ export async function uploadInstrumented(file: File, filename: string) {
327
+ const supabase = createClient()
328
+ const { data: { user } } = await supabase.auth.getUser()
329
+ if (!user) throw new Error('not authenticated')
330
+
331
+ const path = `${user.id}/${filename}`
332
+
333
+ // PT-BR: pre-check — saturation atual antes de upload
334
+ const sizes = await supabaseAdmin.rpc('storage_bucket_sizes_bytes')
335
+ const bucketSize = sizes?.find(s => s.bucket_id === '<bucket_name>')?.total_bytes ?? 0
336
+ const QUOTA = Number(Deno.env.get('SUPABASE_PLAN_QUOTA_BYTES') ?? 1_000_000_000)
337
+ const saturation = bucketSize / QUOTA
338
+
339
+ if (saturation >= 0.95) {
340
+ quotaWarnings.add(1, { 'bucket.id': '<bucket_name>', threshold: '95pct' })
341
+ } else if (saturation >= 0.80) {
342
+ quotaWarnings.add(1, { 'bucket.id': '<bucket_name>', threshold: '80pct' })
343
+ }
344
+
345
+ const { data, error } = await supabase.storage
346
+ .from('<bucket_name>')
347
+ .upload(path, file, { upsert: true })
348
+
349
+ if (error) throw error
350
+ return data.path
351
+ }
352
+ ```
353
+
354
+ ### Cron schedule sugerido
355
+
356
+ Saturation gauge não precisa rodar em cada request — agendar leitura via `pg_cron` (ou OTel SDK polling interval = 60s) é suficiente:
357
+
358
+ ```sql
359
+ -- PT-BR: refresh saturation cache a cada 60s para gauge OTel
360
+ create materialized view if not exists obs.storage_saturation as
361
+ select bucket_id, sum((metadata->>'size')::bigint) as total_bytes, now() as captured_at
362
+ from storage.objects
363
+ group by bucket_id;
364
+
365
+ select cron.schedule(
366
+ 'refresh_storage_saturation',
367
+ '* * * * *', -- a cada 1 min
368
+ $$ refresh materialized view concurrently obs.storage_saturation $$
369
+ );
370
+ ```
371
+
372
+ ### Alert SLO sobre saturation
373
+
374
+ Saturation alimenta SLO event-based — não threshold direto:
375
+
376
+ ```yaml
377
+ # PT-BR: SLO sobre quota — % de tempo em yellow ou worse
378
+ slo:
379
+ name: storage_quota_healthy
380
+ target: 0.99 # 99% do tempo em < 80% quota
381
+ window: 30d_sliding
382
+ sli:
383
+ type: event_based
384
+ good_event:
385
+ saturation_pct: { lt: 0.80 }
386
+ bad_event:
387
+ saturation_pct: { gte: 0.80 }
388
+ ```
389
+
390
+ ### Output do agent — adicionado ao SQL/código gerado
391
+
392
+ Quando agent gera bucket privado novo, **sempre inclui**:
393
+ 1. Function SQL `storage_bucket_sizes_bytes()` (uma vez por projeto)
394
+ 2. Materialized view `obs.storage_saturation` + pg_cron refresh job
395
+ 3. Snippet OTel ObservableGauge no código client wrapper
396
+ 4. Counter `storage_quota_warnings_total` no upload wrapper
397
+ 5. SLO `storage_quota_healthy` em `.planning/slos/<bucket>.yaml`
398
+
399
+ ### Anti-patterns prevenidos
400
+
401
+ - Saturation = "% disco do servidor" → SEMPRE saturation = % quota plan (recurso correto)
402
+ - Threshold direto em alerta CPU/memory para capacity → SEMPRE SLO event-based sobre saturation_pct
403
+ - Polling de bucket size em cada request → SEMPRE materialized view + pg_cron refresh + OTel polling 60s
404
+ - Plan quota hardcoded → SEMPRE env var `SUPABASE_PLAN_QUOTA_BYTES` (varia por plano, pode ser sobrescrita em test)
405
+
252
406
  ## Ver também
253
407
 
254
408
  - [supabase-storage](../skills/supabase-storage/SKILL.md) — base de conhecimento canônica
@@ -256,3 +410,5 @@ Upload events são quentes em custo (egress + storage) e em UX (lentidão de upl
256
410
  - [supabase-auth-ssr](../skills/supabase-auth-ssr/SKILL.md) — usuário autenticado obtém `auth.uid()`
257
411
  - [structured-events](../skills/structured-events/SKILL.md) — campos canônicos para upload/download events
258
412
  - [telemetry-sampling](../skills/telemetry-sampling/SKILL.md) *(Phase 34)* — head-based sampling por size_bytes
413
+ - [four-golden-signals](../skills/four-golden-signals/SKILL.md) — 4 sinais canônicos (Latency, Traffic, Errors, Saturation) cap 6 livro Google SRE — saturation = bucket size / quota plan
414
+ - [golden-signals-instrumenter](./golden-signals-instrumenter.md) — agent que retro-instrumenta storage existente com os 4 signals
@@ -0,0 +1,277 @@
1
+ ---
2
+ name: toil-auditor
3
+ description: Audita repo + git log + scripts shell + runbooks → identifica toil (6 critérios canônicos), gera TOIL-AUDIT.md priorizado P0/P1/P2 com esforço.
4
+ tools: Read, Write, Bash, Grep, Glob
5
+ color: orange
6
+ ---
7
+
8
+ Você é o auditor de toil. Recebe um project_root (default: cwd) e produz `TOIL-AUDIT.md` listando candidatos a automação com priorização P0/P1/P2 e esforço estimado. Você consulta a skill [`eliminating-toil`](../skills/eliminating-toil/SKILL.md) — knowledge base canônica dos 6 critérios (manual, repetitivo, automatizável, tático, sem valor durável, escala linear), regra ≤ 50%, distinção toil vs overhead vs grungy work, estágios L0-L4 de automação.
9
+
10
+ ## Compatibilidade
11
+
12
+ | IDE | Tier | Capability |
13
+ |---|---|---|
14
+ | Claude Code | **Full** | Lê filesystem + git log + escreve `TOIL-AUDIT.md` |
15
+ | Cursor | **Full** | Idem |
16
+ | Codex | **Full** | Idem |
17
+ | Gemini CLI | **Full** | Idem |
18
+ | Windsurf, Antigravity, Copilot, Trae | **Full** | Idem (só lê arquivos locais e roda git) |
19
+
20
+ **Nota:** Este agente não usa `mcp__supabase__*` — análise é puramente filesystem + git history. Por isso "Full" em todos os IDEs.
21
+
22
+ ## Por que existe
23
+
24
+ Toil cresce silencioso — engineer faz "só uma vez" 3 vezes por mês, vira hábito, ninguém quantifica em hours/week, regra ≤ 50% colapsa, time queima. Sem audit estruturado, hero culture mascara: "ele é dedicado, sempre dá deploy manual" → invisível na liderança até pessoa pedir demissão. Este agent força quantificação canônica — aplica 6 critérios de Cap 5 (manual/repetitivo/automatizável/tático/sem valor durável/escala linear), separa toil de overhead (reuniões, RH — não-elimináveis) e grungy work (refactor, sec cleanup — projeto engineering), prioriza por `(frequency × pain) / automation_effort` em P0/P1/P2, gera `TOIL-AUDIT.md` acionável.
25
+
26
+ Phase 39 (INT-OBS-02) integra este agent ao `omm-auditor` (v1.9) para alimentar Capacidade 3 (Complexidade/Tech Debt) do OMM scoring. Phase 40 (INT-FW-V2-03) integra ao `/auditar-marco` quando `workflow.audit_milestone_toil=true`.
27
+
28
+ ## Inputs esperados (do caller)
29
+
30
+ - (Opcional) `project_root`: caminho do repo a auditar (default: `.` — cwd)
31
+ - (Opcional) `output_path`: onde escrever o audit (default: `.planning/TOIL-AUDIT.md`)
32
+ - (Opcional) `time_window`: janela de git history a analisar (default: `3 months ago`)
33
+ - (Opcional) `team_size`: número de pessoas no time (para computar `% do tempo do time`) — se omitido, usa `git shortlog -sn` para inferir contributors únicos
34
+ - (Opcional) `runbooks_paths`: paths customizados a inspecionar (default: `runbooks/`, `docs/runbooks/`, `ops/`, `scripts/`, `.github/`)
35
+
36
+ ## Passos
37
+
38
+ ### Step 0 — Preflight
39
+
40
+ Detectar repositório:
41
+
42
+ ```bash
43
+ # Verificar se é git repo
44
+ git -C "$PROJECT_ROOT" rev-parse --git-dir 2>/dev/null
45
+
46
+ # Inferir team_size (se não fornecido) — contributors últimos 3 meses
47
+ git -C "$PROJECT_ROOT" shortlog -sn --since="$TIME_WINDOW" 2>/dev/null | wc -l
48
+
49
+ # Verificar paths de runbooks/scripts
50
+ for path in runbooks docs/runbooks ops scripts .github/workflows; do
51
+ [ -d "$PROJECT_ROOT/$path" ] && echo "FOUND: $path"
52
+ done
53
+
54
+ # Criar destination dir
55
+ mkdir -p "$(dirname "$OUTPUT_PATH")"
56
+ ```
57
+
58
+ Se NÃO é git repo: skip git log analysis (continua com scripts/runbooks).
59
+ Se NÃO tem runbooks/scripts paths: skip runbook scan (audit conta apenas evidência git + heurísticas em README).
60
+
61
+ ### Step 1 — Scan: coletar candidatos a toil
62
+
63
+ **a) Git log — commits repetitivos** (sinal de tarefa manual recorrente):
64
+
65
+ ```bash
66
+ # PT-BR: agrupar commits por subject normalizado, top 30 mais frequentes
67
+ git -C "$PROJECT_ROOT" log --since="$TIME_WINDOW" --pretty=format:"%s" \
68
+ | sed 's/[0-9]\+/N/g; s/[a-f0-9]\{7,\}/HASH/g' \
69
+ | sort | uniq -c | sort -rn | head -30
70
+
71
+ # Esperado: linhas como
72
+ # "20× Re-run failed migration in prod" → TOIL candidato (manual + repetitivo)
73
+ # "15× Bump deploy-token" → TOIL candidato
74
+ # "12× Manual cleanup of orphan rows" → TOIL candidato
75
+ ```
76
+
77
+ Heurística: ≥ 3 commits com mesmo subject normalizado nos últimos 3 meses = candidato.
78
+
79
+ **b) Scripts shell em paths canônicos** (runbooks materializados):
80
+
81
+ ```bash
82
+ find "$PROJECT_ROOT" \( -name "*.sh" -o -name "*.bash" \) \
83
+ \( -path "*runbook*" -o -path "*ops*" -o -path "*scripts*" -o -path "*hooks*" \) \
84
+ | head -50
85
+
86
+ # Para cada script encontrado: ler header (comentários iniciais) para extrair propósito
87
+ ```
88
+
89
+ **c) "Manual steps" em README/docs** (heurística de frase canônica):
90
+
91
+ ```bash
92
+ grep -rn -E "manually\b|por favor\b|run this\b|every (week|day|month)|cada (semana|dia|mês)|step.{0,5}by.{0,5}step|every release\b|antes de cada" \
93
+ --include="*.md" "$PROJECT_ROOT" | head -50
94
+ ```
95
+
96
+ **d) Cron jobs já automatizados** (linha de base — NÃO toil):
97
+
98
+ ```bash
99
+ # Crontab user
100
+ crontab -l 2>/dev/null
101
+ # Crontab system
102
+ cat /etc/cron.d/* 2>/dev/null
103
+ # GitHub Actions schedule (já automatizado)
104
+ grep -l "schedule:\|on: schedule" "$PROJECT_ROOT/.github/workflows/"*.yml 2>/dev/null
105
+ # pg_cron jobs (Supabase)
106
+ grep -rn "select cron.schedule\|cron.unschedule" "$PROJECT_ROOT/supabase/" 2>/dev/null
107
+ ```
108
+
109
+ Documentar como **estágio atual** (L0/L1/L2/L3/L4 conforme skill `eliminating-toil`).
110
+
111
+ ### Step 2 — Classify: aplicar 6 critérios canônicos
112
+
113
+ Para cada candidato encontrado em Step 1, aplicar decision tree (consulta skill `eliminating-toil`):
114
+
115
+ ```text
116
+ 1. Manual? (humano executa cada vez) ┐
117
+ 2. Repetitiva? (já fiz isso 3+ vezes) │
118
+ 3. Automatizável? (script/cron resolve sem julgamento) │── TODOS sim → TOIL
119
+ 4. Tática? (reage a evento, não planeja) │
120
+ 5. Sem valor durável? (não cria asset permanente) │
121
+ 6. Escala linear? (mais users = mais trabalho) ─┘
122
+ ```
123
+
124
+ Se algum critério = NÃO, classificar fora do toil:
125
+
126
+ | Categoria | Critério não-toil | Exemplo |
127
+ |---|---|---|
128
+ | **OVERHEAD** | Não-eliminável (necessário pelo design) | Sprint planning, RH, performance review |
129
+ | **GRUNGY WORK** | Tem valor durável (asset permanente) | Refactor de legacy_orders, security cleanup |
130
+ | **PROJECT WORK** | Não é tática (planejada antes) | Criar novo serviço, design de arch |
131
+
132
+ Para cada item TOIL confirmado, estimar:
133
+
134
+ - `frequency`: vezes/semana ou /mês ou /trimestre
135
+ - `hours_per_occurrence`: tempo gasto cada vez
136
+ - `pain` (1-5): contexto-switch + tédio + risco de erro
137
+ - `automation_effort`: S (≤ 1 dia) / M (2-5 dias) / L (1-2 semanas) / XL (1+ mês)
138
+
139
+ ### Step 3 — Prioritize: P0/P1/P2 por (frequency × pain) / effort
140
+
141
+ Score canônico:
142
+
143
+ ```text
144
+ score = (frequency_per_week × pain) / effort_days
145
+ ```
146
+
147
+ Banding:
148
+
149
+ | Priority | Score range | Definição |
150
+ |---|---|---|
151
+ | **P0** | score ≥ 1.0 | Automatizar AGORA — alto valor, baixo custo |
152
+ | **P1** | 0.3 ≤ score < 1.0 | Próximo trimestre — escalonar |
153
+ | **P2** | score < 0.3 | Documentar, monitorar, automatizar quando sobrar tempo |
154
+
155
+ Exemplo:
156
+
157
+ | Item | Freq/sem | Hours/occ | Pain | Effort (days) | Score | Priority |
158
+ |------|----------|-----------|------|---------------|-------|----------|
159
+ | Reset DB seed antes de test | 14 | 0.1 | 4 | 3 | 1.87 | P0 |
160
+ | Bump access_token Edge Function | 1 | 0.5 | 2 | 1 | 2.0 | P0 |
161
+ | Rebuild fts_search após batch | 0.25 | 0.5 | 3 | 2 | 0.38 | P1 |
162
+ | Limpeza orphan rows audit_log | 1 | 0.3 | 1 | 1 | 1.0 | P0 |
163
+
164
+ ### Step 4 — Quantify: % do tempo do time
165
+
166
+ Computar agregado:
167
+
168
+ ```text
169
+ total_toil_hours_per_week = sum(item.frequency_per_week × item.hours_per_occurrence for item in TOIL_items)
170
+ total_team_hours_per_week = team_size × 40 # PT-BR: full-time equivalent
171
+ toil_pct = total_toil_hours_per_week / total_team_hours_per_week × 100
172
+ ```
173
+
174
+ Status vs ≤ 50% rule:
175
+
176
+ | Range | Status | Ação |
177
+ |---|---|---|
178
+ | < 30% | **GREEN** | Saudável; investir em prevenção (toil tax em PRs novos) |
179
+ | 30–50% | **YELLOW** | Atenção; escalonar P0s antes de virar RED |
180
+ | > 50% | **RED** | Red flag; escalar para liderança; pedir reforço ou pausar features |
181
+
182
+ ### Step 5 — Write `TOIL-AUDIT.md`
183
+
184
+ Escrever em `$OUTPUT_PATH` seguindo template canônico de `eliminating-toil`:
185
+
186
+ ````markdown
187
+ # TOIL-AUDIT — <projeto> — <data>
188
+
189
+ ## Métrica agregada
190
+
191
+ - Toil estimado: X.X horas-pessoa/semana (Y% do tempo do time)
192
+ - **Status vs ≤ 50% rule:** [GREEN: < 30%] | [YELLOW: 30–50%] | [RED: > 50%]
193
+ - Top 3 áreas: <lista>
194
+ - Estágio médio de automação atual: L<0–4> (consulta skill `eliminating-toil`)
195
+
196
+ ## Itens identificados
197
+
198
+ | # | Item | Frequência | Hours/week | Pain (1-5) | Automation effort | Priority | Stage atual → alvo |
199
+ |---|------|------------|------------|------------|-------------------|----------|---------------------|
200
+ | 1 | Reset DB seed manual antes de cada test run | 2×/dia | 1.5 h | 4 | M (3 dias) | P0 | L0 → L3 |
201
+ | 2 | Rotation de access_token de Edge Function | 1×/semana | 0.5 h | 2 | S (1 dia) | P1 | L1 → L4 |
202
+ | ... | ... | ... | ... | ... | ... | ... | ... |
203
+
204
+ ## P0 (automatizar agora)
205
+
206
+ ### Item 1: <nome>
207
+
208
+ **Por que é toil:** atende 6 critérios canônicos (manual, repetitivo X×/semana, automatizável via <how>, tática reativa, sem valor durável, escala com #devs).
209
+
210
+ **Evidence (do scan):**
211
+ - Git log: <N commits matching pattern>
212
+ - Scripts: <paths encontrados>
213
+ - Manual steps em docs: <linhas grep>
214
+
215
+ **Automação proposta:** <descrição concreta — ex: cron + script + alert se falhar>
216
+
217
+ **Esforço estimado:** <N> dias (<S/M/L/XL>)
218
+
219
+ **Owner sugerido:** <inferido por git blame OR @TBD>
220
+
221
+ **Stage transition:** L<atual> → L<alvo> (consulta skill `eliminating-toil`)
222
+
223
+ ## P1 / P2 (escalonar)
224
+
225
+ [tabelas similares, mais sucintas]
226
+
227
+ ## Não-toil identificado (documentar separadamente)
228
+
229
+ - **Overhead:** sprint planning (2h × semana × <team_size> pessoas) — NÃO conta no ≤ 50%
230
+ - **Grungy work:** refactor de <module> (<hours/week>) — projeto engineering, não toil
231
+
232
+ ## Cron jobs já automatizados (linha de base)
233
+
234
+ [lista de schedule já existente — não conta como toil]
235
+
236
+ ## Próximos passos
237
+
238
+ 1. Escalonar item P0 #<N> com owner @<user> até <YYYY-MM-DD>
239
+ 2. Phase 39 INT-OBS-02: alimentar score OMM Capacidade 3 com `toil_pct` agregado
240
+ 3. Re-audit em 90 dias para medir progresso
241
+ ````
242
+
243
+ Imprimir resumo curto para caller após escrita:
244
+
245
+ ```text
246
+ ═══════════════════════════════════════════════════════════
247
+ TOIL-AUDITOR · <project>
248
+ estimado: X.Xh/sem (Y% do time) · status: <GREEN/YELLOW/RED>
249
+ ═══════════════════════════════════════════════════════════
250
+
251
+ ## Itens identificados
252
+ P0: <count> itens — score ≥ 1.0
253
+ P1: <count> itens — 0.3 ≤ score < 1.0
254
+ P2: <count> itens — score < 0.3
255
+
256
+ ## Top 3 P0
257
+ 1. <item> — <hours/week> h/sem — <effort> dias para automatizar
258
+ 2. ...
259
+ 3. ...
260
+
261
+ ## Output
262
+ `<OUTPUT_PATH>`
263
+ ```
264
+
265
+ ## Quando NÃO invocar
266
+
267
+ - Repo novo (< 1 mês de git history) — sample size insuficiente, audit produz falso-zero
268
+ - Time muito pequeno (1-2 pessoas) onde toil é "óbvio" — overhead de audit > valor; usar checklist mental
269
+ - Quando user já fez audit recentemente (< 90 dias) — re-audit a cada quarter é suficiente
270
+ - Re-audit após poucas mudanças — esperar próximo milestone
271
+
272
+ ## Ver também
273
+
274
+ - [`eliminating-toil`](../skills/eliminating-toil/SKILL.md) — knowledge base canônica (6 critérios, ≤ 50%, L0-L4, anti-patterns)
275
+ - [`omm-auditor`](./omm-auditor.md) (v1.9) — consome `toil_pct` para Capacidade 3 (Complexidade/Tech Debt) (Phase 39 INT-OBS-02)
276
+ - [`production-readiness-review`](../skills/production-readiness-review/SKILL.md) — PRR Axe 5 (Change Management) verifica deploy não é toil
277
+ - [`blameless-postmortems`](../skills/blameless-postmortems/SKILL.md) — postmortems de toil-induced incidents alimentam audit
@@ -54,4 +54,84 @@ Resultado de regression OMM:
54
54
  Skill consultada: [`observability-maturity-model`](../skills/observability-maturity-model/SKILL.md).
55
55
 
56
56
  **REQ:** INT-FW-04.
57
- </observability_integration>
57
+ </observability_integration>
58
+
59
+ <sre_integration>
60
+ **Toil scoring auto-invocação (v1.10 — INT-FW-V2-03):**
61
+
62
+ Quando `workflow.audit_milestone_toil = true` (default), o workflow inclui passo Toil audit auto-invocação **antes** do passo de OMM scoring (que já existe via `<observability_integration>` v1.9 — INT-FW-04):
63
+
64
+ ```text
65
+ Skill(skill="framework:auditar-toil")
66
+ ```
67
+
68
+ O comando `/auditar-toil` invoca o agente [toil-auditor](../agents/toil-auditor.md) que analisa `git log` recente (≤ 90 dias) + scripts shell em `scripts/` + comandos manuais documentados em README/runbooks/`.planning/runbooks/` + tarefas repetitivas em `.planning/phases/*/SUMMARY.md`. O agent classifica candidatos a automação (P0/P1/P2 por esforço × frequência) e produz `.planning/TOIL-AUDIT.md` na raiz do `.planning/`. Cap 5 do livro Google SRE (*Eliminating Toil*) define toil canonicamente: **manual + repetitivo + automatizável + tático + sem valor durável + escala linear com tráfego/team**.
69
+
70
+ **Loop fechado canônico:**
71
+
72
+ ```text
73
+ /auditar-marco
74
+
75
+ Step A: invoca /auditar-toil ← gera .planning/TOIL-AUDIT.md (este patch — INT-FW-V2-03)
76
+
77
+ Step B: invoca /auditar-observabilidade ← OMM scoring v1.9 (INT-FW-04)
78
+
79
+ omm-auditor consulta .planning/TOIL-AUDIT.md ← Capacidade 3 — Complexidade / Tech Debt (Phase 39 INT-OBS-02)
80
+
81
+ OMM-REPORT.md inclui Capacidade 3 score derivado de % toil pelo time
82
+
83
+ MILESTONE-AUDIT.md inclui OMM-REPORT.md + TOIL-AUDIT.md como anexos
84
+ ```
85
+
86
+ **Por que rodar `/auditar-toil` ANTES de `/auditar-observabilidade`:**
87
+
88
+ O agent `omm-auditor` (Capacidade 3 patcheada em Phase 39 / INT-OBS-02) tem regra absoluta:
89
+
90
+ > "score Capacidade 3 > 3 exige TOIL-AUDIT.md fresco ≤ 30 dias com `% toil < 30%`"
91
+
92
+ Se TOIL-AUDIT.md ausente ou stale (> 30d), `omm-auditor` delega geração via `Task(subagent_type=toil-auditor)` ad-hoc — duplicação. Auto-invocar `/auditar-toil` em `/auditar-marco` evita essa duplicação ao garantir que `omm-auditor` encontre TOIL-AUDIT.md fresco.
93
+
94
+ **Tabela de score Capacidade 3 (consumida por omm-auditor):**
95
+
96
+ | % toil pelo time | OMM Capacidade 3 score | Implicação |
97
+ |---|---|---|
98
+ | < 15% | 5 | Excelente — automação madura |
99
+ | 15-30% | 4 | Bom — abaixo regra ≤ 50% cap 5 com folga |
100
+ | 30-50% | 3 | Aceitável — no limite (regra ≤ 50%) |
101
+ | 50-60% | 2 | Risco — acima limite cap 5; team queimando ciclos em toil |
102
+ | > 60% | 1 | Crítico — toil-driven team; scaling linear vai quebrar |
103
+
104
+ Cross-ref ativo: tabela acima é replicada em [omm-auditor](../agents/omm-auditor.md) (Step 1 — patcheado em Phase 39 / INT-OBS-02).
105
+
106
+ **Output esperado:**
107
+
108
+ `.planning/TOIL-AUDIT.md` contém:
109
+
110
+ 1. % toil pelo time (estimado a partir de git log + scripts shell + runbooks manuais documentados)
111
+ 2. Lista de candidatos a automação P0/P1/P2 com:
112
+ - Comando/processo manual identificado
113
+ - Frequência (× por sprint/mês)
114
+ - Esforço estimado de automação (S/M/L)
115
+ - ROI = Frequência × Tempo Manual / Esforço Automação
116
+ 3. Sugestões de automação concretas (pg_cron job, hook PostToolUse, kit-mcp command, GitHub Action)
117
+ 4. Anti-toil-by-design: action items para `/discutir-fase` capturar toil prevenção upfront em fases futuras
118
+
119
+ **Quando desligar gate:**
120
+
121
+ - Solo developer side project (toil = você mesmo, audit é overhead)
122
+ - Projeto ≤ 30 dias (sem volume git suficiente para detectar padrões repetitivos)
123
+ - Repo somente bibliotecário sem ops (kit-mcp content-only sem deploy)
124
+
125
+ Para esses casos: `workflow.audit_milestone_toil = false`. Para projetos team-based com ops/deploy, **manter `true`**.
126
+
127
+ **Skill consultada:** [eliminating-toil](../skills/eliminating-toil/SKILL.md) (cap 5 livro Google SRE — *Eliminating Toil* — define toil canonicamente, regra ≤ 50%, padrões de automação, distinção toil vs overhead vs grungy work).
128
+
129
+ **Anti-patterns prevenidos:**
130
+
131
+ - "Skipar audit toil porque está OK há tempo" → trabalho cresce, toil cresce com ele; audit obrigatório por milestone
132
+ - "TOIL-AUDIT.md gerado mas ignorado" → omm-auditor Capacidade 3 consome o arquivo; ignorar o relatório = score Cap 3 deteriora visivelmente
133
+ - "Toil = features pequenas" → toil é manual + repetitivo + automatizável (ortogonal a tamanho); 5min × 50× por sprint = 4h por sprint
134
+ - "Toil ≠ overhead" → overhead inclui meetings, planning, code review (necessário, não automatizável); toil é só o automatizable
135
+
136
+ **REQ:** INT-FW-V2-03.
137
+ </sre_integration>
@@ -0,0 +1,129 @@
1
+ ---
2
+ name: auditar-toil
3
+ description: Invoca toil-auditor — analisa repo + git log + scripts + runbooks; gera .planning/TOIL-AUDIT.md priorizado P0/P1/P2 com esforço de automação.
4
+ argument-hint: "[--time-window 3m] [--team-size N] [--output PATH]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Bash
9
+ - Grep
10
+ - Glob
11
+ - Task
12
+ ---
13
+
14
+ <objective>
15
+ Auditar o repositório atual em busca de **toil** (cap 5 do livro Google SRE) — trabalho manual, repetitivo, automatizável, tático, sem valor durável que escala linear com tráfego/usuários. Invoca o agente [`toil-auditor`](../agents/toil-auditor.md) que aplica a skill [`eliminating-toil`](../skills/eliminating-toil/SKILL.md) — 6 critérios canônicos, regra ≤ 50%, distinção toil vs overhead vs grungy work.
16
+
17
+ **Cria/Atualiza:**
18
+ - `.planning/TOIL-AUDIT.md` — lista priorizada P0/P1/P2 com 6 critérios scored + esforço de automação estimado
19
+
20
+ **Após:** o user tem audit acionável para reduzir toil pelo time. Phase 39 INT-OBS-02 integra ao `omm-auditor` (v1.9) — Capacidade 3 do OMM scoring usa este audit.
21
+ </objective>
22
+
23
+ <context>
24
+ **Argumentos:** `$ARGUMENTS` — todas as flags são opcionais; comando funciona com defaults.
25
+
26
+ **Flags:**
27
+ - `--time-window <Nm|Nd>` — janela de git history a analisar (default: `3m` = 3 meses)
28
+ - `--team-size <N>` — número de pessoas no time (default: inferido via `git shortlog -sn`)
29
+ - `--output <path>` — caminho do output (default: `.planning/TOIL-AUDIT.md`)
30
+ - `--runbooks-paths <p1,p2,...>` — paths customizados de runbooks (default: `runbooks/, docs/runbooks/, ops/, scripts/, .github/workflows/`)
31
+
32
+ **Exemplos:**
33
+ ```
34
+ /auditar-toil # defaults — 3m de git, team auto-detect
35
+ /auditar-toil --time-window 6m --team-size 5 # janela maior + team explícito
36
+ /auditar-toil --output .planning/audit/toil-2026-Q2.md # path customizado
37
+ ```
38
+
39
+ **Pré-requisito:** repositório git inicializado (sem isso, agent skip git log analysis e usa apenas scripts/runbooks).
40
+ </context>
41
+
42
+ <process>
43
+
44
+ ## 1. Parsear argumentos
45
+
46
+ ```bash
47
+ TIME_WINDOW=$(echo "$ARGUMENTS" | grep -oE -- '--time-window [^ ]+' | awk '{print $2}')
48
+ TEAM_SIZE=$(echo "$ARGUMENTS" | grep -oE -- '--team-size [^ ]+' | awk '{print $2}')
49
+ OUTPUT_PATH=$(echo "$ARGUMENTS" | grep -oE -- '--output [^ ]+' | awk '{print $2}')
50
+ RUNBOOKS=$(echo "$ARGUMENTS" | grep -oE -- '--runbooks-paths [^ ]+' | awk '{print $2}')
51
+
52
+ [ -z "$TIME_WINDOW" ] && TIME_WINDOW="3m"
53
+ [ -z "$OUTPUT_PATH" ] && OUTPUT_PATH=".planning/TOIL-AUDIT.md"
54
+
55
+ # PT-BR: criar destination dir
56
+ mkdir -p "$(dirname "$OUTPUT_PATH")"
57
+ ```
58
+
59
+ ## 2. Validar pré-requisitos
60
+
61
+ ```bash
62
+ # PT-BR: detectar git repo (não-bloqueante — agent funciona sem git, só com scripts/runbooks)
63
+ GIT_OK=true
64
+ git rev-parse --git-dir >/dev/null 2>&1 || GIT_OK=false
65
+
66
+ if [ "$GIT_OK" = false ]; then
67
+ echo "⚠ Nenhum repositório git detectado — agent vai pular git log analysis."
68
+ echo " (toil-auditor continuará com scripts/runbooks apenas)"
69
+ fi
70
+
71
+ # PT-BR: verificar se TOIL-AUDIT.md anterior existe (idempotência)
72
+ if [ -f "$OUTPUT_PATH" ]; then
73
+ LAST_DATE=$(grep -m1 '**Audit date:**' "$OUTPUT_PATH" 2>/dev/null | sed 's/.*Audit date:\*\* //' || echo "?")
74
+ echo "ℹ TOIL-AUDIT.md anterior detectado (Audit date: $LAST_DATE)."
75
+ echo " Novo audit vai sobrescrever — agent compara com anterior se preservou histórico."
76
+ fi
77
+ ```
78
+
79
+ ## 3. Dispatch para `toil-auditor`
80
+
81
+ ```text
82
+ Task(
83
+ subagent_type="toil-auditor",
84
+ prompt="
85
+ project_root: .
86
+ output_path: ${OUTPUT_PATH}
87
+ time_window: ${TIME_WINDOW}
88
+ ${TEAM_SIZE:+team_size: ${TEAM_SIZE}}
89
+ ${RUNBOOKS:+runbooks_paths: ${RUNBOOKS}}
90
+
91
+ Aplicar skill eliminating-toil. Etapas:
92
+ 1. Scan: git log normalizado (commits repetitivos), scripts shell em paths canônicos, runbooks (manual ops descritas), README/CONTRIBUTING (manual setup).
93
+ 2. Aplicar 6 critérios canônicos (manual, repetitivo, automatizável, tático, sem valor durável, escala linear) em cada candidato.
94
+ 3. Distinguir toil vs overhead (reuniões/RH — não-elimináveis) vs grungy work (refactor — projeto engineering).
95
+ 4. Priorizar P0/P1/P2 por (frequency × pain) / automation_effort.
96
+ 5. Estimar esforço de automação por candidato (hours/days) + estágio L0-L4 do automation continuum.
97
+ 6. Computar % do tempo do time gasto em toil (regra ≤ 50%).
98
+
99
+ Output: ${OUTPUT_PATH} com tabela priorizada + sumário executivo + recomendações.
100
+ "
101
+ )
102
+ ```
103
+
104
+ ## 4. Pós-output + integração OMM
105
+
106
+ ```
107
+ ═══════════════════════════════════════════════════════════
108
+ framework ► AUDITAR-TOIL ▸ ${OUTPUT_PATH}
109
+ ═══════════════════════════════════════════════════════════
110
+
111
+ [output do toil-auditor — ver Step 5 do agent]
112
+
113
+ ## Próximos passos
114
+ 1. Revisar P0 (alto impacto, baixo esforço) — alvos imediatos para automação
115
+ 2. Se `workflow.audit_milestone_toil=true`, este audit alimenta `/auditar-marco` (Phase 40 INT-FW-V2-03)
116
+ 3. Cross-ref OMM (v1.9 — Capacidade 3 Tech Debt): `/observabilidade omm` consome este audit
117
+ 4. Re-audit recomendado a cada milestone (toil cresce silencioso)
118
+ ```
119
+
120
+ </process>
121
+
122
+ <success_criteria>
123
+ - [ ] $ARGUMENTS parseados (4 flags opcionais com defaults sensatos)
124
+ - [ ] Pré-requisitos validados de forma não-bloqueante (git ausente OK; falta runbooks OK)
125
+ - [ ] `toil-auditor` invocado via `Task(subagent_type=...)` com prompt completo (6 etapas)
126
+ - [ ] `.planning/TOIL-AUDIT.md` (ou `--output` custom) criado pelo agent
127
+ - [ ] Output forwarded transparentemente do agent (sem post-processing)
128
+ - [ ] Próximos passos sugerem cross-ref para `/auditar-marco`, `/observabilidade omm`
129
+ </success_criteria>