diff --git a/tools/paperclip/paperclip_fleet_error_reporting_audit_once.py b/tools/paperclip/paperclip_fleet_error_reporting_audit_once.py new file mode 100755 index 0000000..e63e4ed --- /dev/null +++ b/tools/paperclip/paperclip_fleet_error_reporting_audit_once.py @@ -0,0 +1,440 @@ +#!/usr/bin/env python3 +""" +Fleet audit — error reporting por slug (semanal). + +Verifica se todos os slugs esperados estão a reportar eventos frescos para +errors.bitreport.pt. Para cada slug silencioso ou stale, cria uma issue de +correção no Paperclip. + +Env vars lidos (ver /etc/paperclip/paperclip-fleet-error-audit.env): + PAPERCLIP_ERROR_API_KEY — chave leitura do hub + PAPERCLIP_FLEET_AUDIT_HUB_BASE — base URL do hub (default: https://errors.bitreport.pt) + PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS — CSV de slugs esperados + PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS — limiar de frescura (default: 168) + PAPERCLIP_FLEET_AUDIT_FETCH_LIMIT — rows a buscar (default: 2000) + PAPERCLIP_FLEET_AUDIT_MIN_ROWS — mínimo de rows antes de enforcement (default: 20) + PAPERCLIP_FLEET_AUDIT_PROJECT_ID — Paperclip project ID para issues de correção + PAPERCLIP_FLEET_AUDIT_ASSIGNEE_ID — Paperclip agent ID para assignar issues + PAPERCLIP_FLEET_AUDIT_PARENT_ID — (opcional) parent issue ID para sub-issues + PAPERCLIP_FLEET_AUDIT_ANCHOR_ISSUE_ID — (opcional) issue onde postar resumo + PAPERCLIP_API_URL — Paperclip API base + PAPERCLIP_API_KEY — Paperclip auth token + PAPERCLIP_COMPANY_ID — Paperclip company ID + PAPERCLIP_RUN_ID — run ID para audit trail +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from collections import defaultdict +from datetime import datetime, timezone +from pathlib import Path +from typing import Any +from urllib import request as urllib_request +from urllib.error import HTTPError, URLError + +# --------------------------------------------------------------------------- +# Env helpers +# --------------------------------------------------------------------------- + +def _load_env_file(path: str) -> None: + try: + lines = Path(path).read_text(encoding="utf-8").splitlines() + except OSError: + return + for line in lines: + line = line.strip() + if not line or line.startswith("#"): + continue + if "=" not in line: + continue + k, _, v = line.partition("=") + k = k.strip() + v = v.strip() + # strip inline comments + if "#" in v: + v = v[: v.index("#")].strip() + if k and k not in os.environ: + os.environ[k] = v + + +def _env(key: str, default: str = "") -> str: + return os.environ.get(key, default).strip() + + +def _env_int(key: str, default: int) -> int: + raw = _env(key) + if not raw: + return default + try: + return int(raw) + except ValueError: + return default + + +# --------------------------------------------------------------------------- +# HTTP helpers +# --------------------------------------------------------------------------- + +def _get_json(url: str, headers: dict[str, str] | None = None) -> Any: + req = urllib_request.Request(url, headers=headers or {}) + try: + with urllib_request.urlopen(req, timeout=30) as resp: + return json.loads(resp.read().decode()) + except HTTPError as e: + body = e.read().decode(errors="replace") + raise RuntimeError(f"HTTP {e.code} {e.url}: {body[:300]}") from e + except URLError as e: + raise RuntimeError(f"URL error {url}: {e.reason}") from e + + +def _post_json(url: str, payload: dict[str, Any], headers: dict[str, str] | None = None) -> Any: + data = json.dumps(payload).encode() + hdrs = {"Content-Type": "application/json", **(headers or {})} + req = urllib_request.Request(url, data=data, headers=hdrs, method="POST") + try: + with urllib_request.urlopen(req, timeout=30) as resp: + return json.loads(resp.read().decode()) + except HTTPError as e: + body = e.read().decode(errors="replace") + raise RuntimeError(f"HTTP {e.code} {e.url}: {body[:300]}") from e + except URLError as e: + raise RuntimeError(f"URL error {url}: {e.reason}") from e + + +def _patch_json(url: str, payload: dict[str, Any], headers: dict[str, str] | None = None) -> Any: + data = json.dumps(payload).encode() + hdrs = {"Content-Type": "application/json", **(headers or {})} + req = urllib_request.Request(url, data=data, headers=hdrs, method="PATCH") + try: + with urllib_request.urlopen(req, timeout=30) as resp: + return json.loads(resp.read().decode()) + except HTTPError as e: + body = e.read().decode(errors="replace") + raise RuntimeError(f"HTTP {e.code} {e.url}: {body[:300]}") from e + except URLError as e: + raise RuntimeError(f"URL error {url}: {e.reason}") from e + + +# --------------------------------------------------------------------------- +# Hub query +# --------------------------------------------------------------------------- + +def fetch_hub_rows(hub_base: str, api_key: str, limit: int) -> list[dict[str, Any]]: + url = ( + f"{hub_base}/api/error-monitoring/recent-errors" + f"?limit={limit}&status=open,investigating,resolved,ignored" + f"&order=occurred_at_desc&api_key={api_key}" + ) + # Use curl to avoid Cloudflare bot challenges on urllib + result = subprocess.run( + ["curl", "-sf", "--max-time", "30", url], + capture_output=True, text=True, + ) + if result.returncode != 0: + raise RuntimeError(f"curl failed (exit {result.returncode}): {result.stderr[:200]}") + try: + data = json.loads(result.stdout) + except json.JSONDecodeError as e: + raise RuntimeError(f"Invalid JSON from hub: {e} — body: {result.stdout[:200]}") from e + if not data.get("success"): + raise RuntimeError(f"Hub returned success=false: {data}") + return data.get("data", []) + + +def analyse_rows( + rows: list[dict[str, Any]], + expected_slugs: list[str], + max_age_hours: int, + min_rows: int, +) -> dict[str, Any]: + now = datetime.now(timezone.utc) + + # Aggregate per slug + by_slug: dict[str, list[datetime]] = defaultdict(list) + for row in rows: + slug = str(row.get("project_slug", "")).lower() + occurred_at_raw = row.get("occurred_at", "") + if not slug or not occurred_at_raw: + continue + try: + dt = datetime.fromisoformat(str(occurred_at_raw).replace("Z", "+00:00")) + by_slug[slug].append(dt) + except ValueError: + pass + + total_rows = len(rows) + enforcement_active = total_rows >= min_rows + + results: list[dict[str, Any]] = [] + for slug in expected_slugs: + times = by_slug.get(slug, []) + if not times: + status = "silent" + hours_since = None + latest = None + else: + latest = max(times) + hours_since = (now - latest).total_seconds() / 3600 + status = "stale" if hours_since > max_age_hours else "ok" + + results.append( + { + "slug": slug, + "status": status, + "event_count": len(times), + "latest_occurred_at": latest.isoformat() if latest else None, + "hours_since_last_event": round(hours_since, 1) if hours_since is not None else None, + } + ) + + seen_slugs = sorted(by_slug.keys()) + unexpected_slugs = [s for s in seen_slugs if s not in expected_slugs] + + return { + "total_rows_fetched": total_rows, + "min_rows": min_rows, + "enforcement_active": enforcement_active, + "max_age_hours": max_age_hours, + "expected_slugs": expected_slugs, + "results": results, + "unexpected_slugs": unexpected_slugs, + "audited_at": now.isoformat(), + } + + +# --------------------------------------------------------------------------- +# Paperclip helpers +# --------------------------------------------------------------------------- + +def paperclip_create_issue( + api_url: str, + api_key: str, + run_id: str, + company_id: str, + title: str, + description: str, + project_id: str, + assignee_id: str, + parent_id: str | None, +) -> dict[str, Any]: + payload: dict[str, Any] = { + "title": title, + "description": description, + "status": "todo", + "priority": "high", + "projectId": project_id, + "assigneeAgentId": assignee_id, + } + if parent_id: + payload["parentId"] = parent_id + + headers = { + "Authorization": f"Bearer {api_key}", + "X-Paperclip-Run-Id": run_id, + } + return _post_json(f"{api_url}/api/companies/{company_id}/issues", payload, headers) + + +def paperclip_post_comment( + api_url: str, + api_key: str, + run_id: str, + issue_id: str, + body: str, +) -> dict[str, Any]: + headers = { + "Authorization": f"Bearer {api_key}", + "X-Paperclip-Run-Id": run_id, + } + return _post_json( + f"{api_url}/api/issues/{issue_id}/comments", + {"body": body}, + headers, + ) + + +def paperclip_update_issue( + api_url: str, + api_key: str, + run_id: str, + issue_id: str, + payload: dict[str, Any], +) -> dict[str, Any]: + headers = { + "Authorization": f"Bearer {api_key}", + "X-Paperclip-Run-Id": run_id, + } + return _patch_json(f"{api_url}/api/issues/{issue_id}", payload, headers) + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +def main() -> int: + # Load env files (automation.env first so fleet-audit.env can override) + _load_env_file("/etc/paperclip/automation.env") + _load_env_file("/etc/paperclip/paperclip-fleet-error-audit.env") + + hub_base = _env("PAPERCLIP_FLEET_AUDIT_HUB_BASE", "https://errors.bitreport.pt").rstrip("/") + hub_api_key = _env("PAPERCLIP_ERROR_API_KEY") + expected_slugs_raw = _env("PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS", "") + max_age_hours = _env_int("PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS", 168) + fetch_limit = _env_int("PAPERCLIP_FLEET_AUDIT_FETCH_LIMIT", 2000) + min_rows = _env_int("PAPERCLIP_FLEET_AUDIT_MIN_ROWS", 20) + project_id = _env("PAPERCLIP_FLEET_AUDIT_PROJECT_ID") + assignee_id = _env("PAPERCLIP_FLEET_AUDIT_ASSIGNEE_ID") + parent_id = _env("PAPERCLIP_FLEET_AUDIT_PARENT_ID") or None + anchor_issue_id = _env("PAPERCLIP_FLEET_AUDIT_ANCHOR_ISSUE_ID") or None + + api_url = _env("PAPERCLIP_API_URL", "http://127.0.0.1:3100") + api_key = _env("PAPERCLIP_API_KEY") + run_id = _env("PAPERCLIP_RUN_ID", "") + company_id = _env("PAPERCLIP_COMPANY_ID") + + # Validation + if not hub_api_key: + print("ERROR: PAPERCLIP_ERROR_API_KEY is not set", file=sys.stderr) + return 1 + + expected_slugs = [s.strip().lower() for s in expected_slugs_raw.split(",") if s.strip()] + if not expected_slugs: + print("ERROR: PAPERCLIP_FLEET_AUDIT_EXPECTED_SLUGS is empty", file=sys.stderr) + return 1 + + print(f"Fleet audit starting — hub: {hub_base}") + print(f"Expected slugs: {expected_slugs}") + print(f"Max age: {max_age_hours}h, min rows: {min_rows}, fetch limit: {fetch_limit}") + + # Fetch hub data + try: + rows = fetch_hub_rows(hub_base, hub_api_key, fetch_limit) + except RuntimeError as e: + print(f"ERROR fetching hub rows: {e}", file=sys.stderr) + return 1 + + print(f"Fetched {len(rows)} rows from hub") + + # Analyse + report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows) + print(json.dumps(report, indent=2, default=str)) + + # Determine problems + if not report["enforcement_active"]: + print( + f"\nEnforcement SKIPPED — only {report['total_rows_fetched']} rows " + f"(threshold: {min_rows}). Hub may be quiet; no correction issues created." + ) + else: + problems = [r for r in report["results"] if r["status"] in ("silent", "stale")] + if problems: + print(f"\n{len(problems)} problem slug(s) found — creating correction issues") + else: + print("\nAll expected slugs are fresh — no correction issues needed") + + problems = [r for r in report["results"] if r["status"] in ("silent", "stale")] + created_issues: list[dict[str, Any]] = [] + + if report["enforcement_active"] and problems and project_id and assignee_id and api_key and company_id: + for p in problems: + slug = p["slug"] + status = p["status"] + if status == "silent": + title = f"[fleet-audit] {slug} — sem eventos no hub (slug silencioso)" + desc = ( + f"O slug `{slug}` não tem eventos registados em `{hub_base}`.\n\n" + f"Auditoria: {report['audited_at']}\n" + f"Total de rows no hub: {report['total_rows_fetched']}" + ) + else: + hours = p["hours_since_last_event"] + latest = p["latest_occurred_at"] + title = f"[fleet-audit] {slug} — stale ({hours:.0f}h sem eventos)" + desc = ( + f"O slug `{slug}` está stale: último evento há **{hours:.1f}h** " + f"(limiar: {max_age_hours}h).\n\n" + f"Último evento: `{latest}`\n" + f"Hub: `{hub_base}`\n" + f"Auditoria: {report['audited_at']}" + ) + + try: + issue = paperclip_create_issue( + api_url, api_key, run_id, company_id, + title, desc, project_id, assignee_id, parent_id, + ) + issue_id = issue.get("id", "") + identifier = issue.get("identifier", "") + created_issues.append({"slug": slug, "issue_id": issue_id, "identifier": identifier}) + print(f" Created correction issue {identifier} for slug '{slug}'") + except RuntimeError as e: + print(f" ERROR creating issue for slug '{slug}': {e}", file=sys.stderr) + + # Build summary comment + lines = ["## Fleet Audit — Error Reporting por Slug", ""] + lines.append(f"**Auditado em:** {report['audited_at']}") + lines.append(f"**Hub:** {hub_base}") + lines.append(f"**Rows fetched:** {report['total_rows_fetched']} (min para enforcement: {min_rows})") + lines.append("") + + if not report["enforcement_active"]: + lines.append("> **Enforcement inativo** — hub com poucos eventos, possível dia tranquilo.") + lines.append("") + + lines.append("### Slugs esperados") + lines.append("") + for r in report["results"]: + slug = r["slug"] + st = r["status"] + if st == "ok": + hours = r["hours_since_last_event"] + icon = "✅" + detail = f"fresco — último evento há {hours:.1f}h" + elif st == "stale": + hours = r["hours_since_last_event"] + icon = "⚠️" + detail = f"stale — último evento há {hours:.1f}h (limiar: {max_age_hours}h)" + else: + icon = "🔴" + detail = "silencioso — sem eventos" + lines.append(f"- {icon} **{slug}**: {detail}") + + if report["unexpected_slugs"]: + lines.append("") + lines.append("### Slugs inesperados no hub (informação)") + for s in report["unexpected_slugs"]: + lines.append(f"- `{s}`") + + if created_issues: + lines.append("") + lines.append("### Issues de correção criadas") + for ci in created_issues: + identifier = ci["identifier"] + issue_id = ci["issue_id"] + lines.append(f"- [{identifier}](/BIT/issues/{identifier}) — slug `{ci['slug']}`") + + if not problems or not report["enforcement_active"]: + lines.append("") + lines.append("_Sem ações corretivas necessárias nesta execução._") + + summary_comment = "\n".join(lines) + print("\n--- SUMMARY ---") + print(summary_comment) + + # Post summary to anchor issue if configured + if anchor_issue_id and api_key: + try: + paperclip_post_comment(api_url, api_key, run_id, anchor_issue_id, summary_comment) + print(f"\nSummary posted to issue {anchor_issue_id}") + except RuntimeError as e: + print(f"WARNING: could not post summary comment: {e}", file=sys.stderr) + + return 0 + + +if __name__ == "__main__": + sys.exit(main())