From ba7a971bc1c23b812b74d0a5d2653e100fd99ca1 Mon Sep 17 00:00:00 2001 From: David Santos Date: Mon, 6 Apr 2026 21:59:01 +0000 Subject: [PATCH 1/5] feat(clients): support project_slug and gitea_repo routing metadata Extend official Node/PHP reporter clients to attach optional project routing metadata (`project_name`, `project_slug`, `gitea_repo`) via env/options so product repos can emit deterministic ERRSIG routing context at source. --- clients/node/errorReporter.cjs | 15 ++++++++++++++- clients/node/errorReporter.mjs | 18 ++++++++++++++++-- clients/php/ErrorReporter.php | 19 +++++++++++++++++++ 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/clients/node/errorReporter.cjs b/clients/node/errorReporter.cjs index a745812..ddc5c2b 100644 --- a/clients/node/errorReporter.cjs +++ b/clients/node/errorReporter.cjs @@ -7,6 +7,9 @@ let _token = ''; let _endpoint = 'https://errors.bitreport.pt'; let _disabled = false; +let _projectName = process.env.ERROR_REPORTING_PROJECT_NAME || ''; +let _projectSlug = process.env.ERROR_REPORTING_PROJECT_SLUG || ''; +let _giteaRepo = process.env.ERROR_REPORTING_GITEA_REPO || ''; const _queue = []; let _flushTimer = null; const BATCH_SIZE = 25; @@ -18,6 +21,9 @@ function initReporter(opts) { _token = opts.token || process.env.ERROR_REPORTING_TOKEN || ''; _endpoint = (opts.endpoint || process.env.ERROR_REPORTING_ENDPOINT || 'https://errors.bitreport.pt').replace(/\/$/, ''); _disabled = opts.disabled != null ? opts.disabled : process.env.ERROR_REPORTING_DISABLED === '1'; + _projectName = opts.projectName || process.env.ERROR_REPORTING_PROJECT_NAME || _projectName; + _projectSlug = opts.projectSlug || process.env.ERROR_REPORTING_PROJECT_SLUG || _projectSlug; + _giteaRepo = opts.giteaRepo || process.env.ERROR_REPORTING_GITEA_REPO || _giteaRepo; if (!_disabled && _token) { process.on('uncaughtException', function (err) { @@ -51,6 +57,9 @@ function reportError(err, context) { line_number: lineNumber || undefined, error_type: (err && err.constructor && err.constructor.name) || 'Error', error_code: (err && err.code) || undefined, + project_name: _projectName || undefined, + project_slug: _projectSlug || undefined, + gitea_repo: _giteaRepo || undefined, }, context), }); } @@ -62,7 +71,11 @@ function reportMessage(message, level, context) { occurred_at: new Date().toISOString(), level: level || 'error', message: message, - context: context || {}, + context: Object.assign({ + project_name: _projectName || undefined, + project_slug: _projectSlug || undefined, + gitea_repo: _giteaRepo || undefined, + }, context || {}), }); } diff --git a/clients/node/errorReporter.mjs b/clients/node/errorReporter.mjs index 3887012..bea54a4 100644 --- a/clients/node/errorReporter.mjs +++ b/clients/node/errorReporter.mjs @@ -17,6 +17,9 @@ let _token = ''; let _endpoint = 'https://errors.bitreport.pt'; let _disabled = false; +let _projectName = process.env.ERROR_REPORTING_PROJECT_NAME || ''; +let _projectSlug = process.env.ERROR_REPORTING_PROJECT_SLUG || ''; +let _giteaRepo = process.env.ERROR_REPORTING_GITEA_REPO || ''; const _queue = []; let _flushTimer = null; const BATCH_SIZE = 25; @@ -25,12 +28,15 @@ const TIMEOUT_MS = 8000; /** * Initialise the reporter. Call once at startup. - * @param {{ token?: string, endpoint?: string, disabled?: boolean }} opts + * @param {{ token?: string, endpoint?: string, disabled?: boolean, projectName?: string, projectSlug?: string, giteaRepo?: string }} opts */ export function initReporter(opts = {}) { _token = opts.token || process.env.ERROR_REPORTING_TOKEN || ''; _endpoint = (opts.endpoint || process.env.ERROR_REPORTING_ENDPOINT || 'https://errors.bitreport.pt').replace(/\/$/, ''); _disabled = opts.disabled ?? process.env.ERROR_REPORTING_DISABLED === '1'; + _projectName = opts.projectName || process.env.ERROR_REPORTING_PROJECT_NAME || _projectName; + _projectSlug = opts.projectSlug || process.env.ERROR_REPORTING_PROJECT_SLUG || _projectSlug; + _giteaRepo = opts.giteaRepo || process.env.ERROR_REPORTING_GITEA_REPO || _giteaRepo; if (!_disabled && _token) { process.on('uncaughtException', (err) => { @@ -69,6 +75,9 @@ export function reportError(err, context = {}) { line_number: lineNumber || undefined, error_type: err?.constructor?.name || 'Error', error_code: err?.code || undefined, + project_name: _projectName || undefined, + project_slug: _projectSlug || undefined, + gitea_repo: _giteaRepo || undefined, ...context, }, }); @@ -87,7 +96,12 @@ export function reportMessage(message, level = 'error', context = {}) { occurred_at: new Date().toISOString(), level, message, - context, + context: { + project_name: _projectName || undefined, + project_slug: _projectSlug || undefined, + gitea_repo: _giteaRepo || undefined, + ...context, + }, }); } diff --git a/clients/php/ErrorReporter.php b/clients/php/ErrorReporter.php index 4ebef56..d1e4099 100644 --- a/clients/php/ErrorReporter.php +++ b/clients/php/ErrorReporter.php @@ -44,6 +44,22 @@ final class ErrorReporter return self::env('ERROR_REPORTING_TOKEN'); } + + private static function projectName(): string + { + return self::env('ERROR_REPORTING_PROJECT_NAME'); + } + + private static function projectSlug(): string + { + return self::env('ERROR_REPORTING_PROJECT_SLUG'); + } + + private static function giteaRepo(): string + { + return self::env('ERROR_REPORTING_GITEA_REPO'); + } + private static function env(string $key): string { $v = getenv($key); @@ -130,6 +146,9 @@ final class ErrorReporter 'request_uri' => $_SERVER['REQUEST_URI'] ?? null, 'http_method' => $_SERVER['REQUEST_METHOD'] ?? null, 'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null, + 'project_name' => self::projectName() !== '' ? self::projectName() : null, + 'project_slug' => self::projectSlug() !== '' ? self::projectSlug() : null, + 'gitea_repo' => self::giteaRepo() !== '' ? self::giteaRepo() : null, ], $context); // Remove null values From a51b3e987a40110e069038815137b6b111f99d11 Mon Sep 17 00:00:00 2001 From: Peter Spark Date: Tue, 7 Apr 2026 02:10:11 +0000 Subject: [PATCH 2/5] feat(clients): optional project_slug and gitea_repo on ingest context PHP + Node reporters read ERROR_REPORTING_* env; ingest-api tests run contract on clients/. Paperclip-Agent: 11179220-3cec-4f0f-880d-2771ff64fce8 Paperclip-Issue: BIT-1310 Paperclip-Run: 35ce1c21-9862-4c60-8b58-441d53b4b3bd --- clients/node/errorReporter.mjs | 3 + clients/php/ErrorReporter.php | 2 + ingest-api/package.json | 2 +- .../check_error_reporter_context_contract.py | 126 ++++++++++++++++++ 4 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 tools/ci/check_error_reporter_context_contract.py diff --git a/clients/node/errorReporter.mjs b/clients/node/errorReporter.mjs index bea54a4..873c16f 100644 --- a/clients/node/errorReporter.mjs +++ b/clients/node/errorReporter.mjs @@ -12,6 +12,9 @@ * ERROR_REPORTING_TOKEN — ingest API key (Bearer token) * ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt) * ERROR_REPORTING_DISABLED — set to "1" to disable + * ERROR_REPORTING_PROJECT_NAME — display name in ingest context (optional) + * ERROR_REPORTING_PROJECT_SLUG — stable product slug (optional) + * ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea (optional) */ let _token = ''; diff --git a/clients/php/ErrorReporter.php b/clients/php/ErrorReporter.php index d1e4099..db6521d 100644 --- a/clients/php/ErrorReporter.php +++ b/clients/php/ErrorReporter.php @@ -14,6 +14,8 @@ declare(strict_types=1); * ERROR_REPORTING_TOKEN — ingest API key (required) * ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt) * ERROR_REPORTING_DISABLED — set to "1" to disable + * ERROR_REPORTING_PROJECT_SLUG — stable product slug for ERRSIG / Paperclip routing (optional) + * ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea, e.g. BitReport.pt/my-product (optional) */ namespace BitReport; diff --git a/ingest-api/package.json b/ingest-api/package.json index c3af015..bff0719 100644 --- a/ingest-api/package.json +++ b/ingest-api/package.json @@ -9,7 +9,7 @@ "build": "tsc", "start": "node dist/server.js", "typecheck": "tsc --noEmit", - "test": "vitest run", + "test": "vitest run && python3 ../tools/ci/check_error_reporter_context_contract.py --path ../clients", "test:watch": "vitest" }, "dependencies": { diff --git a/tools/ci/check_error_reporter_context_contract.py b/tools/ci/check_error_reporter_context_contract.py new file mode 100644 index 0000000..57c0291 --- /dev/null +++ b/tools/ci/check_error_reporter_context_contract.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""CI gate: shipped ingest clients must document project_slug + gitea_repo routing.""" +from __future__ import annotations + +import argparse +import fnmatch +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] + +SCAN_EXTENSIONS = {".php", ".js", ".mjs", ".cjs", ".ts", ".py"} +EXCLUDE_PATTERNS = ( + ".git/*", + "node_modules/*", + "vendor/*", + ".venv/*", + "venv/*", + "__pycache__/*", + "dist/*", + "build/*", +) + +REPORTER_MARKERS = ( + "php-error", + "js-error", + "error-monitoring", + "reporterror(", + "reportmessage(", + "sendtoingestapi", + "/v1/ingest/events", +) + +SLUG_MARKERS = ( + "project_slug", + "projectslug", + "error_monitoring_project_slug", + "error_reporting_project_slug", +) + +REPO_MARKERS = ( + "gitea_repo", + "gitearepo", + "error_monitoring_gitea_repo", + "error_reporting_gitea_repo", +) + + +def _is_excluded(rel_path: str) -> bool: + norm = rel_path.replace("\\", "/") + if "/node_modules/" in norm or norm.startswith("node_modules/"): + return True + if "/vendor/" in norm or norm.startswith("vendor/"): + return True + return any(fnmatch.fnmatch(rel_path, pattern) for pattern in EXCLUDE_PATTERNS) + + +def _is_candidate_file(rel_path: str, text_lower: str) -> bool: + if _is_excluded(rel_path): + return False + if Path(rel_path).suffix.lower() not in SCAN_EXTENSIONS: + return False + name = Path(rel_path).name.lower() + has_reporter_naming = ( + "reporter" in name + or "errorreporter" in text_lower + or "errormonitoringreporter" in text_lower + ) + if not has_reporter_naming: + return False + return any(marker in text_lower for marker in REPORTER_MARKERS) + + +def _contract_ok(text_lower: str) -> tuple[bool, bool]: + has_slug = any(marker in text_lower for marker in SLUG_MARKERS) + has_repo = any(marker in text_lower for marker in REPO_MARKERS) + return has_slug, has_repo + + +def main() -> int: + parser = argparse.ArgumentParser(description="Verify error reporter context contract in repository files.") + parser.add_argument( + "--path", + default=str(REPO_ROOT), + help="Repository root to scan.", + ) + args = parser.parse_args() + + root = Path(args.path).resolve() + if not root.is_dir(): + print(f"error: scan root does not exist: {root}") + return 2 + + failures: list[tuple[str, bool, bool]] = [] + candidates = 0 + + for file_path in root.rglob("*"): + if not file_path.is_file(): + continue + rel = file_path.relative_to(root).as_posix() + if _is_excluded(rel): + continue + try: + content = file_path.read_text(encoding="utf-8", errors="ignore") + except OSError: + continue + low = content.lower() + if not _is_candidate_file(rel, low): + continue + candidates += 1 + has_slug, has_repo = _contract_ok(low) + if not (has_slug and has_repo): + failures.append((rel, has_slug, has_repo)) + + print(f"reporter_contract_candidates={candidates}") + if not failures: + print("reporter_context_contract=ok") + return 0 + + print("reporter_context_contract=failed") + for rel, has_slug, has_repo in failures: + print(f"- {rel}: has_project_slug={int(has_slug)} has_gitea_repo={int(has_repo)}") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) From f8c401a990efa9df2e5d47fa0cc874a67d29bbff Mon Sep 17 00:00:00 2001 From: David Santos Date: Tue, 7 Apr 2026 23:21:18 +0000 Subject: [PATCH 3/5] feat(admin-ui): add POST /api/error-monitoring/php-error bridge (BIT-1541) Translates CRM-shaped ErrorMonitoringReporter payloads (project_slug, gitea_repo at top level) to ingest-api /v1/ingest/events format. Both routing fields are promoted into the event context so they are persisted in context_json and surfaced by GET /api/error-monitoring/recent-errors, unblocking ERRSIG routing validation for CasamentoWeb. Auth: X-Error-Monitoring-Key is forwarded as Bearer to the ingest-api; the key must be registered in er_ingest_keys for the target project. Paperclip-Issue: BIT-1541 Co-Authored-By: Paperclip --- .../api/error-monitoring/php-error/route.ts | 165 ++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 admin-ui/app/api/error-monitoring/php-error/route.ts diff --git a/admin-ui/app/api/error-monitoring/php-error/route.ts b/admin-ui/app/api/error-monitoring/php-error/route.ts new file mode 100644 index 0000000..7a46601 --- /dev/null +++ b/admin-ui/app/api/error-monitoring/php-error/route.ts @@ -0,0 +1,165 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; + +export const dynamic = "force-dynamic"; + +/** + * CRM-shaped PHP error ingest bridge. + * + * Receives the legacy `X-Error-Monitoring-Key` + flat JSON payload sent by + * ErrorMonitoringReporter (CasamentoWeb, CRM, etc.) and translates it to the + * ingest-api `/v1/ingest/events` schema, ensuring `gitea_repo` and + * `project_slug` are promoted into the event `context` so they are persisted + * in `context_json` and returned by `GET /api/error-monitoring/recent-errors`. + * + * Auth: the `X-Error-Monitoring-Key` value is forwarded as `Authorization: + * Bearer` to the ingest-api — the key must exist in `er_ingest_keys`. + */ + +interface CrmPhpPayload { + message?: unknown; + severity?: unknown; + level?: unknown; + stack_trace?: unknown; + stacktrace?: unknown; + file_path?: unknown; + line_number?: unknown; + error_type?: unknown; + environment?: unknown; + url?: unknown; + http_method?: unknown; + ip_address?: unknown; + user_agent?: unknown; + context_data?: unknown; + // routing metadata (hub-mirrored fields) + project_slug?: unknown; + project_name?: unknown; + gitea_repo?: unknown; +} + +function safeStr(v: unknown): string { + return typeof v === "string" ? v : ""; +} + +export async function POST(request: NextRequest) { + const ingestApiUrl = (process.env.INGEST_API_URL ?? "http://127.0.0.1:3041").replace(/\/$/, ""); + + // Extract auth key — forwarded as Bearer to ingest-api. + const monitoringKey = + request.headers.get("x-error-monitoring-key")?.trim() ?? + request.headers.get("x-api-key")?.trim() ?? + ""; + + if (!monitoringKey) { + return NextResponse.json( + { success: false, message: "Missing X-Error-Monitoring-Key header." }, + { status: 401 }, + ); + } + + let body: CrmPhpPayload; + try { + body = (await request.json()) as CrmPhpPayload; + } catch { + return NextResponse.json( + { success: false, message: "Invalid JSON body." }, + { status: 400 }, + ); + } + + const message = safeStr(body.message); + if (!message) { + return NextResponse.json( + { success: false, message: "Missing required field: message." }, + { status: 400 }, + ); + } + + // Normalise severity → ingest level. + const level = safeStr(body.severity || body.level) || "error"; + + // Stack trace (CRM uses snake_case `stack_trace`). + const stackTrace = safeStr(body.stack_trace || body.stacktrace); + + // Build context: start with context_data, then promote top-level routing + // fields so they land in context_json and are readable by recent-errors. + const contextData: Record = + body.context_data !== null && + typeof body.context_data === "object" && + !Array.isArray(body.context_data) + ? { ...(body.context_data as Record) } + : {}; + + // Routing metadata — always overwrite so reporter values win. + const gitea_repo = safeStr(body.gitea_repo); + const project_slug = safeStr(body.project_slug); + const project_name = safeStr(body.project_name); + if (gitea_repo) contextData.gitea_repo = gitea_repo; + if (project_slug) contextData.project_slug = project_slug; + if (project_name) contextData.project_name = project_name; + + // Preserve other top-level diagnostic fields. + const file_path = safeStr(body.file_path); + const line_number = safeStr(body.line_number); + const error_type = safeStr(body.error_type); + if (file_path) contextData.file_path = file_path; + if (line_number) contextData.line_number = line_number; + if (error_type) contextData.error_type = error_type; + const httpUrl = safeStr(body.url); + if (httpUrl) contextData.url = httpUrl; + const httpMethod = safeStr(body.http_method); + if (httpMethod) contextData.http_method = httpMethod; + const ipAddress = safeStr(body.ip_address); + if (ipAddress) contextData.ip_address = ipAddress; + const userAgent = safeStr(body.user_agent); + if (userAgent) contextData.user_agent = userAgent; + + const event = { + schema_version: 1, + occurred_at: new Date().toISOString(), + level, + message, + ...(stackTrace ? { stack_trace: stackTrace } : {}), + ...(Object.keys(contextData).length > 0 ? { context: contextData } : {}), + }; + + const ingestTarget = `${ingestApiUrl}/v1/ingest/events`; + const ingestBody = JSON.stringify({ events: [event] }); + + let upstream: Response; + try { + upstream = await fetch(ingestTarget, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${monitoringKey}`, + }, + body: ingestBody, + cache: "no-store", + }); + } catch (err) { + const msg = err instanceof Error ? err.message : "ingest_unreachable"; + return NextResponse.json( + { success: false, message: `Ingest API unreachable: ${msg}` }, + { status: 502 }, + ); + } + + if (upstream.status === 401) { + return NextResponse.json( + { success: false, message: "Ingest key not recognised." }, + { status: 401 }, + ); + } + + if (!upstream.ok) { + const errText = await upstream.text().catch(() => ""); + return NextResponse.json( + { success: false, message: `Ingest failed (${upstream.status}): ${errText}` }, + { status: upstream.status >= 500 ? 502 : upstream.status }, + ); + } + + return NextResponse.json({ success: true, message: "ok" }); +} From 17781da9ec2c5bf61b47cad45fd16d5796a10aca Mon Sep 17 00:00:00 2001 From: David Santos Date: Wed, 8 Apr 2026 00:48:41 +0000 Subject: [PATCH 4/5] feat(api): expose gitea_repo on recent-errors rows (BIT-1291) Extract gitea_repo from context_json and include it as a top-level field on each row returned by GET /api/error-monitoring/recent-errors. Supports gitea_repo, giteaRepo, repo_full_name, and repository keys. Added unit tests covering the include and omit cases. Paperclip-Issue: BIT-1291 Co-Authored-By: Paperclip --- api/src/routes/public/recentErrors.test.ts | 87 ++++++++++++++++++++++ api/src/routes/public/recentErrors.ts | 16 +++- 2 files changed, 102 insertions(+), 1 deletion(-) create mode 100644 api/src/routes/public/recentErrors.test.ts diff --git a/api/src/routes/public/recentErrors.test.ts b/api/src/routes/public/recentErrors.test.ts new file mode 100644 index 0000000..28cf109 --- /dev/null +++ b/api/src/routes/public/recentErrors.test.ts @@ -0,0 +1,87 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import Fastify, { type FastifyInstance } from 'fastify'; +import type { RowDataPacket } from 'mysql2'; +import recentErrorsPublicRoutes from './recentErrors.js'; + +describe('GET /api/error-monitoring/recent-errors', () => { + const prevResolve = process.env.ERROR_RESOLVE_API_KEY; + + beforeEach(() => { + process.env.ERROR_RESOLVE_API_KEY = 'test-recent-errors-key'; + }); + + afterEach(() => { + if (prevResolve === undefined) { + delete process.env.ERROR_RESOLVE_API_KEY; + } else { + process.env.ERROR_RESOLVE_API_KEY = prevResolve; + } + }); + + async function buildApp(execute: ReturnType): Promise { + const app = Fastify({ logger: false }); + app.decorate('db', { execute } as unknown as FastifyInstance['db']); + await app.register(recentErrorsPublicRoutes); + return app; + } + + it('includes top-level gitea_repo when stored in context_json', async () => { + const execute = vi.fn().mockResolvedValue([ + [ + { + incident_id: '1', + occurrence_id: '99', + project_slug: 'wdmi-store', + incident_severity: 'high', + incident_state: 'open', + message: 'probe', + stack_trace: '', + context_json: JSON.stringify({ + gitea_repo: 'BitReport.pt/WDMI_STORE', + file_path: '/src/x.ts', + line_number: 3, + }), + environment: 'production', + occurred_at: '2026-01-01T00:00:00.000Z', + } as RowDataPacket, + ], + ]); + const app = await buildApp(execute); + const res = await app.inject({ + method: 'GET', + url: '/api/error-monitoring/recent-errors?api_key=test-recent-errors-key', + }); + expect(res.statusCode).toBe(200); + const body = res.json() as { data: Array<{ gitea_repo?: string; file_path?: string }> }; + expect(body.data).toHaveLength(1); + expect(body.data[0].gitea_repo).toBe('BitReport.pt/WDMI_STORE'); + expect(body.data[0].file_path).toBe('/src/x.ts'); + }); + + it('omits gitea_repo when not present in context', async () => { + const execute = vi.fn().mockResolvedValue([ + [ + { + incident_id: '1', + occurrence_id: '99', + project_slug: 'other', + incident_severity: 'medium', + incident_state: 'open', + message: 'x', + stack_trace: '', + context_json: JSON.stringify({ file_path: '/b.php' }), + environment: 'production', + occurred_at: '2026-01-01T00:00:00.000Z', + } as RowDataPacket, + ], + ]); + const app = await buildApp(execute); + const res = await app.inject({ + method: 'GET', + url: '/api/error-monitoring/recent-errors?api_key=test-recent-errors-key', + }); + expect(res.statusCode).toBe(200); + const body = res.json() as { data: Array<{ gitea_repo?: string }> }; + expect(body.data[0].gitea_repo).toBeUndefined(); + }); +}); diff --git a/api/src/routes/public/recentErrors.ts b/api/src/routes/public/recentErrors.ts index d9be4b3..0351447 100644 --- a/api/src/routes/public/recentErrors.ts +++ b/api/src/routes/public/recentErrors.ts @@ -65,6 +65,15 @@ function extractFileLine(ctx: Record | null): { file_path: stri return { file_path, line_number }; } +/** Paperclip error loop reads top-level `gitea_repo` on each recent-error row. */ +function extractGiteaRepo(ctx: Record | null): string { + if (!ctx) { + return ''; + } + const raw = ctx.gitea_repo ?? ctx.giteaRepo ?? ctx.repo_full_name ?? ctx.repository; + return typeof raw === 'string' ? raw.trim() : ''; +} + function parseStatusList(raw: string | undefined): string[] | null { if (raw == null || raw.trim() === '') { return ['open', 'investigating']; @@ -201,6 +210,7 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply): const data = (rows as Record[]).map((row) => { const ctx = parseJsonObject(row.context_json != null ? String(row.context_json) : null); const { file_path, line_number } = extractFileLine(ctx); + const gitea_repo = extractGiteaRepo(ctx); const incSev = String(row.incident_severity ?? 'medium').toLowerCase(); const sev = ['critical', 'high', 'medium', 'low'].includes(incSev) ? incSev : 'medium'; const st = String(row.incident_state ?? 'open').toLowerCase(); @@ -212,7 +222,7 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply): const stack_trace = rawStack !== '' ? rawStack : synthesizeStackTraceForDisplay(message, ctx); - return { + const rowOut: Record = { status: st === 'resolved' ? 'resolved' : st === 'ignored' ? 'ignored' : 'open', message, error_message: message, @@ -225,6 +235,10 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply): environment: String(row.environment ?? 'production'), occurred_at: toIsoOccurredAt(row.occurred_at), }; + if (gitea_repo !== '') { + rowOut.gitea_repo = gitea_repo; + } + return rowOut; }); return void reply.send({ From ab992382bc08e8dcc4b3f262ef752affc0356031 Mon Sep 17 00:00:00 2001 From: David Santos Date: Wed, 8 Apr 2026 00:56:12 +0000 Subject: [PATCH 5/5] fix(deploy): restart Fastify API on webhook promote + git safe.directory BIT-1599 follow-up: recent-errors changes live in api/; restart bitreport-error-reporting-api.service alongside other units. Register ER_REPO_ROOT as a safe directory when root runs git against a tree owned by error-reporting (avoids dubious ownership failure on write-version-json / verify). Paperclip: BIT-1599 Made-with: Cursor --- deploy/lxc/webhook-deploy.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/deploy/lxc/webhook-deploy.sh b/deploy/lxc/webhook-deploy.sh index 71ca73b..17e17cf 100755 --- a/deploy/lxc/webhook-deploy.sh +++ b/deploy/lxc/webhook-deploy.sh @@ -17,6 +17,9 @@ set +a _ROOT="${ER_REPO_ROOT:?ER_REPO_ROOT must be set in ${_ENV_FILE}}" cd "${_ROOT}" +# Avoid `fatal: detected dubious ownership` when root runs git on a tree owned by error-reporting. +git config --global --add safe.directory "${_ROOT}" 2>/dev/null || true + # Match your deploy branch (repository uses master today). _DEPLOY_BRANCH="${ER_DEPLOY_BRANCH:-master}" git fetch origin "${_DEPLOY_BRANCH}" @@ -40,6 +43,7 @@ if [[ "${ER_WEBHOOK_RESTART_SERVICES:-1}" == "1" ]]; then systemctl restart bitreport-error-reporting-ingest-api.service systemctl restart bitreport-error-reporting-admin-ui.service systemctl restart bitreport-error-reporting-collector-worker.service + systemctl restart bitreport-error-reporting-api.service fi echo "webhook-deploy: done"