Compare commits

..
Author SHA1 Message Date
1sonhador 8f7ff6b1d5 chore: limit CODEOWNERS to active Gitea reviewers
CI / Test ingest-api (pull_request) Successful in 28s
CI / Test api (pull_request) Successful in 34s
CI / Lint and typecheck admin-ui (pull_request) Successful in 59s
CI / Validate Docker build (pull_request) Successful in 4m16s
Only owners that review in practice are listed, so official review
requests from code owners never block merges on protected branches.
2026-10-22 04:45:10 +01:00
spark dc1aa3365e Merge branch 'master' into chore/codeowners-fix
CI / Test ingest-api (pull_request) Successful in 36s
CI / Test api (pull_request) Successful in 36s
CI / Lint and typecheck admin-ui (pull_request) Successful in 1m3s
CI / Validate Docker build (pull_request) Successful in 3m2s
2026-10-22 01:16:24 +01:00
spark d987d2aaf4 Merge pull request 'fix(hub): BIT-31442 route /v1/paperclip alias to admin API + accept X-Api-Key header' (#17) from fix/BIT-31442-recent-errors-alias-proxy-and-xapikey into master
CI / Test ingest-api (push) Successful in 25s
CI / Test api (push) Successful in 29s
CI / Lint and typecheck admin-ui (push) Successful in 59s
CI / Validate Docker build (push) Successful in 4m24s
2026-10-21 20:40:24 +01:00
David Santos d4059d801a fix(hub): BIT-31442 route /v1/paperclip alias to admin API + accept X-Api-Key header
CI / Test ingest-api (pull_request) Successful in 41s
CI / Test api (pull_request) Successful in 44s
CI / Lint and typecheck admin-ui (pull_request) Successful in 1m24s
CI / Validate Docker build (pull_request) Successful in 6m2s
The recent-errors handler (api/src/routes/public/recentErrors.ts) registers
both GET /api/error-monitoring/recent-errors and the alias
GET /v1/paperclip/recent-errors on the admin API (port 3200). However the
admin-ui Next.js rewrite sent all /v1/* to ingest-api (port 3041), which has
no such route, so the alias returned 404 in production while the
/api/error-monitoring path worked (401 without a key).

Changes:
- admin-ui/next.config.ts: add a specific /v1/paperclip/:path* -> admin API
  rewrite before the generic /v1/:path* -> ingest-api rule (rewrite order
  matters; first match wins).
- api/src/lib/errorMonitoringAuth.ts: authorizeReadQuery now also accepts an
  X-Api-Key header carrying either ERROR_RESOLVE_API_KEY/ERROR_REPORTING_API_KEY
  or DEBUG_VIEW_ERRORS_KEY, so programmatic callers avoid leaking keys in
  URLs/access logs. Backward compatible with the existing query params.
- api/src/routes/public/recentErrors.test.ts: cover the alias path and the
  X-Api-Key header (resolve key, view key, invalid key).
- docs/HTTP_CONTRACTS.md, docs/permission-matrix.md: document the header and
  the proxy ordering requirement.
2026-10-21 18:16:05 +01:00
1sonhador 9e318b5b9a chore: corrige CODEOWNERS para contas existentes no Gitea
CI / Test ingest-api (pull_request) Successful in 2m12s
CI / Test api (pull_request) Successful in 2m2s
CI / Lint and typecheck admin-ui (pull_request) Successful in 1m37s
CI / Validate Docker build (pull_request) Successful in 4m59s
2026-10-21 17:33:02 +01:00
spark 954b0ced2e Merge pull request 'chore(hub): BIT-30701 add per-slug freshness override + exclude synthetic smoke-test events from fleet audit' (#15) from chore/BIT-30701-fleet-audit-per-slug-threshold-and-synthetic-filter into master
CI / Test ingest-api (push) Successful in 1m2s
CI / Test api (push) Successful in 1m11s
CI / Lint and typecheck admin-ui (push) Successful in 2m6s
CI / Validate Docker build (push) Successful in 5m11s
2026-09-28 08:22:42 +01:00
David Santos 9dd88db4ae chore(hub): BIT-30701 add per-slug freshness override + exclude synthetic smoke-test events from fleet audit
CI / Test ingest-api (pull_request) Successful in 55s
CI / Test api (pull_request) Successful in 1m1s
CI / Lint and typecheck admin-ui (pull_request) Successful in 2m9s
CI / Validate Docker build (pull_request) Successful in 5m55s
netvision's real error rate dropped sharply after the 2026-08-25..08-29 bug-fix
wave; at the global 168h threshold the weekly audit fired 3 weeks running for a
now-quiet app, not a broken pipe (BIT-30273/BIT-30527). Each investigation sent
a synthetic verification event to confirm the reporter still works, but those
events were then counted as "fresh" traffic by the next week's run, masking
the real last-event date until the synthetic row itself aged past the
threshold.

Add PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS_OVERRIDES (CSV slug=hours) so a slug's
threshold can differ from the global default, and exclude events matching the
"[BIT-xxxxx] <actor> ... smoke test" marker convention from freshness scoring
so future liveness checks no longer pollute the metric.
2026-09-28 08:22:16 +01:00
spark 52e75a8760 Merge pull request 'chore(hub): BIT-30044 restore multi-status filter in fleet audit script' (#14) from chore/BIT-30044-restore-multistatus-audit-filter into master
CI / Test ingest-api (push) Successful in 1m28s
CI / Test api (push) Successful in 1m30s
CI / Lint and typecheck admin-ui (push) Successful in 2m42s
CI / Validate Docker build (push) Successful in 6m25s
2026-09-07 09:40:05 +01:00
David Santos b190d6fa1b chore(hub): BIT-30044 restore multi-status filter in fleet audit script
CI / Test ingest-api (pull_request) Successful in 54s
CI / Test api (pull_request) Successful in 1m6s
CI / Lint and typecheck admin-ui (pull_request) Successful in 2m37s
CI / Validate Docker build (pull_request) Successful in 6m56s
Revert the BIT-25722 workaround now that BIT-30040 fixed the recent-errors
mega-incident query hang (verified <1s in prod with status=open,investigating,resolved,ignored&limit=2000).
2026-09-07 09:39:28 +01:00
spark 3da9e47873 Merge pull request 'fix(hub): BIT-30040 stop ROW_NUMBER from materializing mega-incident partitions' (#13) from fix/BIT-30040-recent-errors-mega-incident-fastpath into master
CI / Test ingest-api (push) Successful in 1m26s
CI / Test api (push) Successful in 1m41s
CI / Lint and typecheck admin-ui (push) Successful in 3m28s
CI / Validate Docker build (push) Successful in 7m8s
2026-09-07 09:12:28 +01:00
David Santos a1fd3d2db0 fix(hub): BIT-30040 stop ROW_NUMBER from materializing mega-incident partitions
CI / Test ingest-api (pull_request) Successful in 1m9s
CI / Test api (pull_request) Successful in 1m22s
CI / Lint and typecheck admin-ui (pull_request) Successful in 2m30s
CI / Validate Docker build (pull_request) Successful in 8m52s
BIT-29730's incident-first fast path still ran ROW_NUMBER() OVER
(PARTITION BY incident_id ...) across ALL occurrences of every
selected incident before filtering rn = 1. MariaDB can't turn a
PARTITION BY window function into a loose index scan, so it
materializes and sorts each partition in full. At fleet-audit scale
(status=open,investigating,resolved,ignored&limit=2000) several
"mega-incidents" with 48k-148k occurrences each landed in the
selected page, and sorting those partitions hung the query for 70s+.

Replace the ROW_NUMBER CTE with a `LIMIT 1` correlated subquery per
selected incident. EXPLAIN confirms this walks
er_incident_occurrences_incident_time_idx (incident_id, occurred_at
DESC) and stops at the first row per incident instead of scanning the
rest of its history.

Verified against MariaDB (docker compose) seeded with the production
shape from the bug report (3235 resolved / 20 open incidents, 5
mega-incidents at 48k-148k occurrences each, ~425k occurrence rows
total): status=open,investigating,resolved,ignored&limit=2000 dropped
from 2.1s to 0.44s with identical result rows, and
status=resolved&limit=10 stayed at ~0.3s untouched by the
mega-incidents.
2026-09-07 09:05:52 +01:00
spark 7f76c5287d Merge pull request 'fix(hub): BIT-29730 stop timeout on GET recent-errors?status=resolved' (#12) from fix/BIT-29730-recent-errors-resolved-timeout into master
CI / Test ingest-api (push) Successful in 49s
CI / Test api (push) Successful in 50s
CI / Lint and typecheck admin-ui (push) Successful in 1m29s
CI / Validate Docker build (push) Successful in 4m27s
2026-08-24 09:02:38 +01:00
8 changed files with 159 additions and 31 deletions

No files matched your search

+4 -4
View File
@@ -2,11 +2,11 @@
# Replace/add owners as needed per repository domain.
# CI and forge metadata
/.gitea/ @tiago-neves @david-santos
/.gitea/workflows/ @tiago-neves @david-santos
/.gitea/ @devops-engineer @founding-engineer
/.gitea/workflows/ @devops-engineer @founding-engineer
# Documentation
/docs/ @david-santos @planner
/docs/ @founding-engineer
# Catch-all
* @david-santos
* @founding-engineer
+9
View File
@@ -23,6 +23,15 @@ const nextConfig: NextConfig = {
async rewrites() {
return [
{ source: "/health", destination: `${INGEST_API_URL}/health` },
// BIT-31442: the recent-errors handler (api/src/routes/public/recentErrors.ts)
// registers the /v1/paperclip/recent-errors alias on the admin API (port 3200),
// not on ingest-api. The generic /v1/* rule below would otherwise send it to
// ingest-api (port 3041), which has no such route and returns 404. This more
// specific rule must come first; Next.js evaluates rewrites in order.
{
source: "/v1/paperclip/:path*",
destination: `${ADMIN_API_URL}/v1/paperclip/:path*`,
},
{ source: "/v1/:path*", destination: `${INGEST_API_URL}/v1/:path*` },
{
source: "/api/error-monitoring/:path*",
+16
View File
@@ -45,6 +45,22 @@ export function authorizeReadQuery(request: FastifyRequest, reply: FastifyReply)
return true;
}
// BIT-31442: accept X-Api-Key header as an alternative to the query param so
// programmatic callers (Paperclip, QA) can avoid leaking the key in URLs/logs.
// The header may carry either the resolve/reporting key or the read-only
// DEBUG_VIEW_ERRORS_KEY, mirroring the query-param semantics.
const headerRaw = request.headers['x-api-key'];
const headerVal = Array.isArray(headerRaw) ? headerRaw[0] : headerRaw;
const providedHeader = typeof headerVal === 'string' ? headerVal.trim() : '';
if (providedHeader !== '') {
if (apiKey && safeEqual(providedHeader, apiKey)) {
return true;
}
if (viewKey && safeEqual(providedHeader, viewKey)) {
return true;
}
}
reply.code(401).send({
success: false,
message: 'Unauthorized',
@@ -171,4 +171,60 @@ describe('GET /api/error-monitoring/recent-errors', () => {
// ['resolved', '%boom%', '%boom%', '%boom%', limit, offset]
expect(params).toEqual(['resolved', '%boom%', '%boom%', '%boom%', 10, 0]);
});
it('serves the /v1/paperclip/recent-errors alias from the same handler (BIT-31442)', async () => {
const execute = vi.fn().mockResolvedValue([[]]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/v1/paperclip/recent-errors?api_key=test-recent-errors-key',
});
expect(res.statusCode).toBe(200);
expect(execute).toHaveBeenCalledTimes(1);
});
it('accepts the resolve key via X-Api-Key header (BIT-31442)', async () => {
const execute = vi.fn().mockResolvedValue([[]]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/recent-errors',
headers: { 'x-api-key': 'test-recent-errors-key' },
});
expect(res.statusCode).toBe(200);
expect(execute).toHaveBeenCalledTimes(1);
});
it('accepts the read-only view key via X-Api-Key header (BIT-31442)', async () => {
const prevView = process.env.DEBUG_VIEW_ERRORS_KEY;
process.env.DEBUG_VIEW_ERRORS_KEY = 'test-view-key';
try {
const execute = vi.fn().mockResolvedValue([[]]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/recent-errors',
headers: { 'x-api-key': 'test-view-key' },
});
expect(res.statusCode).toBe(200);
} finally {
if (prevView === undefined) {
delete process.env.DEBUG_VIEW_ERRORS_KEY;
} else {
process.env.DEBUG_VIEW_ERRORS_KEY = prevView;
}
}
});
it('rejects an invalid X-Api-Key header with 401 (BIT-31442)', async () => {
const execute = vi.fn().mockResolvedValue([[]]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/recent-errors',
headers: { 'x-api-key': 'wrong-key' },
});
expect(res.statusCode).toBe(401);
expect(execute).not.toHaveBeenCalled();
});
});
+21 -21
View File
@@ -178,12 +178,18 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
let params: Array<string | number>;
if (!hasSearch) {
// Fast path (BIT-29730): page through er_incidents first (small, indexed by
// current_state) and only rank/scan occurrences for the selected page of
// incidents. Starting from er_incident_occurrences instead — as the search
// path below still does — makes the window function churn through the full
// occurrence history of every matching incident before LIMIT is applied,
// which times out for status=resolved (the majority, longest-lived state).
// Fast path (BIT-29730, tightened in BIT-30040): page through er_incidents
// first (small, indexed by current_state) and fetch only the single latest
// occurrence per selected incident via a correlated subquery. Earlier this
// still used ROW_NUMBER() over ALL occurrences of the selected incidents —
// MariaDB can't turn PARTITION BY into a loose index scan, so it
// materialized and sorted the entire occurrence history of every matching
// incident before filtering rn = 1. Fleet-audit-scale "mega-incidents"
// (100k+ occurrences each) blew that up to minutes even after the
// incident-first paging fix. A `LIMIT 1` correlated subquery per incident
// instead walks er_incident_occurrences_incident_time_idx
// (incident_id, occurred_at DESC) and stops at the first row — no
// materialization of the rest of that incident's history.
const incidentOrderDir = orderRaw === 'occurred_at_asc' ? 'ASC' : 'DESC';
sql = `
WITH selected_incidents AS (
@@ -193,18 +199,6 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
WHERE ${incidentWhereClause}
ORDER BY i.last_seen_at ${incidentOrderDir}, i.id ${incidentOrderDir}
LIMIT ? OFFSET ?
),
ranked AS (
SELECT o.id,
o.incident_id,
o.message,
o.stack_trace AS stack_trace,
o.context_json AS context_json,
o.environment,
o.occurred_at AS occurred_at,
ROW_NUMBER() OVER (PARTITION BY o.incident_id ORDER BY o.occurred_at DESC, o.id DESC) AS rn
FROM er_incident_occurrences o
INNER JOIN selected_incidents si ON si.incident_id = o.incident_id
)
SELECT CAST(i.id AS CHAR) AS incident_id,
CAST(r.id AS CHAR) AS occurrence_id,
@@ -216,10 +210,16 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
r.context_json,
r.environment,
r.occurred_at
FROM ranked r
INNER JOIN er_incidents i ON i.id = r.incident_id
FROM selected_incidents si
INNER JOIN er_incidents i ON i.id = si.incident_id
INNER JOIN er_projects p ON p.id = i.project_id
WHERE r.rn = 1
INNER JOIN er_incident_occurrences r ON r.id = (
SELECT o.id
FROM er_incident_occurrences o
WHERE o.incident_id = si.incident_id
ORDER BY o.occurred_at DESC, o.id DESC
LIMIT 1
)
ORDER BY ${orderSql}
`;
params = [...incidentParams, limit, offset];
+4
View File
@@ -59,6 +59,10 @@ Alias: `GET /v1/paperclip/recent-errors` (same handler).
**Query:** `api_key` *or* `view_errors`, plus optional `limit`, `offset`, `status`, `severity`, `project_slug`, `q`, `order`.
**Header (BIT-31442):** `X-Api-Key: <key>` is accepted as an alternative to the `api_key`/`view_errors` query params, so programmatic callers can avoid leaking the key in URLs and access logs. The header may carry either `ERROR_RESOLVE_API_KEY`/`ERROR_REPORTING_API_KEY` or the read-only `DEBUG_VIEW_ERRORS_KEY`.
> **Proxy note (BIT-31442):** the `/v1/paperclip/*` alias is served by the admin API (port 3200), not ingest-api (port 3041). The `admin-ui` Next.js rewrite routes `/v1/paperclip/:path*` to the admin API *before* the generic `/v1/:path*` → ingest-api rule. If the alias returns 404 in production, verify that rewrite order in `admin-ui/next.config.ts`.
**Response 200**
```json
+4 -1
View File
@@ -50,11 +50,14 @@ These routes mirror the CRM error-monitoring module for Paperclip and automation
### Read: `GET /api/error-monitoring/recent-errors`
Alias: `GET /v1/paperclip/recent-errors` (same handler; served by the admin API via the `admin-ui` rewrite — BIT-31442).
| Credential | Notes |
|------------|--------|
| `api_key` query | Must match `ERROR_RESOLVE_API_KEY` or `ERROR_REPORTING_API_KEY` |
| `view_errors` query | Must match `DEBUG_VIEW_ERRORS_KEY` (read-oriented) |
| Admin session | Not used on this path; query credentials only |
| `X-Api-Key` header (BIT-31442) | Carries either the resolve/reporting key or `DEBUG_VIEW_ERRORS_KEY`; alternative to the query params to avoid key leakage in URLs/logs |
| Admin session | Not used on this path; query/header credentials only |
At least one of the server secrets above must be configured or the endpoint returns **503**.
@@ -11,6 +11,8 @@ Env vars lidos (ver /etc/paperclip/paperclip-fleet-error-audit.env):
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_MAX_AGE_HOURS_OVERRIDES — CSV "slug=horas" por slug (opcional,
sobrepõe o limiar global para esse slug)
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
@@ -27,6 +29,7 @@ from __future__ import annotations
import json
import os
import re
import subprocess
import sys
from collections import defaultdict
@@ -36,6 +39,12 @@ from typing import Any
from urllib import request as urllib_request
from urllib.error import HTTPError, URLError
# Marker convention used for one-off pipe-liveness verification events (e.g. sent by
# hand while investigating a "stale" finding, per BIT-30273/BIT-30527). These are real
# hub rows but not production traffic — counting them as "fresh" masks genuine staleness
# for as long as they remain the newest row for a slug. Excluded from freshness scoring.
_SYNTHETIC_EVENT_RE = re.compile(r"^\[BIT-\d+\]\s+\S+.*smoke test", re.IGNORECASE)
# ---------------------------------------------------------------------------
# Env helpers
# ---------------------------------------------------------------------------
@@ -126,7 +135,7 @@ def _patch_json(url: str, payload: dict[str, Any], headers: dict[str, str] | Non
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}&order=occurred_at_desc&api_key={api_key}"
f"?limit={limit}&order=occurred_at_desc&status=open,investigating,resolved,ignored&api_key={api_key}"
)
# Use curl to avoid Cloudflare bot challenges on urllib
result = subprocess.run(
@@ -144,21 +153,45 @@ def fetch_hub_rows(hub_base: str, api_key: str, limit: int) -> list[dict[str, An
return data.get("data", [])
def _parse_max_age_overrides(raw: str) -> dict[str, int]:
overrides: dict[str, int] = {}
for part in raw.split(","):
part = part.strip()
if not part or "=" not in part:
continue
slug, _, hours_raw = part.partition("=")
slug = slug.strip().lower()
try:
hours = int(hours_raw.strip())
except ValueError:
continue
if slug:
overrides[slug] = hours
return overrides
def analyse_rows(
rows: list[dict[str, Any]],
expected_slugs: list[str],
max_age_hours: int,
min_rows: int,
max_age_overrides: dict[str, int] | None = None,
) -> dict[str, Any]:
max_age_overrides = max_age_overrides or {}
now = datetime.now(timezone.utc)
# Aggregate per slug
by_slug: dict[str, list[datetime]] = defaultdict(list)
synthetic_skipped: dict[str, int] = defaultdict(int)
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
message = str(row.get("message") or row.get("error_message") or "")
if _SYNTHETIC_EVENT_RE.match(message.strip()):
synthetic_skipped[slug] += 1
continue
try:
dt = datetime.fromisoformat(str(occurred_at_raw).replace("Z", "+00:00"))
by_slug[slug].append(dt)
@@ -171,6 +204,7 @@ def analyse_rows(
results: list[dict[str, Any]] = []
for slug in expected_slugs:
times = by_slug.get(slug, [])
slug_max_age = max_age_overrides.get(slug, max_age_hours)
if not times:
status = "silent"
hours_since = None
@@ -178,7 +212,7 @@ def analyse_rows(
else:
latest = max(times)
hours_since = (now - latest).total_seconds() / 3600
status = "stale" if hours_since > max_age_hours else "ok"
status = "stale" if hours_since > slug_max_age else "ok"
results.append(
{
@@ -187,6 +221,8 @@ def analyse_rows(
"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,
"max_age_hours": slug_max_age,
"synthetic_events_excluded": synthetic_skipped.get(slug, 0),
}
)
@@ -283,6 +319,7 @@ def main() -> int:
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)
max_age_overrides = _parse_max_age_overrides(_env("PAPERCLIP_FLEET_AUDIT_MAX_AGE_HOURS_OVERRIDES", ""))
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")
@@ -308,6 +345,8 @@ def main() -> int:
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}")
if max_age_overrides:
print(f"Max age overrides: {max_age_overrides}")
# Fetch hub data
try:
@@ -319,7 +358,7 @@ def main() -> int:
print(f"Fetched {len(rows)} rows from hub")
# Analyse
report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows)
report = analyse_rows(rows, expected_slugs, max_age_hours, min_rows, max_age_overrides)
print(json.dumps(report, indent=2, default=str))
# Determine problems
@@ -352,10 +391,11 @@ def main() -> int:
else:
hours = p["hours_since_last_event"]
latest = p["latest_occurred_at"]
slug_max_age = p["max_age_hours"]
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"(limiar: {slug_max_age}h).\n\n"
f"Último evento: `{latest}`\n"
f"Hub: `{hub_base}`\n"
f"Auditoria: {report['audited_at']}"
@@ -396,7 +436,7 @@ def main() -> int:
elif st == "stale":
hours = r["hours_since_last_event"]
icon = "⚠️"
detail = f"stale — último evento há {hours:.1f}h (limiar: {max_age_hours}h)"
detail = f"stale — último evento há {hours:.1f}h (limiar: {r['max_age_hours']}h)"
else:
icon = "🔴"
detail = "silencioso — sem eventos"