Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
chore: audit-logs tools chat (#2156)
Maximilian Kaske7356c787478c
diff --git a/CLAUDE.md b/CLAUDE.mdindex 44b6b35f9..b35fd27c5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -105,6 +105,17 @@ pnpm test- **Code Generation:** The project uses `drizzle-kit` for database schema migrations.- **API:** The backend API is built using Hono and tRPC. The API is documented using OpenAPI.+## Comment Discipline++Default to writing no comments. The code and identifiers should explain *what* — the reader can see that. Only write a comment when the *why* would not be obvious from reading the code: a non-obvious invariant, a workaround for a specific bug, a runtime guarantee that justifies a cast, a constraint imposed from outside this file.++- **Keep them to 1 short line where possible**, 3 lines max. Never write multi-paragraph JSDoc blocks.+- **Strip these every time:** restating what the code does, naming the caller / surface that uses the helper, history ("added for X", "used by the Y flow"), and PR/task context. That belongs in commit messages, not source.+- **Keep these:** the WHY behind a non-obvious choice, an invariant that callers must uphold, a `// safe because …` line above an unavoidable cast, a `// workaround: <bug>` for a known issue.+- **JSDoc:** allowed on exported symbols when the type signature alone is ambiguous — but one sentence, not a tutorial. Don't enumerate every branch of a function in prose.++If you find yourself writing a comment that explains *what just changed* or *what you did*, delete it.+## Type Cast Discipline`as unknown as X`, `as never`, and `as any` are sometimes unavoidable — usually at boundaries with external SDKs (AI SDK, third-party libs) or at registry-style dispatch where TypeScript can't link a runtime string to a literal-keyed map. When you need one:diff --git a/apps/dashboard/src/components/chat/tool-renderers/get-audit-log.tsx b/apps/dashboard/src/components/chat/tool-renderers/get-audit-log.tsxnew file mode 100644index 000000000..3239b5a62--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/get-audit-log.tsx@@ -0,0 +1,16 @@+import type { AgentToolOutput } from "@openstatus/services/agent-tools";++import {+ type ChangeRow,+ buildAuditLogChangeRows,+} from "@/components/common/changes-table";++type Output = AgentToolOutput<"get_audit_log">;++export function getAuditLogChanges(output: Output): ChangeRow[] {+ return buildAuditLogChangeRows({+ before: output.before,+ after: output.after,+ changedFields: output.changedFields,+ });+}diff --git a/apps/dashboard/src/components/chat/tool-renderers/index.tsx b/apps/dashboard/src/components/chat/tool-renderers/index.tsxindex 802d9c32d..a4c00303b 100644--- a/apps/dashboard/src/components/chat/tool-renderers/index.tsx+++ b/apps/dashboard/src/components/chat/tool-renderers/index.tsx@@ -14,10 +14,12 @@ import { addStatusReportUpdateChanges } from "./add-status-report-update";import { createMaintenanceChanges } from "./create-maintenance";import { createStatusReportChanges } from "./create-status-report";import { DetailsTable } from "./details-table";+import { getAuditLogChanges } from "./get-audit-log";import { getMonitorDetails } from "./get-monitor";import { getMonitorStatusTable } from "./get-monitor-status";import { getMonitorSummaryDetails } from "./get-monitor-summary";import { getResponseLogDetails } from "./get-response-log";+import { listAuditLogsTable } from "./list-audit-logs";import { listMaintenancesTable } from "./list-maintenances";import { listMonitorsTable } from "./list-monitors";import { listNotificationsTable } from "./list-notifications";@@ -174,6 +176,18 @@ export const toolRenderers: ToolRendererRegistry = {),summary: (o) => (o.id ? `log ${o.id}` : undefined),},+ list_audit_logs: {+ renderResult: ({ output }) => (+ <ResultTable {...listAuditLogsTable(output)} />+ ),+ summary: (o) => itemsCountSummary(o.items),+ },+ get_audit_log: {+ renderResult: ({ output }) => (+ <ChangesTable changes={getAuditLogChanges(output)} />+ ),+ summary: (o) => `${o.action} · #${o.id}`,+ },};function itemsCountSummary(items: unknown[] | undefined): string | undefined {diff --git a/apps/dashboard/src/components/chat/tool-renderers/list-audit-logs.tsx b/apps/dashboard/src/components/chat/tool-renderers/list-audit-logs.tsxnew file mode 100644index 000000000..cf887d20a--- /dev/null+++ b/apps/dashboard/src/components/chat/tool-renderers/list-audit-logs.tsx@@ -0,0 +1,68 @@+import type { AgentToolOutput } from "@openstatus/services/agent-tools";+import { Badge } from "@openstatus/ui/components/ui/badge";++import { TableCellDate } from "@/components/data-table/table-cell-date";+import { TableCellText } from "@/components/data-table/table-cell-text";+import { cn } from "@/lib/utils";++import type { ResultTableData } from "./result-table";++type Output = AgentToolOutput<"list_audit_logs">;++function getActionBadgeColor(action: string) {+ if (action.endsWith(".create"))+ return "bg-success/10 text-success border-success/20";+ if (action.endsWith(".update")) return "bg-info/10 text-info border-info/20";+ if (action.endsWith(".delete"))+ return "bg-destructive/10 text-destructive border-destructive/20";+ return "bg-muted/10 text-muted-foreground border-muted/20";+}++export function listAuditLogsTable(+ output: Output,+): ResultTableData<"action" | "entity" | "actor" | "createdAt"> {+ const items = output.items;+ return {+ empty: "No audit log entries.",+ columns: [+ { key: "action", header: "Action" },+ { key: "entity", header: "Entity" },+ { key: "actor", header: "Actor" },+ { key: "createdAt", header: "Timestamp" },+ ],+ rows: items.map((item) => ({+ id: item.id,+ cells: {+ action: (+ <Badge+ variant="outline"+ className={cn(+ "font-mono text-xs",+ getActionBadgeColor(item.action),+ )}+ >+ {item.action}+ </Badge>+ ),+ entity: (+ <TableCellText+ value={`${item.entityType}#${item.entityId}`}+ className="font-mono text-muted-foreground"+ />+ ),+ actor: (+ <TableCellText+ value={item.actor}+ className="font-mono text-muted-foreground"+ />+ ),+ createdAt: (+ <TableCellDate+ value={new Date(item.createdAt)}+ className="font-mono"+ />+ ),+ },+ })),+ };+}diff --git a/apps/dashboard/src/components/common/changes-table.tsx b/apps/dashboard/src/components/common/changes-table.tsxindex d2223be9c..804366342 100644--- a/apps/dashboard/src/components/common/changes-table.tsx+++ b/apps/dashboard/src/components/common/changes-table.tsx@@ -70,6 +70,47 @@ function DiffLine({);}+const HIDDEN_FIELDS = new Set([+ "workspaceId",+ "createdAt",+ "updatedAt",+ "deletedAt",+]);++/** Update: rows from `changedFields`. Create: keys of `after`. Delete: keys of `before`. */+export function buildAuditLogChangeRows(input: {+ before: Record<string, unknown> | null | undefined;+ after: Record<string, unknown> | null | undefined;+ changedFields: string[] | null | undefined;+}): ChangeRow[] {+ const { before, after, changedFields } = input;++ if (before && after) {+ if (!changedFields?.length) return [];+ return changedFields+ .filter((field) => !HIDDEN_FIELDS.has(field))+ .map((field) => ({+ field,+ before: before[field],+ after: after[field],+ }));+ }++ if (after) {+ return Object.keys(after)+ .filter((field) => !HIDDEN_FIELDS.has(field))+ .map((field) => ({ field, after: after[field] }));+ }++ if (before) {+ return Object.keys(before)+ .filter((field) => !HIDDEN_FIELDS.has(field))+ .map((field) => ({ field, before: before[field] }));+ }++ return [];+}+export function formatValue(value: unknown): string {if (value === null || value === undefined) return "—";if (value instanceof Date) return value.toISOString();diff --git a/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsx b/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsxindex d950afb66..be22dd484 100644--- a/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsx+++ b/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsx@@ -1,86 +1,16 @@"use client";import {- type ChangeRow,ChangesTable,+ buildAuditLogChangeRows,} from "@/components/common/changes-table";import { CopyRow } from "@/components/common/copy-row";import type { RouterOutputs } from "@openstatus/api";type AuditLog = RouterOutputs["auditLog"]["list"]["items"][number];-/**- * Fields we never surface in the CHANGES view.- *- * `createdAt`/`updatedAt`/`deletedAt` are churny bookkeeping — already- * filtered from `changedFields` by `diffTopLevel` in the services- * package, but they still show up on create/delete snapshots.- *- * `workspaceId` is implied by the workspace scope of the audit log- * itself — noise, not signal.- *- * `id` stays visible: with per-entity audit rows, the entity id tells- * the reader *which* component / group / monitor this row refers to.- *- * This is a display-side belt-and-braces only. Proper secret/PII- * redaction (webhook URLs with tokens, hashed api keys, etc.) is the- * server-side redaction PR's job — don't treat this list as a security- * boundary.- */-const HIDDEN_FIELDS = new Set([- "workspaceId",- "createdAt",- "updatedAt",- "deletedAt",-]);--/**- * Build a field-level diff from `before`/`after`/`changedFields`.- *- * - update: both snapshots present → only rows for keys in `changedFields`.- * - create: only `after` present → every top-level key as an addition.- * - delete: only `before` present → every top-level key as a removal.- *- * Returns an empty array when there's nothing structured to show (e.g. a- * metadata-only action emitted without snapshots).- */-function buildChanges(row: AuditLog): ChangeRow[] {- const { before, after, changedFields } = row;-- if (before && after) {- if (!changedFields?.length) return [];- return changedFields- .filter((field) => !HIDDEN_FIELDS.has(field))- .map((field) => ({- field,- before: (before as Record<string, unknown>)[field],- after: (after as Record<string, unknown>)[field],- }));- }-- if (after) {- return Object.keys(after)- .filter((field) => !HIDDEN_FIELDS.has(field))- .map((field) => ({- field,- after: (after as Record<string, unknown>)[field],- }));- }-- if (before) {- return Object.keys(before)- .filter((field) => !HIDDEN_FIELDS.has(field))- .map((field) => ({- field,- before: (before as Record<string, unknown>)[field],- }));- }-- return [];-}-export function DataTableRowDetails({ row }: { row: AuditLog }) {- const changes = buildChanges(row);+ const changes = buildAuditLogChangeRows(row);return (<div className="bg-muted/30 p-4">diff --git a/apps/server/src/routes/mcp/handler.test.ts b/apps/server/src/routes/mcp/handler.test.tsindex c7feabd80..c18505cd8 100644--- a/apps/server/src/routes/mcp/handler.test.ts+++ b/apps/server/src/routes/mcp/handler.test.ts@@ -76,7 +76,7 @@ describe("MCP transport", () => {expect(res.status).toBe(401);});- test("tools/list returns the 15 registered tools", async () => {+ test("tools/list returns the 17 registered tools", async () => {const app = makeApp();const res = await app.fetch(jsonRpc({ method: "tools/list" }));expect(res.status).toBe(200);@@ -87,10 +87,12 @@ describe("MCP transport", () => {"add_status_report_update","create_maintenance","create_status_report",+ "get_audit_log","get_monitor","get_monitor_status","get_monitor_summary","get_response_log",+ "list_audit_logs","list_maintenances","list_monitors","list_notifications",@@ -183,7 +185,7 @@ describe("MCP transport", () => {}[];}).tools;- expect(tools).toHaveLength(15);+ expect(tools).toHaveLength(17);for (const tool of tools) {expect(tool.description?.length ?? 0).toBeGreaterThan(40);expect(tool.inputSchema).toBeDefined();diff --git a/apps/server/src/routes/mcp/server.ts b/apps/server/src/routes/mcp/server.tsindex a0e3634b1..91a873f70 100644--- a/apps/server/src/routes/mcp/server.ts+++ b/apps/server/src/routes/mcp/server.ts@@ -2,6 +2,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import type { ServiceContext } from "@openstatus/services";import packageJson from "../../../package.json" with { type: "json" };+import { registerAuditTools } from "./tools/audit";import { registerMaintenanceTools } from "./tools/maintenance";import { registerMonitorTools } from "./tools/monitor";import { registerNotificationTools } from "./tools/notification";@@ -28,5 +29,6 @@ export function createMcpServer(ctx: ServiceContext): McpServer {registerMaintenanceTools(server, ctx);registerMonitorTools(server, ctx);registerNotificationTools(server, ctx);+ registerAuditTools(server, ctx);return server;}diff --git a/apps/server/src/routes/mcp/tools/audit.ts b/apps/server/src/routes/mcp/tools/audit.tsnew file mode 100644index 000000000..f73160d19--- /dev/null+++ b/apps/server/src/routes/mcp/tools/audit.ts@@ -0,0 +1,25 @@+import type {+ McpServer,+ RegisteredTool,+} from "@modelcontextprotocol/sdk/server/mcp.js";+import type { ServiceContext } from "@openstatus/services";+import {+ getAuditLogTool,+ listAuditLogsTool,+} from "@openstatus/services/agent-tools";++import { registerRegistryTools } from "./registry-adapter";++/** Skip registration when the plan lacks `audit-log` so the tools don't surface in `tools/list`. */+export function registerAuditTools(+ server: McpServer,+ ctx: ServiceContext,+): Map<string, RegisteredTool> {+ if (!ctx.workspace.limits["audit-log"]) {+ return new Map();+ }+ return registerRegistryTools(server, ctx, [+ listAuditLogsTool,+ getAuditLogTool,+ ]);+}diff --git a/packages/api/src/router/auditLog.ts b/packages/api/src/router/auditLog.tsindex d76cfdcf3..c7b9da89b 100644--- a/packages/api/src/router/auditLog.ts+++ b/packages/api/src/router/auditLog.ts@@ -1,4 +1,9 @@-import { ListAuditLogsInput, listAuditLogs } from "@openstatus/services/audit";+import {+ ListAuditLogsInput,+ getAuditLog,+ listAuditLogs,+} from "@openstatus/services/audit";+import { z } from "zod";import { toServiceCtx } from "../service-adapter";import { createTRPCRouter, protectedProcedure } from "../trpc";@@ -9,4 +14,9 @@ export const auditLogRouter = createTRPCRouter({.query(async ({ ctx, input }) =>listAuditLogs({ ctx: toServiceCtx(ctx), input }),),+ get: protectedProcedure+ .input(z.object({ id: z.number().int() }))+ .query(async ({ ctx, input }) =>+ getAuditLog({ ctx: toServiceCtx(ctx), input }),+ ),});diff --git a/packages/services/src/agent-tools/audit.ts b/packages/services/src/agent-tools/audit.tsnew file mode 100644index 000000000..79679ca8a--- /dev/null+++ b/packages/services/src/agent-tools/audit.ts@@ -0,0 +1,174 @@+import { z } from "zod";++import { getAuditLog, listAuditLogs } from "../audit";+import { ForbiddenError } from "../errors";+import type { AgentTool } from "./types";++const PER_PAGE_DEFAULT = 25;+const PER_PAGE_MAX = 50;++function assertAuditLogPlan(workspaceLimits: { "audit-log": boolean }): void {+ if (!workspaceLimits["audit-log"]) {+ throw new ForbiddenError(+ "Audit log is not included in your workspace plan.",+ );+ }+}++function actorDisplay(input: {+ actorType: string;+ actorId: string;+ user: { name: string | null; email: string | null } | null;+}): string {+ return (+ input.user?.name ??+ input.user?.email ??+ `${input.actorType}:${input.actorId}`+ );+}++const ListAuditLogsInputShape = z.object({+ entityType: z+ .string()+ .optional()+ .describe(+ 'Filter to one entity type (e.g. "monitor", "page", "status_report", "notification"). Optional.',+ ),+ entityId: z+ .string()+ .optional()+ .describe(+ "Filter to a single entity id (string form — matches the audit_log column). Requires entityType to be meaningful.",+ ),+ page: z+ .number()+ .int()+ .min(1)+ .default(1)+ .describe("1-indexed page number (default 1)."),+ perPage: z+ .number()+ .int()+ .min(1)+ .max(PER_PAGE_MAX)+ .default(PER_PAGE_DEFAULT)+ .describe(+ `Items per page (default ${PER_PAGE_DEFAULT}, max ${PER_PAGE_MAX}).`,+ ),+});++const ListAuditLogsOutput = z.object({+ items: z.array(+ z.object({+ id: z.number().int(),+ action: z.string(),+ entityType: z.string(),+ entityId: z.string(),+ actor: z.string(),+ createdAt: z.string(),+ }),+ ),+ pagination: z.object({+ page: z.number().int(),+ perPage: z.number().int(),+ totalSize: z.number().int(),+ totalPages: z.number().int(),+ }),+});++export const listAuditLogsTool: AgentTool<+ z.infer<typeof ListAuditLogsInputShape>,+ z.infer<typeof ListAuditLogsOutput>+> = {+ name: "list_audit_logs",+ description:+ "List audit-log entries (mutating actions) for this workspace, newest first. Bounded to the last 14 days. Returns one summary row per entry — call get_audit_log with the numeric audit-log id to see the before/after diff. Optionally filter to a single entity via entityType + entityId. Requires the `audit-log` workspace plan feature.",+ scope: "read",+ destructive: false,+ inputSchema: ListAuditLogsInputShape,+ outputSchema: ListAuditLogsOutput,+ async run({ ctx, input }) {+ assertAuditLogPlan(ctx.workspace.limits);+ const { page, perPage, entityType, entityId } = input;+ const result = await listAuditLogs({+ ctx,+ input: {+ entityType,+ entityId,+ limit: perPage,+ offset: (page - 1) * perPage,+ },+ });+ return {+ items: result.items.map((row) => ({+ id: row.id,+ action: row.action,+ entityType: row.entityType,+ entityId: row.entityId,+ actor: actorDisplay(row),+ createdAt: row.createdAt.toISOString(),+ })),+ pagination: {+ page,+ perPage,+ totalSize: result.totalSize,+ totalPages: Math.max(1, Math.ceil(result.totalSize / perPage)),+ },+ };+ },+};++const GetAuditLogInputShape = z.object({+ id: z+ .number()+ .int()+ .describe(+ "Audit-log entry id (numeric, from `list_audit_logs` items[].id — NOT the entityId of the affected row).",+ ),+});++const snapshotSchema = z.record(z.string(), z.unknown());++const GetAuditLogOutput = z.object({+ id: z.number().int(),+ action: z.string(),+ actorType: z.string(),+ actorId: z.string(),+ entityType: z.string(),+ entityId: z.string(),+ before: snapshotSchema.nullable(),+ after: snapshotSchema.nullable(),+ changedFields: z.array(z.string()).nullable(),+ createdAt: z.string(),+ actor: z.string(),+});++export const getAuditLogTool: AgentTool<+ z.infer<typeof GetAuditLogInputShape>,+ z.infer<typeof GetAuditLogOutput>+> = {+ name: "get_audit_log",+ description:+ "Full detail of a single audit-log entry: before/after snapshots and changedFields for the diff view. Use after list_audit_logs to drill into one entry. Requires the `audit-log` workspace plan feature.",+ scope: "read",+ destructive: false,+ inputSchema: GetAuditLogInputShape,+ outputSchema: GetAuditLogOutput,+ async run({ ctx, input }) {+ assertAuditLogPlan(ctx.workspace.limits);+ const row = await getAuditLog({ ctx, input });+ return {+ id: row.id,+ action: row.action,+ actorType: row.actorType,+ actorId: row.actorId,+ entityType: row.entityType,+ entityId: row.entityId,+ before: row.before ?? null,+ after: row.after ?? null,+ changedFields: row.changedFields ?? null,+ createdAt: row.createdAt.toISOString(),+ actor: actorDisplay(row),+ };+ },+};diff --git a/packages/services/src/agent-tools/index.ts b/packages/services/src/agent-tools/index.tsindex 899f8e77f..e6c6e20ab 100644--- a/packages/services/src/agent-tools/index.ts+++ b/packages/services/src/agent-tools/index.ts@@ -1,5 +1,6 @@import type { z } from "zod";+import { getAuditLogTool, listAuditLogsTool } from "./audit";import { createMaintenanceTool, listMaintenancesTool } from "./maintenance";import {getMonitorStatusTool,@@ -20,6 +21,7 @@ import {} from "./status-report";import type { AnyAgentTool } from "./types";+export { getAuditLogTool, listAuditLogsTool } from "./audit";export {createMaintenanceTool,listMaintenancesTool,@@ -79,6 +81,8 @@ export const agentTools = {list_response_logs: listResponseLogsTool,get_response_log: getResponseLogTool,list_notifications: listNotificationsTool,+ list_audit_logs: listAuditLogsTool,+ get_audit_log: getAuditLogTool,} satisfies Record<string, AnyAgentTool>;/**diff --git a/packages/services/src/agent-tools/prompt.ts b/packages/services/src/agent-tools/prompt.tsindex 5de8a8531..e400e0e11 100644--- a/packages/services/src/agent-tools/prompt.ts+++ b/packages/services/src/agent-tools/prompt.ts@@ -31,8 +31,8 @@ export function buildAgentSystemPrompt(opts: AgentSystemPromptOptions): string {opts.surface === "dashboard"? `\n\nAfter a tool returns, the dashboard already renders a structured view of the result:- Write tools (create_*, update_*, resolve_*, add_*) render a diff card with every input/output field (id, status, message, dates, notify outcome).-- List tools (list_status_pages, list_status_reports, list_maintenances, list_monitors, list_notifications, list_response_logs) render a table with one row per result.-- Detail tools (get_monitor, get_monitor_status, get_monitor_summary, get_response_log) render a structured detail card.+- List tools (list_status_pages, list_status_reports, list_maintenances, list_monitors, list_notifications, list_response_logs, list_audit_logs) render a table with one row per result.+- Detail tools (get_monitor, get_monitor_status, get_monitor_summary, get_response_log, get_audit_log) render a structured detail card.DO NOT restate that data in your reply — no markdown tables, no bullet recaps of the rows, no field-by-field summaries. A one-line acknowledgement ("You have 4 status reports — 3 active." / "Monitor 12 is healthy in 5/7 regions; failing in gru, fra." / "Incident resolved.") plus an optional next step is enough.`: "";diff --git a/packages/services/src/audit/__tests__/audit.test.ts b/packages/services/src/audit/__tests__/audit.test.tsindex 603f0b9bd..e67d18bd9 100644--- a/packages/services/src/audit/__tests__/audit.test.ts+++ b/packages/services/src/audit/__tests__/audit.test.ts@@ -1,9 +1,12 @@import { afterAll, beforeAll, describe, expect, test } from "bun:test";import { db, eq } from "@openstatus/db";-import { auditLog } from "@openstatus/db/src/schema";+import { auditLog, user } from "@openstatus/db/src/schema";import type { AuditEntry } from "@openstatus/db/src/schema";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";+import {+ SEEDED_WORKSPACE_FREE_ID,+ SEEDED_WORKSPACE_TEAM_ID,+} from "../../../test/fixtures";import {clearAuditLog,loadSeededWorkspace,@@ -15,8 +18,10 @@ import {withTestTransaction,} from "../../../test/helpers";import type { ServiceContext } from "../../context";+import { NotFoundError } from "../../errors";import { diffTopLevel, emitAudit } from "../emit";+import { getAuditLog } from "../get";/*** Test-only escape hatch around `emitAudit`'s compile-time snapshot@@ -571,3 +576,106 @@ describe("emitAudit — runtime Zod validation", () => {});});});++describe("getAuditLog", () => {+ test("returns the row when scoped to the same workspace", async () => {+ await withTestTransaction(async (tx) => {+ await emitAudit(tx, teamCtx, {+ action: "monitor.update",+ entityType: "monitor",+ entityId: 9800,+ before: { name: "old" },+ after: { name: "new" },+ });+ const [inserted] = await readAuditLog({+ workspaceId: teamCtx.workspace.id,+ entityType: "monitor",+ entityId: 9800,+ db: tx,+ });+ if (!inserted) throw new Error("unreachable");++ const row = await getAuditLog({+ ctx: { ...teamCtx, db: tx },+ input: { id: inserted.id },+ });+ expect(row.id).toBe(inserted.id);+ expect(row.action).toBe("monitor.update");+ expect(row.entityType).toBe("monitor");+ expect(row.entityId).toBe("9800");+ expect(row.changedFields).toEqual(["name"]);+ expect(row.user?.id).toBe(1);+ });+ });++ test("throws NotFoundError when the id belongs to another workspace", async () => {+ await withTestTransaction(async (tx) => {+ await emitAudit(tx, teamCtx, {+ action: "monitor.create",+ entityType: "monitor",+ entityId: 9801,+ after: { name: "in-team" },+ });+ const [inserted] = await readAuditLog({+ workspaceId: teamCtx.workspace.id,+ entityType: "monitor",+ entityId: 9801,+ db: tx,+ });+ if (!inserted) throw new Error("unreachable");++ const otherWorkspace = await loadSeededWorkspace(+ SEEDED_WORKSPACE_FREE_ID,+ );+ const otherCtx = makeUserCtx(otherWorkspace, { userId: 1 });++ let caught: unknown;+ try {+ await getAuditLog({+ ctx: { ...otherCtx, db: tx },+ input: { id: inserted.id },+ });+ } catch (e) {+ caught = e;+ }+ expect(caught).toBeInstanceOf(NotFoundError);+ });+ });++ test("soft-deleted actor resolves to user: null", async () => {+ await withTestTransaction(async (tx) => {+ const ghostUserId = 9_999_001;+ await tx+ .insert(user)+ .values({+ id: ghostUserId,+ tenantId: `ghost-${ghostUserId}`,+ email: `ghost-${ghostUserId}@example.test`,+ deletedAt: new Date("2025-01-01"),+ })+ .run();++ const ghostCtx = makeUserCtx(teamCtx.workspace, { userId: ghostUserId });+ await emitAudit(tx, ghostCtx, {+ action: "monitor.create",+ entityType: "monitor",+ entityId: 9802,+ after: { name: "by-ghost" },+ });+ const [inserted] = await readAuditLog({+ workspaceId: teamCtx.workspace.id,+ entityType: "monitor",+ entityId: 9802,+ db: tx,+ });+ if (!inserted) throw new Error("unreachable");+ expect(inserted.actorUserId).toBe(ghostUserId);++ const row = await getAuditLog({+ ctx: { ...teamCtx, db: tx },+ input: { id: inserted.id },+ });+ expect(row.user).toBeNull();+ });+ });+});diff --git a/packages/services/src/audit/get.ts b/packages/services/src/audit/get.tsnew file mode 100644index 000000000..e3bdffce0--- /dev/null+++ b/packages/services/src/audit/get.ts@@ -0,0 +1,49 @@+import { and, eq, isNull } from "@openstatus/db";+import {+ auditLog,+ selectAuditLogSchema,+ user,+} from "@openstatus/db/src/schema";++import { type ServiceContext, getReadDb } from "../context";+import { NotFoundError } from "../errors";+import type { AuditLogListItem } from "./list";++/** Soft-deleted actors come back with `user: null` (same join shape as listAuditLogs). */+export async function getAuditLog(args: {+ ctx: ServiceContext;+ input: { id: number };+}): Promise<AuditLogListItem> {+ const { ctx, input } = args;+ const db = getReadDb(ctx);++ const row = await db+ .select({+ auditLog,+ user: {+ id: user.id,+ name: user.name,+ email: user.email,+ photoUrl: user.photoUrl,+ },+ })+ .from(auditLog)+ .leftJoin(+ user,+ and(eq(user.id, auditLog.actorUserId), isNull(user.deletedAt)),+ )+ .where(+ and(+ eq(auditLog.id, input.id),+ eq(auditLog.workspaceId, ctx.workspace.id),+ ),+ )+ .get();++ if (!row) throw new NotFoundError("audit_log", input.id);++ return {+ ...selectAuditLogSchema.parse(row.auditLog),+ user: row.user?.id != null ? row.user : null,+ };+}diff --git a/packages/services/src/audit/index.ts b/packages/services/src/audit/index.tsindex 6a8a69298..de8db0c2d 100644--- a/packages/services/src/audit/index.ts+++ b/packages/services/src/audit/index.ts@@ -7,6 +7,7 @@ export {auditEntrySchema,} from "@openstatus/db/src/schema";export { diffTopLevel, emitAudit } from "./emit";+export { getAuditLog } from "./get";export {type AuditLogListItem,type ListAuditLogsResult,