--- name: clip-routine description: Gerir routines Paperclip — listar crons activos, ver execuções, criar/editar routines. Usar quando "clip routine", "routines clip", "crons paperclip", "automações clip". context: fork layer: wiki --- # /clip-routine — Gerir Routines Paperclip ## Modelo de governance (desde 29-03-2026) **Todas as routines são atribuídas ao CEO.** O CEO delega pela cadeia hierárquica: ``` Routine (cron trigger) → CEO avalia e delega → C-Level adiciona contexto departamental → Director coordena e atribui → Especialista executa → Resultado sobe a cadeia com síntese progressiva ``` Cada routine tem no campo `description` a cadeia de delegação (ex: `CADEIA: CEO → CTO → Dir. Infraestrutura → Backup Specialist`). **Regras:** - Novas routines devem ser SEMPRE atribuídas ao CEO - A cadeia de delegação deve estar explícita na descrição - Nunca atribuir routines directamente a especialistas — quebra a visibilidade hierárquica ## Dois tipos de periodicidade 1. **Heartbeats** — intervalos configurados via `runtime_config` dos agentes (quando acordam) 2. **Routines** — tarefas periódicas via tabela `routines` + `routine_triggers` com cron (o que fazem ao acordar) ## Constantes ``` BD: PGPASSWORD="paperclip" psql -h localhost -p 54329 -U paperclip -d paperclip COMPANY_ID: ebe10308-efd7-453f-86ab-13e6fe84004f ``` ## Tiers de heartbeat | Tier | Intervalo | Uso | |------|-----------|-----| | 1 | 1h (3600s) | CEO, agentes criticos | | 2 | 2h (7200s) | C-Level activos | | 3 | 4h (14400s) | Directores | | 4 | 6h (21600s) | Especialistas com rotina | | 5 | on-demand | Especialistas reactivos (sem timer) | ## Modo lista (sem argumentos) Listar agentes com heartbeat configurado: ```sql SELECT name, role, status, runtime_config->'heartbeat'->>'enabled' as hb_enabled, runtime_config->'heartbeat'->>'intervalSec' as hb_interval, last_heartbeat_at FROM agents WHERE company_id = 'ebe10308-efd7-453f-86ab-13e6fe84004f' AND runtime_config::text != '{}' AND runtime_config->'heartbeat' IS NOT NULL ORDER BY (runtime_config->'heartbeat'->>'intervalSec')::int ASC NULLS LAST; ``` Complementar com contagem de execucoes recentes: ```sql SELECT a.name, COUNT(CASE WHEN hr.status = 'succeeded' THEN 1 END) as ok_24h, COUNT(CASE WHEN hr.status = 'failed' THEN 1 END) as fail_24h FROM agents a LEFT JOIN heartbeat_runs hr ON hr.agent_id = a.id AND hr.started_at > NOW() - INTERVAL '24 hours' WHERE a.company_id = 'ebe10308-efd7-453f-86ab-13e6fe84004f' AND a.runtime_config->'heartbeat' IS NOT NULL GROUP BY a.name ORDER BY a.name; ``` ## Modo ver (com nome de agente) Ultimas 10 execucoes de um agente: ```sql SELECT hr.status, hr.started_at, hr.finished_at, LEFT(hr.error, 80) as erro FROM heartbeat_runs hr JOIN agents a ON hr.agent_id = a.id WHERE a.company_id = 'ebe10308-efd7-453f-86ab-13e6fe84004f' AND LOWER(a.name) LIKE LOWER('%{{NOME}}%') ORDER BY hr.started_at DESC LIMIT 10; ``` ## Modo criar/editar (configurar heartbeat) ### Activar heartbeat ```sql UPDATE agents SET runtime_config = jsonb_set( COALESCE(runtime_config, '{}'::jsonb), '{heartbeat}', '{"enabled": true, "intervalSec": {{INTERVALO}}, "cooldownSec": 10, "wakeOnDemand": true, "maxConcurrentRuns": 1}'::jsonb ) WHERE name = '{{NOME}}' AND company_id = 'ebe10308-efd7-453f-86ab-13e6fe84004f' RETURNING name, runtime_config; ``` Confirmar sempre com o utilizador: - Nome do agente - Intervalo (sugerir tier adequado ao role) - wakeOnDemand (true para a maioria) ### Desactivar heartbeat ```sql UPDATE agents SET runtime_config = jsonb_set( runtime_config, '{heartbeat,enabled}', 'false'::jsonb ) WHERE name = '{{NOME}}' AND company_id = 'ebe10308-efd7-453f-86ab-13e6fe84004f' RETURNING name, runtime_config; ``` ### Alterar intervalo ```sql UPDATE agents SET runtime_config = jsonb_set( runtime_config, '{heartbeat,intervalSec}', '{{INTERVALO}}'::jsonb ) WHERE name = '{{NOME}}' AND company_id = 'ebe10308-efd7-453f-86ab-13e6fe84004f' RETURNING name, runtime_config; ``` ## Routines do projecto (tabela routines) Alem dos heartbeats por agente, existem routines organizadas por projecto com cron triggers. **Estado actual:** 5 routines activas no Paperclip. 9 routines anteriores foram migradas para workflows n8n em https://automator.descomplicar.pt. **5 routines Paperclip:** - Auditoria processos e compliance (0 10 * * *) - Execução tarefas AikTop (*/30 * * * *) - Reconciliação financeira diária (0 8 * * *) - Varredura inteligência competitiva (0 11 * * *) - Monitorização workflows n8n (0 10,18 * * *) — atribuída ao COO ### Listar routines activas ```sql SELECT r.title, r.status, r.priority, a.name as assignee, rt.cron_expression, rt.enabled, rt.next_run_at FROM routines r LEFT JOIN agents a ON r.assignee_agent_id = a.id LEFT JOIN routine_triggers rt ON rt.routine_id = r.id WHERE r.company_id = 'ebe10308-efd7-453f-86ab-13e6fe84004f' ORDER BY r.title; ``` ### Ver execucoes de uma routine ```sql SELECT rr.status, rr.triggered