Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
feat: trace governance reports and hierarchy views (#1526)
Aman Agarwal2d85f5471085
diff --git a/src/client/src/__tests__/app/api/metrics/request/span/governance-route.test.ts b/src/client/src/__tests__/app/api/metrics/request/span/governance-route.test.tsnew file mode 100644index 00000000..7ba40391--- /dev/null+++ b/src/client/src/__tests__/app/api/metrics/request/span/governance-route.test.ts@@ -0,0 +1,216 @@+jest.mock("@/lib/platform/governance/trace-report", () => ({+ buildTraceGovernanceReport: jest.fn(),+}));+jest.mock("@/helpers/server/governance-analytics", () => ({+ fireGovernanceReportTelemetry: jest.fn(),+}));+jest.mock("@/lib/platform/intelligence/source", () => ({+ resolveIntelligenceClickHouseDbConfigId: jest+ .fn()+ .mockResolvedValue("intel-db-1"),+}));+jest.mock("@/lib/rbac/route", () => ({+ withDbConfigAccess: (handler: unknown) => handler,+}));++import { GET } from "@/app/api/metrics/request/span/[id]/governance/route";+import { buildTraceGovernanceReport } from "@/lib/platform/governance/trace-report";+import { fireGovernanceReportTelemetry } from "@/helpers/server/governance-analytics";+import {+ GOVERNANCE_INVALID_SPAN_ID,+ GOVERNANCE_MISSING_SPAN_ID,+} from "@/constants/messages/en";++(globalThis as unknown as { Response: { json: unknown } }).Response = {+ json: (body: unknown, init?: ResponseInit) => ({+ status: init?.status ?? 200,+ json: async () => body,+ }),+};++function makeRequest(+ spanId = "abc123",+ opts?: { traceId?: string; environment?: string; headerEnvironment?: string }+) {+ const params = new URLSearchParams();+ if (opts?.traceId) params.set("traceId", opts.traceId);+ if (opts?.environment) params.set("environment", opts.environment);+ const qs = params.size ? `?${params.toString()}` : "";+ return {+ url: `http://localhost/api/metrics/request/span/${spanId}/governance${qs}`,+ headers: {+ get: (name: string) =>+ name.toLowerCase() === "x-openlit-environment"+ ? opts?.headerEnvironment || null+ : null,+ },+ } as Request;+}++describe("GET /api/metrics/request/span/[id]/governance", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("rejects missing span id", async () => {+ const response = await GET(makeRequest(), { params: {} });+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toBe(GOVERNANCE_MISSING_SPAN_ID);+ expect(buildTraceGovernanceReport).not.toHaveBeenCalled();+ expect(fireGovernanceReportTelemetry).toHaveBeenCalledWith(+ expect.objectContaining({ success: false, reason: "missing_span" })+ );+ });++ it("rejects invalid span id before querying", async () => {+ const response = await GET(makeRequest("bad span"), {+ params: { id: "bad span" },+ });+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toBe(GOVERNANCE_INVALID_SPAN_ID);+ expect(buildTraceGovernanceReport).not.toHaveBeenCalled();+ });++ it("returns governance report and fires success telemetry", async () => {+ (buildTraceGovernanceReport as jest.Mock).mockResolvedValue({+ report: {+ trace_id: "trace-1",+ root_span_id: "span-1",+ risk_level: "minor",+ summary: "ok",+ harness: {+ span_count: 1,+ max_depth: 1,+ llm_call_count: 0,+ tool_call_count: 0,+ retrieval_call_count: 0,+ embedding_call_count: 0,+ database_call_count: 0,+ http_call_count: 0,+ error_count: 0,+ total_cost_usd: 0,+ total_duration_ms: 1,+ models_used: [],+ tools_used: [],+ },+ rules: [],+ security: [],+ evaluations: [],+ finding_count: 0,+ rule_match_count: 0,+ },+ });++ const response = await GET(makeRequest("span-1", { traceId: "trace-1" }), {+ params: { id: "span-1" },+ });+ expect(response.status).toBe(200);+ const body = await response.json();+ expect(body.report.trace_id).toBe("trace-1");+ expect(buildTraceGovernanceReport).toHaveBeenCalledWith(+ "span-1",+ expect.objectContaining({+ traceId: "trace-1",+ databaseConfigId: "intel-db-1",+ })+ );+ expect(fireGovernanceReportTelemetry).toHaveBeenCalledWith(+ expect.objectContaining({+ success: true,+ spanId: "span-1",+ riskLevel: "minor",+ })+ );+ });++ it("scopes the report to the selected connector environment", async () => {+ (buildTraceGovernanceReport as jest.Mock).mockResolvedValue({+ report: {+ trace_id: "trace-1",+ root_span_id: "span-1",+ risk_level: "none",+ summary: "ok",+ harness: {+ span_count: 1,+ max_depth: 1,+ llm_call_count: 0,+ tool_call_count: 0,+ retrieval_call_count: 0,+ embedding_call_count: 0,+ database_call_count: 0,+ http_call_count: 0,+ error_count: 0,+ total_cost_usd: 0,+ total_duration_ms: 1,+ models_used: [],+ tools_used: [],+ },+ rules: [],+ security: [],+ evaluations: [],+ finding_count: 0,+ rule_match_count: 0,+ },+ });++ await GET(+ makeRequest("span-1", {+ traceId: "trace-1",+ environment: "staging",+ }),+ { params: { id: "span-1" } }+ );++ expect(buildTraceGovernanceReport).toHaveBeenCalledWith(+ "span-1",+ expect.objectContaining({+ traceId: "trace-1",+ environment: "staging",+ databaseConfigId: "intel-db-1",+ })+ );+ });++ it("falls back to the x-openlit-environment header for connector scoping", async () => {+ (buildTraceGovernanceReport as jest.Mock).mockResolvedValue({+ report: {+ trace_id: "trace-1",+ root_span_id: "span-1",+ risk_level: "none",+ summary: "ok",+ harness: {+ span_count: 1,+ max_depth: 1,+ llm_call_count: 0,+ tool_call_count: 0,+ retrieval_call_count: 0,+ embedding_call_count: 0,+ database_call_count: 0,+ http_call_count: 0,+ error_count: 0,+ total_cost_usd: 0,+ total_duration_ms: 1,+ models_used: [],+ tools_used: [],+ },+ rules: [],+ security: [],+ evaluations: [],+ finding_count: 0,+ rule_match_count: 0,+ },+ });++ await GET(+ makeRequest("span-1", { headerEnvironment: "production" }),+ { params: { id: "span-1" } }+ );++ expect(buildTraceGovernanceReport).toHaveBeenCalledWith(+ "span-1",+ expect.objectContaining({+ environment: "production",+ })+ );+ });+});diff --git a/src/client/src/__tests__/app/api/route-access-wraps.test.ts b/src/client/src/__tests__/app/api/route-access-wraps.test.tsindex e9214590..875f7532 100644--- a/src/client/src/__tests__/app/api/route-access-wraps.test.ts+++ b/src/client/src/__tests__/app/api/route-access-wraps.test.ts@@ -54,6 +54,17 @@ describe("new implementation route access wraps", () => {}});+ it("wraps governance route with governance access/audit hooks", () => {+ const source = readFileSync(+ join(API_ROOT, "metrics/request/span/[id]/governance/route.ts"),+ "utf8"+ );+ expect(source).toMatch(/withGovernanceAccess/);+ expect(source).toMatch(/withGovernanceAudit/);+ expect(source).toMatch(/withRouteAccess/);+ expect(source).not.toMatch(/"[a-z_]+:[a-z_]+"/);+ });+it("wraps telemetry query routes with withRouteAccess", () => {const roots = ["metrics", "telemetry", "observability"].map((d) =>join(API_ROOT, d)diff --git a/src/client/src/__tests__/lib/access/governance-route.test.ts b/src/client/src/__tests__/lib/access/governance-route.test.tsnew file mode 100644index 00000000..3d2b4994--- /dev/null+++ b/src/client/src/__tests__/lib/access/governance-route.test.ts@@ -0,0 +1,16 @@+import {+ withGovernanceAccess,+ withGovernanceAudit,+} from "@/lib/access/governance-route";++describe("CE governance route fallback", () => {+ it("keeps handlers unchanged", async () => {+ const handler = jest.fn().mockResolvedValue({ status: 200 });+ const wrapped = withGovernanceAudit(withGovernanceAccess("read", handler));++ await wrapped({} as Request);++ expect(handler).toHaveBeenCalledTimes(1);+ expect(wrapped).toBe(handler);+ });+});diff --git a/src/client/src/__tests__/lib/platform/agents/index.test.ts b/src/client/src/__tests__/lib/platform/agents/index.test.tsindex 5ace1ce8..732c4510 100644--- a/src/client/src/__tests__/lib/platform/agents/index.test.ts+++ b/src/client/src/__tests__/lib/platform/agents/index.test.ts@@ -2,11 +2,17 @@* Unified agent listing query + computeAgentKey helper.*/+jest.mock("@/lib/db-config", () => ({+ getDBConfigByIdForBackground: jest.fn(),+ getDBConfigByIdInternal: jest.fn(),+ getDBConfigByUser: jest.fn(),+}));jest.mock("@/lib/platform/common", () => {const collector = jest.fn();return {dataCollector: collector,intelligenceDataCollector: collector,+ connectorDataCollector: collector,OTEL_TRACES_TABLE_NAME: "otel_traces",};});diff --git a/src/client/src/__tests__/lib/platform/agents/materialize.test.ts b/src/client/src/__tests__/lib/platform/agents/materialize.test.tsindex 36953297..7a655beb 100644--- a/src/client/src/__tests__/lib/platform/agents/materialize.test.ts+++ b/src/client/src/__tests__/lib/platform/agents/materialize.test.ts@@ -55,6 +55,10 @@ jest.mock("@/lib/platform/coding-agents/source", () => ({resolveCodingAgentsClickHouseDbConfigId: (...args: unknown[]) =>mockResolveCodingAgentsClickHouseDbConfigId(...args),}));+jest.mock("@/lib/platform/connectors/datasource/clickhouse/direct-read", () => ({+ resolveTracesTableRef: jest.fn().mockResolvedValue("otel_traces"),+ queryConnectorTraces: jest.fn(),+}));import { intelligenceDataCollector } from "@/lib/platform/common";import { materializeAgents } from "@/lib/platform/agents/materialize";@@ -90,21 +94,29 @@ function queueDiscovery(sdkRows: Array<Record<string, unknown>>,ctrlRows: Array<Record<string, unknown>>,requestCountRows: Array<Record<string, unknown>> = [],- codingRows: Array<Record<string, unknown>> = []+ codingRows: Array<Record<string, unknown>> = [],+ onInsert?: (config: { table?: string; values?: unknown[] }) => void) {- // `materializeAgents` fires `Promise.all([discoverAgents(),- // discoverCodingAgents()])`. Inside `discoverAgents` two queries run- // sequentially (SDK then controller); `discoverCodingAgents` fires- // one. The microtask order under `Promise.all` is therefore:- // 1) SDK discovery (kicked off first inside discoverAgents)- // 2) Coding-agent discovery (kicked off by the second Promise.all entry)- // 3) Controller discovery (resumes after SDK resolves)- // 4) Request-count rollup (after both discovery functions resolve)- mockedDC- .mockResolvedValueOnce({ data: sdkRows } as any)- .mockResolvedValueOnce({ data: codingRows } as any)- .mockResolvedValueOnce({ data: ctrlRows } as any)- .mockResolvedValueOnce({ data: requestCountRows } as any);+ mockedDC.mockImplementation(async (config: any, op?: string) => {+ if (op === "insert") {+ onInsert?.(config);+ return { data: [] } as any;+ }+ const query = String(config?.query || "");+ if (query.includes("sdk_seen AS")) {+ return { data: sdkRows } as any;+ }+ if (query.includes("openlit_controller_services")) {+ return { data: ctrlRows } as any;+ }+ if (query.includes("chat_id") && query.includes("coding_agent")) {+ return { data: codingRows } as any;+ }+ if (query.includes("request_count_24h")) {+ return { data: requestCountRows } as any;+ }+ return { data: [] } as any;+ });}beforeEach(() => {@@ -125,6 +137,7 @@ describe("materializeAgents — connector routing purity", () => {mockGetTelemetryAdapterForDbConfig.mockRejectedValue(new Error("Tempo credentials unavailable"));+ mockedDC.mockResolvedValue({ data: [] });await expect(materializeAgents({ dbConfigId: "db-1" })).rejects.toThrow("Tempo credentials unavailable");@@ -184,6 +197,7 @@ describe("materializeAgents — workload_key dedup", () => {// catalogues the same container as `demo-openai-app` (container_name).// Both carry workload_key='docker:demo-openai-app' — the SDK because// the controller injected it via OTEL_RESOURCE_ATTRIBUTES.+ const inserts: RecordedInsert[] = [];queueDiscovery([{@@ -211,29 +225,16 @@ describe("materializeAgents — workload_key dedup", () => {first_seen: "2026-05-11 21:50:00",last_seen: "2026-05-11 22:10:00",},- ]- );- const inserts: RecordedInsert[] = [];- // First three calls are the queued discovery queries; capture the- // insert that follows.- // `mockImplementation` (not `Once`) intentionally: the materializer- // now runs an extra conflict-resolution SELECT before the final- // summary INSERT when summaryRows contain any non-coding source.- // That probe must be covered too, otherwise the unmocked call- // returns `undefined` and the production code blows up reading- // `res.err`. The implementation here short-circuits every non-- // insert call with `{ data: [] }` so the conflict query sees- // "no conflicting coding rows" and proceeds to the insert.- mockedDC.mockImplementation(async (c: any, op?: string) => {- if (op === "insert") {+ ],+ [],+ [],+ (c) => {inserts.push({table: String(c.table),- values: (c.values || []) as any,+ values: (c.values || []) as Array<Record<string, unknown>>,});- return { data: [] } as any;}- return { data: [] } as any;- });+ );await materializeAgents();@@ -253,6 +254,7 @@ describe("materializeAgents — workload_key dedup", () => {});it("keeps SDK-only and controller-only rows as separate agents when their workload_key doesn't match", async () => {+ const inserts: RecordedInsert[] = [];queueDiscovery([{@@ -278,27 +280,16 @@ describe("materializeAgents — workload_key dedup", () => {first_seen: "2026-05-11 22:00:00",last_seen: "2026-05-11 22:10:00",},- ]- );- const inserts: RecordedInsert[] = [];- // `mockImplementation` (not `Once`) intentionally: the materializer- // now runs an extra conflict-resolution SELECT before the final- // summary INSERT when summaryRows contain any non-coding source.- // That probe must be covered too, otherwise the unmocked call- // returns `undefined` and the production code blows up reading- // `res.err`. The implementation here short-circuits every non-- // insert call with `{ data: [] }` so the conflict query sees- // "no conflicting coding rows" and proceeds to the insert.- mockedDC.mockImplementation(async (c: any, op?: string) => {- if (op === "insert") {+ ],+ [],+ [],+ (c) => {inserts.push({table: String(c.table),- values: (c.values || []) as any,+ values: (c.values || []) as Array<Record<string, unknown>>,});- return { data: [] } as any;}- return { data: [] } as any;- });+ );await materializeAgents();@@ -333,9 +324,9 @@ describe("materializeAgents — workload_key dedup", () => {await materializeAgents();- // First query is the SDK discovery CTE.+ // First SDK discovery query (coding-agent discovery may run in parallel).expect(queries.length).toBeGreaterThan(0);- const sdkQuery = queries[0];+ const sdkQuery = queries.find((q) => q.includes("sdk_seen AS")) || "";expect(sdkQuery).toContain("telemetry.distro.name");expect(sdkQuery).toContain("opentelemetry-ebpf-instrumentation");expect(sdkQuery).toMatch(@@ -349,6 +340,7 @@ describe("materializeAgents — workload_key dedup", () => {// env var yet, so the SDK's traces have no workload_key. We fall// back to the legacy service_name match so we don't briefly// double-list the agent during rollout.+ const inserts: RecordedInsert[] = [];queueDiscovery([{@@ -374,27 +366,16 @@ describe("materializeAgents — workload_key dedup", () => {first_seen: "2026-05-11 22:00:00",last_seen: "2026-05-11 22:10:00",},- ]- );- const inserts: RecordedInsert[] = [];- // `mockImplementation` (not `Once`) intentionally: the materializer- // now runs an extra conflict-resolution SELECT before the final- // summary INSERT when summaryRows contain any non-coding source.- // That probe must be covered too, otherwise the unmocked call- // returns `undefined` and the production code blows up reading- // `res.err`. The implementation here short-circuits every non-- // insert call with `{ data: [] }` so the conflict query sees- // "no conflicting coding rows" and proceeds to the insert.- mockedDC.mockImplementation(async (c: any, op?: string) => {- if (op === "insert") {+ ],+ [],+ [],+ (c) => {inserts.push({table: String(c.table),- values: (c.values || []) as any,+ values: (c.values || []) as Array<Record<string, unknown>>,});- return { data: [] } as any;}- return { data: [] } as any;- });+ );await materializeAgents();@@ -414,6 +395,7 @@ describe("materializeAgents — workload_key dedup", () => {// import-scan and surfaces them in openlit_controller_services// .llm_providers — we union those into providers so the table// renders the logos even before the first request lands.+ const inserts: RecordedInsert[] = [];queueDiscovery([],[@@ -429,27 +411,16 @@ describe("materializeAgents — workload_key dedup", () => {first_seen: "2026-05-11 22:00:00",last_seen: "2026-05-11 22:10:00",},- ]- );- const inserts: RecordedInsert[] = [];- // `mockImplementation` (not `Once`) intentionally: the materializer- // now runs an extra conflict-resolution SELECT before the final- // summary INSERT when summaryRows contain any non-coding source.- // That probe must be covered too, otherwise the unmocked call- // returns `undefined` and the production code blows up reading- // `res.err`. The implementation here short-circuits every non-- // insert call with `{ data: [] }` so the conflict query sees- // "no conflicting coding rows" and proceeds to the insert.- mockedDC.mockImplementation(async (c: any, op?: string) => {- if (op === "insert") {+ ],+ [],+ [],+ (c) => {inserts.push({table: String(c.table),- values: (c.values || []) as any,+ values: (c.values || []) as Array<Record<string, unknown>>,});- return { data: [] } as any;}- return { data: [] } as any;- });+ );await materializeAgents();diff --git a/src/client/src/__tests__/lib/platform/datasource/bootstrap.test.ts b/src/client/src/__tests__/lib/platform/datasource/bootstrap.test.tsindex 0f6d6c33..503e733d 100644--- a/src/client/src/__tests__/lib/platform/datasource/bootstrap.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/bootstrap.test.ts@@ -1,9 +1,14 @@+jest.mock("@/lib/db-config", () => ({+ getDBConfigByIdForBackground: jest.fn(),+ getDBConfigByUser: jest.fn(),+}));jest.mock("@/lib/platform/connectors/datasource/http/secret", () => ({resolveSourceSecret: jest.fn(),redactableSecretValues: () => [],}));jest.mock("@/lib/platform/common", () => ({dataCollector: jest.fn(),+ connectorDataCollector: jest.fn(),OTEL_TRACES_TABLE_NAME: "otel_traces",OTEL_LOGS_TABLE_NAME: "otel_logs",}));diff --git a/src/client/src/__tests__/lib/platform/datasource/clickhouse-adapter.test.ts b/src/client/src/__tests__/lib/platform/datasource/clickhouse-adapter.test.tsindex 8aba9af9..013723f0 100644--- a/src/client/src/__tests__/lib/platform/datasource/clickhouse-adapter.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/clickhouse-adapter.test.ts@@ -1,6 +1,5 @@const mockDataCollector = jest.fn();const mockGetRequests = jest.fn();-const mockGetRequestViaSpanId = jest.fn();const mockGetAttributeKeys = jest.fn();const mockGetLogs = jest.fn();const mockGetLogByRowId = jest.fn();@@ -12,13 +11,17 @@ const mockGetSignalSummary = jest.fn();jest.mock("@/lib/platform/common", () => ({dataCollector: (...args: unknown[]) => mockDataCollector(...args),+ connectorDataCollector: (...args: unknown[]) => mockDataCollector(...args),OTEL_TRACES_TABLE_NAME: "otel_traces",OTEL_LOGS_TABLE_NAME: "otel_logs",}));+jest.mock("@/lib/db-config", () => ({+ getDBConfigByIdForBackground: jest.fn().mockResolvedValue({ database: "openlit" }),+}));+jest.mock("@/lib/platform/request", () => ({getRequests: (...args: unknown[]) => mockGetRequests(...args),- getRequestViaSpanId: (...args: unknown[]) => mockGetRequestViaSpanId(...args),getAttributeKeys: (...args: unknown[]) => mockGetAttributeKeys(...args),}));@@ -117,12 +120,12 @@ describe("ClickHouseAdapter", () => {});it("getSpan returns null when not found", async () => {- mockGetRequestViaSpanId.mockResolvedValue({ record: undefined });+ mockDataCollector.mockResolvedValue({ data: [] });expect(await adapter.getSpan("nope")).toBeNull();});it("getSpan normalizes a found record and its events", async () => {- mockGetRequestViaSpanId.mockResolvedValue({ record: rawSpan });+ mockDataCollector.mockResolvedValue({ data: [rawSpan] });const span = await adapter.getSpan("s1");expect(span?.spanId).toBe("s1");expect(span?.events).toEqual([@@ -136,6 +139,7 @@ describe("ClickHouseAdapter", () => {expect(spans).toHaveLength(1);const [args, type, dbId] = mockDataCollector.mock.calls[0];expect((args as { query: string }).query).toContain("TraceId = 't1'");+ expect((args as { query: string }).query).toContain("`openlit`.`otel_traces`");expect(type).toBe("query");expect(dbId).toBe("db-1");});diff --git a/src/client/src/__tests__/lib/platform/datasource/clickhouse-direct-read.test.ts b/src/client/src/__tests__/lib/platform/datasource/clickhouse-direct-read.test.tsnew file mode 100644index 00000000..5bd6fee8--- /dev/null+++ b/src/client/src/__tests__/lib/platform/datasource/clickhouse-direct-read.test.ts@@ -0,0 +1,40 @@+const mockConnectorDataCollector = jest.fn();++jest.mock("@/lib/platform/common", () => ({+ connectorDataCollector: (...args: unknown[]) => mockConnectorDataCollector(...args),+}));++jest.mock("@/lib/db-config", () => ({+ getDBConfigByIdForBackground: jest.fn().mockResolvedValue({ database: "openlit" }),+}));++import {+ queryConnectorTraces,+ resolveTracesTableRef,+} from "@/lib/platform/connectors/datasource/clickhouse/direct-read";++describe("clickhouse direct-read", () => {+ beforeEach(() => {+ mockConnectorDataCollector.mockReset();+ });++ it("resolveTracesTableRef qualifies with configured database", async () => {+ expect(await resolveTracesTableRef("cfg-1")).toBe(+ "`openlit`.`otel_traces`"+ );+ });++ it("queryConnectorTraces uses connectorDataCollector", async () => {+ mockConnectorDataCollector.mockResolvedValue({ data: [{ TraceId: "t1" }] });+ const result = await queryConnectorTraces(+ "SELECT TraceId FROM `openlit`.`otel_traces`",+ "cfg-1"+ );+ expect(mockConnectorDataCollector).toHaveBeenCalledWith(+ { query: "SELECT TraceId FROM `openlit`.`otel_traces`" },+ "query",+ "cfg-1"+ );+ expect(result.data).toEqual([{ TraceId: "t1" }]);+ });+});diff --git a/src/client/src/__tests__/lib/platform/datasource/clickhouse-sql.test.ts b/src/client/src/__tests__/lib/platform/datasource/clickhouse-sql.test.tsnew file mode 100644index 00000000..cf56ffd7--- /dev/null+++ b/src/client/src/__tests__/lib/platform/datasource/clickhouse-sql.test.ts@@ -0,0 +1,17 @@+import {+ qualifiedTracesTable,+ quoteClickHouseIdentifier,+} from "@/lib/platform/connectors/datasource/clickhouse/sql";++describe("clickhouse sql helpers", () => {+ it("quotes identifiers safely", () => {+ expect(quoteClickHouseIdentifier("otel_traces")).toBe("`otel_traces`");+ expect(qualifiedTracesTable("openlit")).toBe("`openlit`.`otel_traces`");+ });++ it("rejects unsafe identifiers", () => {+ expect(() => quoteClickHouseIdentifier("bad-id")).toThrow(+ "Invalid ClickHouse identifier"+ );+ });+});diff --git a/src/client/src/__tests__/lib/platform/governance/agent-loop-fix.test.ts b/src/client/src/__tests__/lib/platform/governance/agent-loop-fix.test.tsnew file mode 100644index 00000000..37f77b57--- /dev/null+++ b/src/client/src/__tests__/lib/platform/governance/agent-loop-fix.test.ts@@ -0,0 +1,48 @@+import {+ agentLoopFixContext,+ buildAgentLoopKnowledgeRule,+ buildAgentLoopOtterPrompt,+} from "@/lib/platform/governance/agent-loop-fix";++describe("agent-loop-fix", () => {+ const finding = {+ resource: "/Users/nii/openlit/README.md",+ evidence: {+ tool_name: "read_file",+ count: 5,+ args_fingerprint: '{"path":"/Users/nii/openlit/README.md"}',+ },+ };++ it("extracts loop context from finding evidence", () => {+ expect(agentLoopFixContext(finding)).toEqual({+ tool: "read_file",+ count: 5,+ resource: "/Users/nii/openlit/README.md",+ fingerprint: '{"path":"/Users/nii/openlit/README.md"}',+ });+ });++ it("builds a paste-ready agent knowledge rule", () => {+ const rule = buildAgentLoopKnowledgeRule(finding);+ expect(rule).toContain("Tool-loop guard (read_file)");+ expect(rule).toContain("AGENTS.md");+ expect(rule).toContain(".cursor/rules/");+ expect(rule).toContain("read_file");+ expect(rule).toContain("README.md");+ expect(rule).not.toMatch(/interrupt/i);+ });++ it("builds an Otter prompt that prefers durable knowledge over interrupt", () => {+ const prompt = buildAgentLoopOtterPrompt(+ "Draft a rule for this loop",+ finding+ );+ expect(prompt).toContain("Tool: read_file");+ expect(prompt).toContain("Repeat count: 5");+ expect(prompt).toContain("AGENTS.md");+ expect(prompt).toContain("Draft a rule for this loop");+ expect(prompt).not.toMatch(/Stop or interrupt/i);+ expect(prompt).toMatch(/cannot interrupt|durable agent knowledge/i);+ });+});diff --git a/src/client/src/__tests__/lib/platform/governance/evidence.test.ts b/src/client/src/__tests__/lib/platform/governance/evidence.test.tsnew file mode 100644index 00000000..ef28704b--- /dev/null+++ b/src/client/src/__tests__/lib/platform/governance/evidence.test.ts@@ -0,0 +1,55 @@+import {+ extractResourceHint,+ matchingLoopSpans,+} from "@/lib/platform/governance/evidence";+import type { TraceHeirarchySpan } from "@/types/trace";++function makeSpan(+ overrides: Partial<TraceHeirarchySpan> & Pick<TraceHeirarchySpan, "SpanId">+): TraceHeirarchySpan {+ return {+ SpanName: "tool",+ Duration: 1,+ SpanAttributes: {},+ ResourceAttributes: {},+ children: [],+ ...overrides,+ };+}++describe("governance evidence", () => {+ it("extracts file paths from tool args json", () => {+ const hint = extractResourceHint(+ makeSpan({+ SpanId: "s1",+ SpanAttributes: {+ "gen_ai.tool.name": "read_file",+ "gen_ai.tool.args": '{"path":"/tmp/demo.ts"}',+ },+ })+ );+ expect(hint).toBe("/tmp/demo.ts");+ });++ it("matches loop spans by tool name and fingerprint", () => {+ const args = '{"path":"/a.ts"}';+ const spans = [+ makeSpan({+ SpanId: "a",+ SpanAttributes: {+ "gen_ai.tool.name": "read_file",+ "gen_ai.tool.args": args,+ },+ }),+ makeSpan({+ SpanId: "b",+ SpanAttributes: {+ "gen_ai.tool.name": "write",+ "gen_ai.tool.args": args,+ },+ }),+ ];+ const matched = matchingLoopSpans(spans, "read_file", args);+ expect(matched.map((s) => s.SpanId)).toEqual(["a"]);+ });+});diff --git a/src/client/src/__tests__/lib/platform/governance/governance.test.ts b/src/client/src/__tests__/lib/platform/governance/governance.test.tsnew file mode 100644index 00000000..392ef581--- /dev/null+++ b/src/client/src/__tests__/lib/platform/governance/governance.test.ts@@ -0,0 +1,306 @@+import type { TraceHeirarchySpan } from "@/types/trace";+import {+ flattenHierarchy,+ classifySpanRole,+ ruleFieldsFromHierarchySpan,+} from "@/lib/platform/governance/hierarchy";+import {+ buildHarnessMetrics,+ buildSecurityFindings,+ summarizeGovernanceReport,+} from "@/lib/platform/governance/security-checks";++function makeSpan(+ overrides: Partial<TraceHeirarchySpan> & Pick<TraceHeirarchySpan, "SpanId" | "SpanName">+): TraceHeirarchySpan {+ return {+ Duration: 1_000_000,+ SpanAttributes: {},+ ResourceAttributes: {},+ children: [],+ ...overrides,+ };+}++describe("governance hierarchy", () => {+ it("flattens nested spans", () => {+ const root = makeSpan({+ SpanId: "root",+ SpanName: "root",+ children: [+ makeSpan({ SpanId: "child", SpanName: "child" }),+ ],+ });+ const flat = flattenHierarchy(root);+ expect(flat.map((s) => s.SpanId)).toEqual(["root", "child"]);+ });++ it("extracts rule fields from span attributes", () => {+ const span = makeSpan({+ SpanId: "s1",+ SpanName: "chat",+ ServiceName: "my-svc",+ SpanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.system": "openai",+ },+ ResourceAttributes: {+ "deployment.environment": "production",+ },+ });+ const fields = ruleFieldsFromHierarchySpan(span);+ expect(fields.ServiceName).toBe("my-svc");+ expect(fields.SpanName).toBe("chat");+ expect(fields["gen_ai.request.model"]).toBe("gpt-4o");+ expect(fields["deployment.environment"]).toBe("production");+ });++ it("classifies tool spans", () => {+ const span = makeSpan({+ SpanId: "t1",+ SpanName: "tool.call",+ SpanAttributes: { "gen_ai.tool.name": "search" },+ });+ expect(classifySpanRole(span)).toBe("tool");+ });+});++describe("governance security checks", () => {+ it("flags span errors and generation health", () => {+ const spans = [+ makeSpan({+ SpanId: "err",+ SpanName: "llm",+ StatusCode: "STATUS_CODE_ERROR",+ StatusMessage: "boom",+ SpanAttributes: {+ "gen_ai.response.finish_reasons": "length",+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ "gen_ai.usage.output_tokens": 0,+ },+ }),+ ];+ const findings = buildSecurityFindings(spans);+ expect(findings.some((f) => f.category === "span_error")).toBe(true);+ expect(findings.some((f) => f.category === "generation_health")).toBe(true);+ });++ it("builds harness metrics", () => {+ const root = makeSpan({+ SpanId: "root",+ SpanName: "agent",+ children: [+ makeSpan({+ SpanId: "tool",+ SpanName: "tool.call",+ SpanAttributes: { "gen_ai.tool.name": "bash" },+ }),+ ],+ });+ const spans = flattenHierarchy(root);+ const harness = buildHarnessMetrics(root, spans);+ expect(harness.span_count).toBe(2);+ expect(harness.tool_call_count).toBe(1);+ expect(harness.tools_used).toContain("bash");+ expect(harness.total_tokens).toBe(0);+ expect(harness.cost_reported).toBe(false);+ });++ it("prefers session token rollups on the root for harness totals", () => {+ const root = makeSpan({+ SpanId: "root",+ SpanName: "coding_agent.session",+ SpanAttributes: {+ "gen_ai.usage.total_tokens": 1200,+ "coding_agent.client": "cursor",+ },+ children: [],+ });+ const harness = buildHarnessMetrics(root, flattenHierarchy(root));+ expect(harness.total_tokens).toBe(1200);+ expect(harness.cost_reported).toBe(false);+ });++ it("summarizes mixed governance posture", () => {+ const summary = summarizeGovernanceReport(+ [+ {+ id: "f1",+ category: "span_error",+ severity: "major",+ summary: "err",+ detail: "err",+ span_refs: ["a"],+ },+ ],+ 2,+ 1+ );+ expect(summary.risk_level).toBe("major");+ expect(summary.summary).toContain("2");+ });++ it("attaches real span ids and remediation for agent loops", () => {+ const args = '{"path":"/Users/nii/openlit/README.md"}';+ const spans = [+ makeSpan({+ SpanId: "loop-1",+ SpanName: "coding_agent.tool.call",+ TraceId: "t1",+ SpanAttributes: {+ "gen_ai.tool.name": "read_file",+ "gen_ai.tool.args": args,+ "coding_agent.session.id": "sess-1",+ },+ }),+ makeSpan({+ SpanId: "loop-2",+ SpanName: "coding_agent.tool.call",+ TraceId: "t1",+ SpanAttributes: {+ "gen_ai.tool.name": "read_file",+ "gen_ai.tool.args": args,+ "coding_agent.session.id": "sess-1",+ },+ }),+ makeSpan({+ SpanId: "loop-3",+ SpanName: "coding_agent.tool.call",+ TraceId: "t1",+ SpanAttributes: {+ "gen_ai.tool.name": "read_file",+ "gen_ai.tool.args": args,+ "coding_agent.session.id": "sess-1",+ },+ }),+ ];+ const findings = buildSecurityFindings(spans);+ const loop = findings.find((f) => f.category === "agent_loop");+ expect(loop).toBeTruthy();+ expect(loop?.span_refs).toEqual(+ expect.arrayContaining(["loop-1", "loop-2", "loop-3"])+ );+ expect(loop?.span_refs.every((id) => id.startsWith("loop-"))).toBe(true);+ expect(loop?.resource).toContain("README.md");+ expect(loop?.remediation).toBeTruthy();+ expect(loop?.remediation).toMatch(/AGENTS\.md|\.cursor\/rules/i);+ expect(loop?.remediation).not.toMatch(/Stop or interrupt/i);+ });++ it("dedupes permission-mode findings across spans", () => {+ const spans = [+ makeSpan({+ SpanId: "p1",+ SpanName: "coding_agent.session",+ SpanAttributes: {+ "coding_agent.policy.permission_mode": "agent",+ },+ }),+ makeSpan({+ SpanId: "p2",+ SpanName: "coding_agent.tool.call",+ SpanAttributes: {+ "coding_agent.policy.permission_mode": "agent",+ },+ }),+ ];+ const findings = buildSecurityFindings(spans).filter(+ (f) => f.category === "policy"+ );+ expect(findings).toHaveLength(1);+ expect(findings[0].span_refs).toEqual(expect.arrayContaining(["p1", "p2"]));+ expect(findings[0].remediation).toBeTruthy();+ });++ it("flags leftover coding-agent governance findings", () => {+ const spans = [+ makeSpan({+ SpanId: "session",+ SpanName: "coding_agent.session",+ SpanAttributes: {+ "coding_agent.content_capture_mode": "full",+ "coding_agent.session.outcome": "abandoned_with_change",+ "coding_agent.session.edit.reject_count": 3,+ "coding_agent.session.edit.accept_count": 1,+ "coding_agent.session.commit_count": 3,+ "coding_agent.session.pr_count": 2,+ "coding_agent.session.subagent_count": 4,+ "coding_agent.session.lines.added": 12,+ "coding_agent.vcs.dirty": "true",+ "coding_agent.mcp.server.name": "browser",+ "coding_agent.mcp.scope": "user",+ "coding_agent.mcp.source": "marketplace",+ },+ }),+ makeSpan({+ SpanId: "tool-secret",+ SpanName: "coding_agent.tool.call",+ SpanAttributes: {+ "gen_ai.tool.name": "write",+ "gen_ai.tool.args": '{"token":"AKIAIOSFODNN7EXAMPLE"}',+ },+ }),+ ];+ const findings = buildSecurityFindings(spans);+ expect(findings.some((f) => f.evidence?.content_capture_mode === "full")).toBe(+ true+ );+ expect(findings.some((f) => f.evidence?.session_outcome === "abandoned_with_change")).toBe(+ true+ );+ expect(findings.some((f) => f.evidence?.edit_reject_count === 3)).toBe(true);+ expect(findings.some((f) => f.evidence?.vcs_dirty === true)).toBe(true);+ expect(findings.some((f) => f.evidence?.mcp_scope === "user_or_local")).toBe(+ true+ );+ expect(findings.some((f) => f.evidence?.mcp_source === "marketplace")).toBe(+ true+ );+ expect(findings.some((f) => f.evidence?.commit_count === 3)).toBe(true);+ expect(findings.some((f) => f.evidence?.subagent_count === 4)).toBe(true);+ const secret = findings.find((f) =>+ String(f.evidence?.secret_kinds || "").includes("aws_access_key")+ );+ expect(secret).toBeTruthy();+ expect(JSON.stringify(secret)).not.toContain("AKIAIOSFODNN7EXAMPLE");+ });++ it("does not flag a dirty tree when the agent did not write", () => {+ const findings = buildSecurityFindings([+ makeSpan({+ SpanId: "session",+ SpanName: "coding_agent.session",+ SpanAttributes: {+ "coding_agent.vcs.dirty": "true",+ "coding_agent.session.outcome": "completed",+ },+ }),+ ]);+ expect(findings.some((f) => f.evidence?.vcs_dirty)).toBe(false);+ });++ it("does not flag healthy coding-agent defaults", () => {+ const spans = [+ makeSpan({+ SpanId: "session",+ SpanName: "coding_agent.session",+ SpanAttributes: {+ "coding_agent.content_capture_mode": "metadata_only",+ "coding_agent.session.outcome": "completed",+ "coding_agent.session.edit.reject_count": 1,+ "coding_agent.session.edit.accept_count": 8,+ "coding_agent.session.commit_count": 1,+ "coding_agent.session.pr_count": 1,+ "coding_agent.session.subagent_count": 1,+ "coding_agent.vcs.dirty": "false",+ "coding_agent.mcp.server.name": "repo",+ "coding_agent.mcp.scope": "project",+ "coding_agent.mcp.source": "builtin",+ },+ }),+ ];+ const findings = buildSecurityFindings(spans);+ expect(findings).toEqual([]);+ });+});diff --git a/src/client/src/__tests__/lib/platform/governance/secret-scan.test.ts b/src/client/src/__tests__/lib/platform/governance/secret-scan.test.tsnew file mode 100644index 00000000..18a18a0d--- /dev/null+++ b/src/client/src/__tests__/lib/platform/governance/secret-scan.test.ts@@ -0,0 +1,27 @@+import { detectSecretKinds, scanSpanPayloads } from "@/lib/platform/governance/secret-scan";++describe("governance secret scan", () => {+ it("detects high-confidence credential kinds without returning the value", () => {+ const sample =+ "AKIAIOSFODNN7EXAMPLE and ghp_abcdefghijklmnopqrstuvwxyz0123456789";+ expect(detectSecretKinds(sample)).toEqual(+ expect.arrayContaining(["aws_access_key", "github_token"])+ );+ });++ it("scans tool payload attributes only", () => {+ const kinds = scanSpanPayloads({+ "gen_ai.tool.args": '{"password":"supersecretvalue"}',+ "gen_ai.request.model": "gpt-4o",+ });+ expect(kinds).toContain("password_assignment");+ });++ it("does not flag ordinary tool arguments", () => {+ expect(+ scanSpanPayloads({+ "gen_ai.tool.args": '{"path":"/tmp/demo.ts","limit":20}',+ })+ ).toEqual([]);+ });+});diff --git a/src/client/src/__tests__/lib/platform/governance/validate.test.ts b/src/client/src/__tests__/lib/platform/governance/validate.test.tsnew file mode 100644index 00000000..3ba3fa54--- /dev/null+++ b/src/client/src/__tests__/lib/platform/governance/validate.test.ts@@ -0,0 +1,23 @@+import {+ GOVERNANCE_SPAN_ID_MAX_LENGTH,+ validateGovernanceSpanId,+} from "@/lib/platform/governance/validate";++describe("validateGovernanceSpanId", () => {+ it("accepts standard otel span ids", () => {+ expect(validateGovernanceSpanId("a1b2c3d4e5f6a7b8")).toBe("a1b2c3d4e5f6a7b8");+ expect(validateGovernanceSpanId("synthetic-session-1")).toBe(+ "synthetic-session-1"+ );+ });++ it("rejects empty, oversized, and injection-prone values", () => {+ expect(validateGovernanceSpanId("")).toBeNull();+ expect(validateGovernanceSpanId(" ")).toBeNull();+ expect(+ validateGovernanceSpanId("x".repeat(GOVERNANCE_SPAN_ID_MAX_LENGTH + 1))+ ).toBeNull();+ expect(validateGovernanceSpanId("'; DROP TABLE--")).toBeNull();+ expect(validateGovernanceSpanId("span\nid")).toBeNull();+ });+});diff --git a/src/client/src/__tests__/lib/platform/request/request.test.ts b/src/client/src/__tests__/lib/platform/request/request.test.tsindex d7a9b098..ab6b9968 100644--- a/src/client/src/__tests__/lib/platform/request/request.test.ts+++ b/src/client/src/__tests__/lib/platform/request/request.test.ts@@ -1,7 +1,16 @@-jest.mock('@/lib/platform/common', () => ({- dataCollector: jest.fn(),- OTEL_TRACES_TABLE_NAME: 'otel_traces',+jest.mock('@/lib/db-config', () => ({+ getDBConfigByIdForBackground: jest.fn().mockResolvedValue({ database: 'openlit' }),+ getDBConfigByUser: jest.fn(),}));+jest.mock('@/lib/platform/common', () => {+ const collector = jest.fn();+ return {+ dataCollector: collector,+ connectorDataCollector: collector,+ intelligenceDataCollector: collector,+ OTEL_TRACES_TABLE_NAME: 'otel_traces',+ };+});import {getGroupByExpression,diff --git a/src/client/src/app/api/metrics/request/span/[id]/governance/route.ts b/src/client/src/app/api/metrics/request/span/[id]/governance/route.tsnew file mode 100644index 00000000..77a2acd3--- /dev/null+++ b/src/client/src/app/api/metrics/request/span/[id]/governance/route.ts@@ -0,0 +1,102 @@+import { getRequestEnvironment } from "@/constants/openlit-context";+import {+ GOVERNANCE_INVALID_SPAN_ID,+ GOVERNANCE_MISSING_SPAN_ID,+} from "@/constants/messages/en";+import {+ withGovernanceAccess,+ withGovernanceAudit,+} from "@/lib/access/governance-route";+import { withRouteAccess } from "@/lib/access/route-access";+import { fireGovernanceReportTelemetry } from "@/helpers/server/governance-analytics";+import { buildTraceGovernanceReport } from "@/lib/platform/governance/trace-report";+import { validateGovernanceSpanId } from "@/lib/platform/governance/validate";+import { resolveIntelligenceClickHouseDbConfigId } from "@/lib/platform/intelligence/source";+import { errorResponse } from "@/utils/api-response";++async function GETHandler(+ request: Request,+ context: { params?: { id?: string } }+) {+ const startTimestamp = Date.now();+ const { id } = context.params || {};+ const url = new URL(request.url);+ const traceId = url.searchParams.get("traceId") || undefined;++ if (!id) {+ fireGovernanceReportTelemetry({+ success: false,+ startTimestamp,+ spanId: "",+ traceId,+ reason: "missing_span",+ });+ return errorResponse(GOVERNANCE_MISSING_SPAN_ID, GOVERNANCE_MISSING_SPAN_ID, 400);+ }++ const spanId = validateGovernanceSpanId(id);+ if (!spanId) {+ fireGovernanceReportTelemetry({+ success: false,+ startTimestamp,+ spanId: id,+ traceId,+ reason: "invalid_span",+ });+ return errorResponse(+ GOVERNANCE_INVALID_SPAN_ID,+ GOVERNANCE_INVALID_SPAN_ID,+ 400+ );+ }++ const environment =+ url.searchParams.get("environment") || getRequestEnvironment(request);++ // Intelligence-layer tables (rules / evals) follow the connector binding for+ // the selected environment; traces hierarchy uses the same environment via+ // resolveTracesAdapter inside buildTraceGovernanceReport.+ const databaseConfigId =+ (await resolveIntelligenceClickHouseDbConfigId({ environment })) ||+ undefined;++ const result = await buildTraceGovernanceReport(spanId, {+ traceId,+ environment,+ databaseConfigId,+ });++ if (result.err) {+ fireGovernanceReportTelemetry({+ success: false,+ startTimestamp,+ spanId,+ traceId,+ error: String(result.err),+ });+ return errorResponse(result.err, String(result.err), 400);+ }++ const report = result.report!;+ fireGovernanceReportTelemetry({+ success: true,+ startTimestamp,+ spanId,+ traceId: report.trace_id,+ riskLevel: report.risk_level,+ findingCount: report.finding_count,+ ruleMatchCount: report.rule_match_count,+ evaluationCount: report.evaluations.length,+ analysisLimited: report.analysis_limited,+ });++ return Response.json({ report });+}++export const GET = withGovernanceAudit(+ withRouteAccess(+ "traces.read",+ withGovernanceAccess("read", GETHandler),+ { requireDbConfig: true }+ )+);diff --git a/src/client/src/app/api/telemetry/[...segments]/route.ts b/src/client/src/app/api/telemetry/[...segments]/route.tsindex cfd49376..1453e3fb 100644--- a/src/client/src/app/api/telemetry/[...segments]/route.ts+++ b/src/client/src/app/api/telemetry/[...segments]/route.ts@@ -57,6 +57,10 @@ async function GETHandler(request: NextRequest, context: RouteContext) {const handler = (await import("@/app/api/metrics/request/span/[id]/heirarchy/route")).GET;return handler(request, { params: { id: segments[2] } });}+ if (segments.length === 4 && segments[0] === "request" && segments[1] === "span" && segments[3] === "governance") {+ const handler = (await import("@/app/api/metrics/request/span/[id]/governance/route")).GET;+ return handler(request, { params: { id: segments[2] } });+ }if (segments.length === 3 && segments[0] === "request" && segments[1] === "span") {const handler = (await import("@/app/api/metrics/request/span/[id]/route")).GET;return handler(request, { params: { id: segments[2] } });diff --git a/src/client/src/components/(playground)/chat/ask-otter-panel.tsx b/src/client/src/components/(playground)/chat/ask-otter-panel.tsxindex 204a33e9..5f2c296e 100644--- a/src/client/src/components/(playground)/chat/ask-otter-panel.tsx+++ b/src/client/src/components/(playground)/chat/ask-otter-panel.tsx@@ -28,6 +28,8 @@ export type AskOtterPanelProps = {buildPrompt: (question: string) => string;/** Optional chip for the currently selected item on the host page. */contextLabel?: string | null;+ /** Prefill the question input (e.g. governance “get a fix” default). */+ defaultQuestion?: string;/*** `dock` — compact bottom strip.* `fill` — full-height column for side panels / resizable hosts.@@ -48,11 +50,12 @@ export default function AskOtterPanel({copy,buildPrompt,contextLabel,+ defaultQuestion = "",layout = "dock",className,}: AskOtterPanelProps) {const messages = getMessage();- const [question, setQuestion] = useState("");+ const [question, setQuestion] = useState(defaultQuestion);const [hasConfig, setHasConfig] = useState<boolean | null>(null);const [thread, setThread] = useState<AskMessage[]>([]);const [streaming, setStreaming] = useState(false);diff --git a/src/client/src/components/(playground)/observability/detail-object-tabs.tsx b/src/client/src/components/(playground)/observability/detail-object-tabs.tsxindex 392c040d..1308f6f2 100644--- a/src/client/src/components/(playground)/observability/detail-object-tabs.tsx+++ b/src/client/src/components/(playground)/observability/detail-object-tabs.tsx@@ -1,9 +1,12 @@"use client";-import type { ReactNode } from "react";+import { useMemo, useState, type ReactNode } from "react";import { isPlainObject } from "lodash";+import { ClipboardCheck, Sparkles } from "lucide-react";import AttributeGrid from "./attribute-grid";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { cn } from "@/lib/utils";+import getMessage from "@/constants/messages";type DetailObjectTab = {id: string;@@ -127,45 +130,90 @@ export function buildObjectTabs(return [...rootTab, ...directTabs, ...groupedTabs];}+function featuredIcon(tabId: string) {+ if (tabId === "evaluations") return <ClipboardCheck className="h-3.5 w-3.5" />;+ return <Sparkles className="h-3.5 w-3.5" />;+}++type CustomTab = {+ id: string;+ label: string;+ content: ReactNode;+};+export default function DetailObjectTabs({tabs,extraTabs,- extraTabsPlacement = "after",}: {tabs: DetailObjectTab[];- extraTabs?: Array<{- id: string;- label: string;- content: ReactNode;- }>;+ extraTabs?: CustomTab[];extraTabsPlacement?: "before" | "after";}) {+ const m = getMessage();const objectTabs = tabs.map((tab) => ({ ...tab, type: "object" as const }));- const customTabs = (extraTabs || []).map((tab) => ({+ const featuredTabs = (extraTabs || []).map((tab) => ({...tab,type: "custom" as const,}));- const allTabs =- extraTabsPlacement === "before"- ? [...customTabs, ...objectTabs]- : [...objectTabs, ...customTabs];- if (!allTabs.length) return null;+ const detailTabs = objectTabs;+ const allTabs = [...featuredTabs, ...detailTabs];+ const defaultTab = detailTabs[0]?.id || featuredTabs[0]?.id;+ const [activeTab, setActiveTab] = useState(defaultTab);+ const resolvedTab = useMemo(() => {+ if (allTabs.some((tab) => tab.id === activeTab)) return activeTab;+ return defaultTab;+ }, [activeTab, allTabs, defaultTab]);++ if (!allTabs.length || !resolvedTab) return null;return (- <Tabs defaultValue={allTabs[0].id} className="min-w-0">- <div className="max-w-full overflow-x-auto overflow-y-hidden pb-1">- <TabsList className="h-9 w-max min-w-full justify-start rounded-md bg-stone-100 p-1 dark:bg-stone-900">- {allTabs.map((tab) => (- <TabsTrigger- key={tab.id}- value={tab.id}- className="shrink-0 px-3 py-1 text-xs"- >- {tab.label}- </TabsTrigger>- ))}- </TabsList>- </div>+ <Tabs+ value={resolvedTab}+ onValueChange={setActiveTab}+ className="min-w-0"+ >+ {featuredTabs.length > 0 && (+ <div className="mb-2 flex flex-wrap gap-1.5">+ {featuredTabs.map((tab) => {+ const selected = resolvedTab === tab.id;+ return (+ <button+ key={tab.id}+ type="button"+ onClick={() => setActiveTab(tab.id)}+ aria-pressed={selected}+ className={cn(+ "inline-flex h-7 items-center gap-1 rounded-md px-2 text-xs font-medium transition-colors",+ selected+ ? "bg-primary text-white"+ : "border border-stone-200 bg-white text-stone-700 hover:bg-stone-50 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-200 dark:hover:bg-stone-900"+ )}+ >+ {featuredIcon(tab.id)}+ {tab.label}+ </button>+ );+ })}+ </div>+ )}+ {detailTabs.length > 0 && (+ <div className="max-w-full overflow-x-auto overflow-y-hidden">+ <TabsList+ aria-label={m.OBSERVABILITY_SPAN_DETAILS}+ className="h-8 w-max min-w-full justify-start gap-0 rounded-none border-b border-stone-200 bg-transparent p-0 dark:border-stone-800"+ >+ {detailTabs.map((tab) => (+ <TabsTrigger+ key={tab.id}+ value={tab.id}+ className="h-8 shrink-0 rounded-none border-b-2 border-transparent bg-transparent px-2.5 text-xs shadow-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-stone-900 data-[state=active]:shadow-none dark:data-[state=active]:text-stone-50"+ >+ {tab.label}+ </TabsTrigger>+ ))}+ </TabsList>+ </div>+ )}{allTabs.map((tab) => (<TabsContent key={tab.id} value={tab.id} className="mt-3">{tab.type === "object" ? (diff --git a/src/client/src/components/(playground)/observability/detail-shell.tsx b/src/client/src/components/(playground)/observability/detail-shell.tsxindex d70b9416..5d4050ea 100644--- a/src/client/src/components/(playground)/observability/detail-shell.tsx+++ b/src/client/src/components/(playground)/observability/detail-shell.tsx@@ -1,3 +1,5 @@+import { cn } from "@/lib/utils";+export default function DetailShell({title,leadingActions,@@ -5,6 +7,7 @@ export default function DetailShell({headerMeta,children,compact = false,+ fill = false,}: {title: string;leadingActions?: React.ReactNode;@@ -12,11 +15,22 @@ export default function DetailShell({headerMeta?: React.ReactNode;children: React.ReactNode;compact?: boolean;+ /** Lock the shell height and let inner panes scroll instead of the page. */+ fill?: boolean;}) {return (- <div className="flex flex-col w-full h-full overflow-auto rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950">+ <div+ className={cn(+ "flex h-full w-full flex-col rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950",+ fill ? "overflow-hidden" : "overflow-auto"+ )}+ ><div- className={`sticky top-0 z-10 flex flex-col border-b border-stone-200 bg-white/95 shadow-sm shadow-stone-200/40 backdrop-blur dark:border-stone-800 dark:bg-stone-950/95 dark:shadow-black/20 ${compact ? "gap-2 px-3 py-2" : "gap-3 px-4 py-3"}`}+ className={cn(+ "z-10 flex shrink-0 flex-col border-b border-stone-200 bg-white/95 shadow-sm shadow-stone-200/40 backdrop-blur dark:border-stone-800 dark:bg-stone-950/95 dark:shadow-black/20",+ compact ? "gap-2 px-3 py-2" : "gap-3 px-4 py-3",+ !fill && "sticky top-0"+ )}><divclassName={`flex flex-col md:flex-row md:items-start md:justify-between ${compact ? "gap-2" : "gap-3"}`}@@ -28,14 +42,20 @@ export default function DetailShell({className={`truncate font-semibold text-stone-950 dark:text-stone-50 ${compact ? "text-base md:text-lg" : "text-lg md:text-xl"}`}>{title}- </h1>+ </h1></div></div>{actions && <div className="shrink-0">{actions}</div>}</div>{headerMeta && <div>{headerMeta}</div>}</div>- <div className={`flex flex-col ${compact ? "gap-2 p-2" : "gap-4 p-4"}`}>+ <div+ className={cn(+ "flex flex-col",+ compact ? "gap-2 p-2" : "gap-4 p-4",+ fill && "min-h-0 flex-1 overflow-hidden"+ )}+ >{children}</div></div>diff --git a/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx b/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsxindex 3a9ab6c4..e9ab1bd4 100644--- a/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx+++ b/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx@@ -2,7 +2,12 @@import { useEffect, useMemo, useRef, useState } from "react";import type { ReactNode } from "react";-import { BarChart3, DollarSign, GitBranch, MessageSquareText, Network, Sparkles } from "lucide-react";+import { BarChart3, DollarSign, GitBranch, MessageSquareText, Network, Repeat, Shield, Sparkles } from "lucide-react";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";import useFetchWrapper from "@/utils/hooks/useFetchWrapper";import { useSignalCapabilities } from "@/utils/hooks/useSignalCapabilities";import { TraceHeirarchySpan } from "@/types/trace";@@ -15,20 +20,31 @@ import TimelineView from "@/components/(playground)/request/components/timeline-import NodeGraph from "@/components/(playground)/request/components/node-graph";import ChatView from "@/components/(playground)/request/components/chat-view";import TraceAiAnalysisPanel from "@/components/(playground)/request/components/trace-ai-analysis-panel";+import TraceGovernancePanel from "./trace-governance-panel";import getMessage from "@/constants/messages";import { cn } from "@/lib/utils";+import { getCurrentProjectEnvironment } from "@/selectors/project";+import { useRootStore } from "@/store";+import { detectAgentLoops } from "@/lib/platform/agent-loop/classify";+import { agentLoopDetailLine } from "@/lib/platform/agent-loop/format";+import { flattenHierarchy } from "@/lib/platform/governance/hierarchy";+import { extractResourceHint, matchingLoopSpans } from "@/lib/platform/governance/evidence";-type ViewMode = "tree" | "chat" | "analysis" | "timeline" | "graph";+type ViewMode = "tree" | "chat" | "agentloop" | "analysis" | "governance" | "timeline" | "graph";type ViewModeLabelKey =| "OBSERVABILITY_TREE"| "OBSERVABILITY_CHAT"+ | "OBSERVABILITY_AGENT_LOOP"| "TRACE_AI_TAB_TITLE"+ | "GOVERNANCE_TAB_TITLE"| "OBSERVABILITY_TIMELINE"| "OBSERVABILITY_GRAPH";const VIEW_MODES: { key: ViewMode; labelKey: ViewModeLabelKey; icon: ReactNode }[] = [{ key: "tree", labelKey: "OBSERVABILITY_TREE", icon: <GitBranch className="h-3.5 w-3.5" /> },{ key: "chat", labelKey: "OBSERVABILITY_CHAT", icon: <MessageSquareText className="h-3.5 w-3.5" /> },+ { key: "agentloop", labelKey: "OBSERVABILITY_AGENT_LOOP", icon: <Repeat className="h-3.5 w-3.5" /> },+ { key: "governance", labelKey: "GOVERNANCE_TAB_TITLE", icon: <Shield className="h-3.5 w-3.5" /> },{ key: "analysis", labelKey: "TRACE_AI_TAB_TITLE", icon: <Sparkles className="h-3.5 w-3.5" /> },{ key: "timeline", labelKey: "OBSERVABILITY_TIMELINE", icon: <BarChart3 className="h-3.5 w-3.5" /> },{ key: "graph", labelKey: "OBSERVABILITY_GRAPH", icon: <Network className="h-3.5 w-3.5" /> },@@ -82,6 +98,66 @@ function isCodingAgentTree(span?: TraceHeirarchySpan): boolean {return false;}+function AgentLoopView({+ record,+ onSelectSpan,+}: {+ record: TraceHeirarchySpan;+ onSelectSpan?: (spanId: string) => void;+}) {+ const m = getMessage();+ const spans = useMemo(() => flattenHierarchy(record), [record]);+ const loops = useMemo(() => detectAgentLoops(spans), [spans]);++ if (!loops.length) {+ return (+ <div className="px-3 py-8 text-sm text-stone-400">+ {m.OBSERVABILITY_AGENT_LOOP_EMPTY}+ </div>+ );+ }++ return (+ <div className="grid min-w-0 gap-2 p-3">+ {loops.map((loop) => {+ const matched = matchingLoopSpans(spans, loop.toolName, loop.fingerprint);+ const sample = matched[0];+ const resource = sample ? extractResourceHint(sample) : "";+ return (+ <div+ key={`${loop.toolName}:${loop.fingerprint}`}+ className="min-w-0 max-w-full overflow-hidden rounded-md border border-stone-200 bg-white px-2.5 py-2 dark:border-stone-800 dark:bg-stone-950"+ >+ <p className="break-words text-xs font-medium text-stone-900 dark:text-stone-50">+ {agentLoopDetailLine(loop)}+ </p>+ {resource ? (+ <p className="mt-1 break-all font-mono text-[11px] text-stone-500 dark:text-stone-400">+ {resource}+ </p>+ ) : null}+ {matched.length > 0 && onSelectSpan ? (+ <div className="mt-2 flex min-w-0 flex-wrap gap-1">+ <span className="sr-only">{m.OBSERVABILITY_AGENT_LOOP_SPANS}</span>+ {matched.slice(0, 8).map((span) => (+ <button+ key={span.SpanId}+ type="button"+ onClick={() => onSelectSpan(span.SpanId)}+ className="max-w-full break-all rounded border border-stone-200 px-1.5 py-0.5 font-mono text-[10px] text-stone-600 hover:bg-stone-50 dark:border-stone-800 dark:text-stone-300 dark:hover:bg-stone-900"+ >+ {span.SpanId.slice(0, 8)}+ </button>+ ))}+ </div>+ ) : null}+ </div>+ );+ })}+ </div>+ );+}+function SpanHierarchyExplorerInner({hierarchySpanId,selectedSpanId,@@ -102,8 +178,9 @@ function SpanHierarchyExplorerInner({// whether the user has explicitly picked a view so we don't keep// snapping back to "chat" every time the trace data refreshes.const userPickedViewRef = useRef(false);- const { data, fireRequest, isLoading } = useFetchWrapper();+ const { data, fireRequest, isLoading, reset } = useFetchWrapper();const { capabilities } = useSignalCapabilities();+ const environment = useRootStore(getCurrentProjectEnvironment);// The Chat view renders OTel span events (prompts/completions). Sources that// don't carry span events (e.g. Datadog, New Relic) can't populate it, so we@@ -120,12 +197,19 @@ function SpanHierarchyExplorerInner({}, [selectedSpanId, updateRequest]);useEffect(() => {- const qs = traceId ? `?traceId=${encodeURIComponent(traceId)}` : "";+ reset();+ }, [environment, reset]);++ useEffect(() => {+ const params = new URLSearchParams();+ if (traceId) params.set("traceId", traceId);+ if (environment) params.set("environment", environment);+ const qs = params.size ? `?${params.toString()}` : "";fireRequest({requestType: "GET",url: `/api/telemetry/request/span/${hierarchySpanId}/heirarchy${qs}`,});- }, [fireRequest, hierarchySpanId, traceId]);+ }, [environment, fireRequest, hierarchySpanId, traceId]);const typedData = (data as { record?: TraceHeirarchySpan; err?: string }) || {};const record = typedData.record;@@ -152,103 +236,138 @@ function SpanHierarchyExplorerInner({}}, [availableViewModes, viewMode]);+ const spanCountLabel = isLoading+ ? m.OBSERVABILITY_LOADING_SPANS+ : m.OBSERVABILITY_SPAN_COUNT(spanCount.toLocaleString());+return (<sectionclassName={cn(- "rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 overflow-hidden",- fill && "flex h-full min-h-0 flex-col"+ "overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950",+ fill ? "flex h-full min-h-0" : "flex")}><SelectionBridgeselectedSpanId={selectedSpanId}onSelectSpan={onSelectSpan}/>- <div className="flex flex-wrap items-center gap-2 border-b border-stone-200 bg-stone-50 px-2 py-1.5 dark:border-stone-800 dark:bg-stone-900">-- <div className="flex rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 p-0.5">- {availableViewModes.map((mode) => (- <button- key={mode.key}- onClick={() => {- userPickedViewRef.current = true;- setViewMode(mode.key);- }}- className={`inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-medium transition-colors ${- viewMode === mode.key- ? "bg-primary text-white"- : "text-stone-500 hover:bg-stone-100 dark:text-stone-400 dark:hover:bg-stone-800"- }`}- >- {mode.icon}- {m[mode.labelKey]}- </button>- ))}- </div>- <div className="ml-auto flex min-w-0 items-center gap-2">- <span className="rounded border border-stone-200 bg-white px-1.5 py-0.5 text-[11px] text-stone-500 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-400">- {isLoading- ? m.OBSERVABILITY_LOADING_SPANS- : m.OBSERVABILITY_SPAN_COUNT(spanCount.toLocaleString())}- </span>+ <nav+ aria-label={m.OBSERVABILITY_SPAN_HIERARCHY}+ className="flex w-9 shrink-0 flex-col items-center gap-0.5 border-r border-stone-200 bg-stone-50 py-1.5 dark:border-stone-800 dark:bg-stone-900"+ >+ {availableViewModes.map((mode) => {+ const selected = viewMode === mode.key;+ const label = m[mode.labelKey];+ return (+ <Tooltip key={mode.key} delayDuration={100}>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-label={label}+ aria-pressed={selected}+ onClick={() => {+ userPickedViewRef.current = true;+ setViewMode(mode.key);+ }}+ className={cn(+ "flex h-8 w-8 items-center justify-center rounded transition-colors",+ selected+ ? "bg-primary text-white"+ : "text-stone-500 hover:bg-stone-100 hover:text-stone-800 dark:text-stone-400 dark:hover:bg-stone-800 dark:hover:text-stone-100"+ )}+ >+ {mode.icon}+ </button>+ </TooltipTrigger>+ <TooltipContent side="right" sideOffset={6}>+ {label}+ </TooltipContent>+ </Tooltip>+ );+ })}+ <div className="mt-auto px-0.5 pb-0.5">+ <Tooltip delayDuration={100}>+ <TooltipTrigger asChild>+ <span className="block max-w-[2rem] truncate text-center text-[9px] font-medium tabular-nums text-stone-500 dark:text-stone-400">+ {isLoading ? "…" : spanCount.toLocaleString()}+ </span>+ </TooltipTrigger>+ <TooltipContent side="right" sideOffset={6}>+ {spanCountLabel}+ </TooltipContent>+ </Tooltip></div>+ </nav>+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">+ {isLoading ? (+ <div className="grid gap-2 p-3">+ {[0, 1, 2, 3].map((item) => (+ <div+ key={item}+ className="h-9 animate-pulse rounded bg-stone-100 dark:bg-stone-900"+ />+ ))}+ </div>+ ) : !record || typedData.err ? (+ <div className="px-3 py-8 text-sm text-stone-400">+ {m.OBSERVABILITY_HIERARCHY_UNAVAILABLE}+ </div>+ ) : (+ <div+ className={cn(+ "min-w-0 bg-stone-50/60 dark:bg-stone-950",+ fill+ ? viewMode === "graph"+ ? "min-h-0 flex-1 overflow-hidden overscroll-contain"+ : "min-h-0 flex-1 overflow-auto"+ : viewMode === "graph"+ ? "h-[520px] overflow-hidden overscroll-contain"+ : "max-h-[520px] overflow-auto"+ )}+ >+ {viewMode === "tree" && (+ <div className="min-w-fit p-3">+ <TreeNode span={record} level={0} />+ </div>+ )}+ {viewMode === "chat" && <ChatView record={record} />}+ {viewMode === "agentloop" && (+ <AgentLoopView record={record} onSelectSpan={onSelectSpan} />+ )}+ {viewMode === "analysis" && (+ <div className="h-full overflow-auto">+ <TraceAiAnalysisPanel spanId={hierarchySpanId} scope="trace" />+ </div>+ )}+ {viewMode === "governance" && (+ <div className="h-full overflow-auto">+ <TraceGovernancePanel+ hierarchySpanId={hierarchySpanId}+ traceId={traceId}+ onSelectSpan={onSelectSpan}+ />+ </div>+ )}+ {viewMode === "timeline" && (+ <div className="min-w-fit p-3">+ <TimelineView record={record} />+ </div>+ )}+ {viewMode === "graph" && <NodeGraph record={record} />}+ </div>+ )}+ {aggregateCost > 0 && (+ <div className="flex shrink-0 items-center gap-2 border-t border-stone-200 bg-stone-50 px-3 py-2 dark:border-stone-800 dark:bg-stone-900/50">+ <DollarSign className="h-3.5 w-3.5 text-stone-500 dark:text-stone-400" />+ <span className="text-xs font-medium text-stone-600 dark:text-stone-400">+ {m.EVALUATION_STAT_TOTAL_COST}+ </span>+ <span className="font-mono text-xs font-semibold text-stone-900 dark:text-stone-100">+ ${aggregateCost.toFixed(10)}+ </span>+ </div>+ )}</div>-- {isLoading ? (- <div className="grid gap-2 p-3">- {[0, 1, 2, 3].map((item) => (- <div- key={item}- className="h-9 animate-pulse rounded bg-stone-100 dark:bg-stone-900"- />- ))}- </div>- ) : !record || typedData.err ? (- <div className="px-3 py-8 text-sm text-stone-400">- {m.OBSERVABILITY_HIERARCHY_UNAVAILABLE}- </div>- ) : (- <div- className={cn(- "bg-stone-50/60 dark:bg-stone-950",- fill- ? viewMode === "graph"- ? "min-h-0 flex-1 overflow-hidden overscroll-contain"- : "min-h-0 flex-1 overflow-auto"- : viewMode === "graph"- ? "h-[520px] overflow-hidden overscroll-contain"- : "max-h-[520px] overflow-auto"- )}- >- {viewMode === "tree" && (- <div className="min-w-fit p-3">- <TreeNode span={record} level={0} />- </div>- )}- {viewMode === "chat" && <ChatView record={record} />}- {viewMode === "analysis" && (- <div className="h-full overflow-auto">- <TraceAiAnalysisPanel spanId={hierarchySpanId} scope="trace" />- </div>- )}- {viewMode === "timeline" && (- <div className="min-w-fit p-3">- <TimelineView record={record} />- </div>- )}- {viewMode === "graph" && <NodeGraph record={record} />}- </div>- )}- {aggregateCost > 0 && (- <div className="flex shrink-0 items-center gap-2 border-t border-stone-200 bg-stone-50 px-3 py-2 dark:border-stone-800 dark:bg-stone-900/50">- <DollarSign className="h-3.5 w-3.5 text-stone-500 dark:text-stone-400" />- <span className="text-xs font-medium text-stone-600 dark:text-stone-400">- Total cost- </span>- <span className="font-mono text-xs font-semibold text-stone-900 dark:text-stone-100">- ${aggregateCost.toFixed(10)}- </span>- </div>- )}</section>);}diff --git a/src/client/src/components/(playground)/observability/trace-detail-page.tsx b/src/client/src/components/(playground)/observability/trace-detail-page.tsxindex 4342a5d3..cd96067e 100644--- a/src/client/src/components/(playground)/observability/trace-detail-page.tsx+++ b/src/client/src/components/(playground)/observability/trace-detail-page.tsx@@ -172,7 +172,10 @@ function CostStat({}) {const m = getMessage();const currentEnvironment = useRootStore(getCurrentProjectEnvironment);- const hasCost = !!costValue && costValue !== "-";+ const hasCost =+ !!costValue &&+ costValue !== "-" &&+ costValue !== m.GOVERNANCE_COST_NOT_REPORTED;const canRecalculate = hasModel && !!spanId;const { fireRequest, isLoading } = useFetchWrapper<{success: boolean;@@ -743,7 +746,7 @@ export function TraceDetailView({? [{id: "evaluations",- label: "Evaluations",+ label: m.EVALUATION_RESULTS,content: (<Evaluationstrace={trace}@@ -756,6 +759,7 @@ export function TraceDetailView({];const detailTabs = useMemo(() => buildObjectTabs(raw, {+ excludeKeys: ["agentLoop"],labelOverrides: {SpanAttributes: "Span Attributes",ResourceAttributes: "Resource Attributes",@@ -869,6 +873,9 @@ export function TraceDetailView({const tokensValue = codingTokensValue ?? trace?.totalTokens;const costValue =codingCostValue ?? (trace?.cost && trace.cost !== "-" ? `$${trace.cost}` : undefined);+ const displayCostValue =+ costValue ||+ (isCodingAgentTrace ? m.GOVERNANCE_COST_NOT_REPORTED : undefined);const durationValue =codingDurationValue ||(trace ? `${parseFloat(trace.requestDuration).toFixed(3)}s` : "");@@ -878,6 +885,7 @@ export function TraceDetailView({<DetailShelltitle={title}compact+ fillleadingActions={variant === "page" ? (<Button@@ -900,7 +908,7 @@ export function TraceDetailView({<Stat icon={<Clock className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_DURATION} value={durationValue} /><Stat icon={<Zap className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_TOKENS} value={tokensValue} /><CostStat- costValue={costValue}+ costValue={displayCostValue}spanId={trace.spanId}traceId={knownTraceId}hasModel={!!modelValue}@@ -938,8 +946,8 @@ export function TraceDetailView({}>{trace && (- <>- <div className="flex flex-wrap gap-1.5">+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-hidden">+ <div className="flex shrink-0 flex-wrap gap-1.5"><MetaPill label={m.OBSERVABILITY_TRACE_ID} value={trace.id} /><MetaPill label={m.OBSERVABILITY_SPAN_ID} value={trace.spanId} />{!isCodingAgentTrace && (@@ -1004,10 +1012,10 @@ export function TraceDetailView({)}<GenerationHealthNote spanAttributes={spanAttributes} /><AgentLoopNote hit={asAgentLoopHit(raw?.agentLoop)} />- <div className="hidden h-[min(860px,calc(100vh-12rem))] min-h-[620px] overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950 lg:block">+ <div className="hidden min-h-0 flex-1 overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950 lg:block"><ResizablePanelGroup direction="horizontal" className="h-full"><ResizablePanel defaultSize={48} minSize={32} maxSize={68}>- <div className="h-full min-h-0 p-2">+ <div className="h-full min-h-0 overflow-hidden p-2"><SpanHierarchyExplorerhierarchySpanId={hierarchySpanIdRef.current}selectedSpanId={selectedSpanId}@@ -1029,7 +1037,7 @@ export function TraceDetailView({</ResizablePanel></ResizablePanelGroup></div>- <div className="grid gap-3 lg:hidden">+ <div className="grid min-h-0 flex-1 gap-3 overflow-auto lg:hidden"><SpanHierarchyExplorerhierarchySpanId={hierarchySpanIdRef.current}selectedSpanId={selectedSpanId}@@ -1042,7 +1050,7 @@ export function TraceDetailView({extraTabsPlacement="before"/></div>- </>+ </div>)}</DetailShell>);diff --git a/src/client/src/components/(playground)/observability/trace-governance-panel.tsx b/src/client/src/components/(playground)/observability/trace-governance-panel.tsxnew file mode 100644index 00000000..e9706c62--- /dev/null+++ b/src/client/src/components/(playground)/observability/trace-governance-panel.tsx@@ -0,0 +1,784 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import Link from "next/link";+import {+ AlertTriangle,+ ChevronDown,+ ChevronRight,+ Copy,+ Download,+ RefreshCw,+ ShieldAlert,+ ShieldCheck,+ ShieldQuestion,+ Sparkles,+} from "lucide-react";+import { usePostHog } from "posthog-js/react";+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";+import getMessage from "@/constants/messages";+import { CLIENT_EVENTS } from "@/constants/events";+import { governanceReportEventProps } from "@/helpers/client/governance-analytics";+import { getCurrentProjectEnvironment } from "@/selectors/project";+import { useRootStore } from "@/store";+import { cn } from "@/lib/utils";+import type {+ GovernanceFinding,+ GovernanceFindingCategory,+ GovernanceSeverity,+ TraceGovernanceReport,+} from "@/types/governance-report";+import {+ buildAgentLoopKnowledgeRule,+ buildAgentLoopOtterPrompt,+} from "@/lib/platform/governance/agent-loop-fix";+import AskOtterPanel from "@/components/(playground)/chat/ask-otter-panel";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";++type SeverityFilter = "all" | GovernanceSeverity;++const FINDING_PAGE_SIZE = 20;++function riskLabel(level: TraceGovernanceReport["risk_level"]): string {+ const m = getMessage();+ switch (level) {+ case "critical":+ return m.GOVERNANCE_RISK_CRITICAL;+ case "major":+ return m.GOVERNANCE_RISK_MAJOR;+ case "minor":+ return m.GOVERNANCE_RISK_MINOR;+ case "info":+ return m.GOVERNANCE_RISK_INFO;+ default:+ return m.GOVERNANCE_RISK_NONE;+ }+}++function riskIcon(level: TraceGovernanceReport["risk_level"]) {+ switch (level) {+ case "critical":+ case "major":+ return <ShieldAlert className="h-3.5 w-3.5" />;+ case "minor":+ case "info":+ return <ShieldQuestion className="h-3.5 w-3.5" />;+ default:+ return <ShieldCheck className="h-3.5 w-3.5" />;+ }+}++/** Left border accent only — keeps the panel body neutral. */+function severityBorder(severity: GovernanceSeverity | "none"): string {+ switch (severity) {+ case "critical":+ return "border-l-red-500";+ case "major":+ return "border-l-amber-500";+ case "minor":+ return "border-l-yellow-400";+ case "info":+ return "border-l-stone-400";+ default:+ return "border-l-stone-300 dark:border-l-stone-600";+ }+}++/** Compact tint for finding headers / risk badge only. */+function severityHeader(severity: GovernanceSeverity): string {+ switch (severity) {+ case "critical":+ return "bg-red-50 text-red-900 dark:bg-red-950/40 dark:text-red-100";+ case "major":+ return "bg-amber-50 text-amber-950 dark:bg-amber-950/40 dark:text-amber-100";+ case "minor":+ return "bg-yellow-50/80 text-yellow-950 dark:bg-yellow-950/30 dark:text-yellow-100";+ default:+ return "bg-stone-50 text-stone-800 dark:bg-stone-900/60 dark:text-stone-200";+ }+}++function severityBadge(severity: GovernanceSeverity | "none"): string {+ switch (severity) {+ case "critical":+ return "bg-red-100 text-red-800 dark:bg-red-950/60 dark:text-red-200";+ case "major":+ return "bg-amber-100 text-amber-900 dark:bg-amber-950/60 dark:text-amber-200";+ case "minor":+ return "bg-yellow-100 text-yellow-900 dark:bg-yellow-950/50 dark:text-yellow-200";+ case "info":+ return "bg-stone-100 text-stone-700 dark:bg-stone-800 dark:text-stone-300";+ default:+ return "bg-stone-100 text-stone-600 dark:bg-stone-800 dark:text-stone-300";+ }+}++function categoryLabel(category: GovernanceFindingCategory): string {+ const m = getMessage();+ switch (category) {+ case "agent_loop":+ return m.GOVERNANCE_CATEGORY_AGENT_LOOP;+ case "policy":+ return m.GOVERNANCE_CATEGORY_POLICY;+ case "coding_agent":+ return m.GOVERNANCE_CATEGORY_CODING_AGENT;+ case "span_error":+ return m.GOVERNANCE_CATEGORY_SPAN_ERROR;+ case "generation_health":+ return m.GOVERNANCE_CATEGORY_GENERATION_HEALTH;+ case "harness":+ return m.GOVERNANCE_CATEGORY_HARNESS;+ case "evaluation":+ return m.GOVERNANCE_CATEGORY_EVALUATION;+ default:+ return category;+ }+}++function formatDurationMs(ms: number): string {+ if (!Number.isFinite(ms) || ms <= 0) return "0ms";+ if (ms < 1000) return `${Math.round(ms)}ms`;+ if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;+ const minutes = Math.floor(ms / 60_000);+ const seconds = Math.round((ms % 60_000) / 1000);+ return `${minutes}m ${seconds}s`;+}++function FindingCard({+ finding,+ onSelectSpan,+}: {+ finding: GovernanceFinding;+ onSelectSpan?: (spanId: string) => void;+}) {+ const m = getMessage();+ const [open, setOpen] = useState(false);+ const [askOtterOpen, setAskOtterOpen] = useState(false);+ const [copiedRule, setCopiedRule] = useState(false);+ const isAgentLoop = finding.category === "agent_loop";+ const evidenceEntries = Object.entries(finding.evidence || {}).filter(+ ([key, value]) => {+ if (value === undefined || value === "") return false;+ if (+ (key === "wasted_tokens" || key === "wasted_cost") &&+ finding.evidence?.usage_reported === false+ ) {+ return false;+ }+ return true;+ }+ );++ const copyAgentRule = useCallback(async () => {+ const text = buildAgentLoopKnowledgeRule(finding);+ try {+ await navigator.clipboard.writeText(text);+ setCopiedRule(true);+ window.setTimeout(() => setCopiedRule(false), 2000);+ } catch {+ setCopiedRule(false);+ }+ }, [finding]);++ return (+ <div+ className={cn(+ "overflow-hidden rounded-md border border-stone-200 border-l-4 bg-white dark:border-stone-800 dark:bg-stone-950",+ severityBorder(finding.severity)+ )}+ >+ <button+ type="button"+ className={cn(+ "flex w-full items-start gap-2 px-2.5 py-2 text-left",+ severityHeader(finding.severity)+ )}+ onClick={() => setOpen((value) => !value)}+ aria-expanded={open}+ >+ {open ? (+ <ChevronDown className="mt-0.5 h-3.5 w-3.5 shrink-0 opacity-70" />+ ) : (+ <ChevronRight className="mt-0.5 h-3.5 w-3.5 shrink-0 opacity-70" />+ )}+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 opacity-80" />+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-1.5">+ <span className="text-[10px] font-medium uppercase tracking-wide opacity-80">+ {categoryLabel(finding.category)}+ </span>+ <span+ className={cn(+ "rounded px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide",+ severityBadge(finding.severity)+ )}+ >+ {finding.severity}+ </span>+ </div>+ <p className="mt-0.5 text-xs font-medium text-stone-900 dark:text-stone-100">+ {finding.summary}+ </p>+ {finding.resource && (+ <p className="mt-0.5 truncate font-mono text-[11px] text-stone-600 dark:text-stone-400">+ {finding.resource}+ </p>+ )}+ </div>+ </button>+ {open && (+ <div className="space-y-2 border-t border-stone-200 bg-white px-2.5 py-2 text-[11px] text-stone-700 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300">+ <p>{finding.detail}</p>+ {finding.remediation && (+ <div>+ <p className="font-medium text-stone-500 dark:text-stone-400">+ {m.GOVERNANCE_FINDING_FIX}+ </p>+ <p className="mt-0.5">{finding.remediation}</p>+ {isAgentLoop && (+ <div className="mt-1.5 flex flex-wrap gap-1.5">+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="h-7 gap-1 px-2 text-[10px]"+ onClick={copyAgentRule}+ >+ <Copy className="h-3 w-3" />+ {copiedRule+ ? m.GOVERNANCE_COPY_AGENT_RULE_DONE+ : m.GOVERNANCE_COPY_AGENT_RULE}+ </Button>+ <Button+ type="button"+ variant={askOtterOpen ? "secondary" : "outline"}+ size="sm"+ className="h-7 gap-1 px-2 text-[10px]"+ onClick={() => setAskOtterOpen((value) => !value)}+ >+ <Sparkles className="h-3 w-3" />+ {askOtterOpen+ ? m.GOVERNANCE_ASK_OTTER_HIDE+ : m.GOVERNANCE_ASK_OTTER_FIX}+ </Button>+ </div>+ )}+ </div>+ )}+ {isAgentLoop && askOtterOpen && (+ <div className="overflow-hidden rounded-md border border-stone-200 dark:border-stone-800">+ <AskOtterPanel+ layout="dock"+ defaultQuestion={m.GOVERNANCE_ASK_OTTER_DEFAULT_QUESTION}+ contextLabel={+ typeof finding.evidence?.tool_name === "string"+ ? finding.evidence.tool_name+ : finding.resource || undefined+ }+ copy={{+ title: m.GOVERNANCE_ASK_OTTER_TITLE,+ empty: m.GOVERNANCE_ASK_OTTER_EMPTY,+ placeholder: m.GOVERNANCE_ASK_OTTER_PLACEHOLDER,+ hint: m.GOVERNANCE_ASK_OTTER_HINT,+ send: m.GOVERNANCE_ASK_OTTER_SEND,+ conversationTitle: m.GOVERNANCE_ASK_OTTER_TITLE,+ }}+ buildPrompt={(question) =>+ buildAgentLoopOtterPrompt(question, finding)+ }+ />+ </div>+ )}+ {evidenceEntries.length > 0 && (+ <p className="font-mono text-[10px] text-stone-500 dark:text-stone-400">+ {evidenceEntries+ .map(([key, value]) => `${key}=${String(value)}`)+ .join(" · ")}+ </p>+ )}+ {finding.span_refs.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {finding.span_refs.slice(0, 8).map((spanId) => (+ <Button+ key={spanId}+ type="button"+ variant="outline"+ size="sm"+ className="h-6 px-2 font-mono text-[10px]"+ onClick={() => onSelectSpan?.(spanId)}+ >+ {spanId.slice(0, 8)}+ </Button>+ ))}+ {finding.span_refs.length > 8 && (+ <span className="self-center text-[10px] text-stone-500">+ +{finding.span_refs.length - 8}+ </span>+ )}+ </div>+ )}+ </div>+ )}+ </div>+ );+}++function GovernanceLoadingSkeleton() {+ return (+ <div className="flex flex-col gap-2 p-3">+ <Skeleton className="h-10 w-full rounded-md" />+ <Skeleton className="h-16 w-full rounded-md" />+ <Skeleton className="h-20 w-full rounded-md" />+ </div>+ );+}++export default function TraceGovernancePanel({+ hierarchySpanId,+ traceId,+ onSelectSpan,+}: {+ hierarchySpanId: string;+ traceId?: string;+ onSelectSpan?: (spanId: string) => void;+}) {+ const m = getMessage();+ const posthog = usePostHog();+ const environment = useRootStore(getCurrentProjectEnvironment);+ const { fireRequest, isLoading, data, error, reset } = useFetchWrapper();+ const [severityFilter, setSeverityFilter] = useState<SeverityFilter>("all");+ const [visibleCount, setVisibleCount] = useState(FINDING_PAGE_SIZE);++ const errorMessage = useMemo(() => {+ if (!error) return "";+ if (typeof error === "string") return error;+ if (typeof error === "object" && error !== null) {+ const record = error as Record<string, unknown>;+ return String(record.message || record.err || record.error || "");+ }+ return String(error);+ }, [error]);++ const load = useCallback(() => {+ const params = new URLSearchParams();+ if (traceId) params.set("traceId", traceId);+ // Explicit query param keeps connector-signal scoping obvious and avoids+ // reusing another environment's cached governance report.+ if (environment) params.set("environment", environment);+ const qs = params.size ? `?${params.toString()}` : "";+ fireRequest({+ requestType: "GET",+ url: `/api/telemetry/request/span/${hierarchySpanId}/governance${qs}`,+ });+ }, [environment, fireRequest, hierarchySpanId, traceId]);++ useEffect(() => {+ posthog?.capture(CLIENT_EVENTS.GOVERNANCE_TAB_VIEWED, {+ span_id: hierarchySpanId,+ trace_id: traceId,+ environment,+ });+ }, [posthog, hierarchySpanId, traceId, environment]);++ useEffect(() => {+ // Drop previous environment's report so production findings never linger+ // after switching connector environment.+ reset();+ }, [environment, reset]);++ useEffect(() => {+ load();+ }, [load]);++ useEffect(() => {+ setVisibleCount(FINDING_PAGE_SIZE);+ }, [severityFilter, hierarchySpanId, traceId, environment]);++ const report = (data as { report?: TraceGovernanceReport } | undefined)?.report;++ useEffect(() => {+ if (!report) return;+ posthog?.capture(+ CLIENT_EVENTS.GOVERNANCE_REPORT_LOADED,+ governanceReportEventProps({+ spanId: hierarchySpanId,+ traceId: report.trace_id,+ riskLevel: report.risk_level,+ findingCount: report.finding_count,+ ruleMatchCount: report.rule_match_count,+ evaluationCount: report.evaluations.length,+ analysisLimited: report.analysis_limited,+ })+ );+ }, [posthog, hierarchySpanId, report]);++ useEffect(() => {+ if (!error) return;+ posthog?.capture(CLIENT_EVENTS.GOVERNANCE_REPORT_LOAD_FAILURE, {+ span_id: hierarchySpanId,+ trace_id: traceId,+ });+ }, [posthog, error, hierarchySpanId, traceId]);++ const harnessRows = useMemo(() => {+ if (!report) return [];+ const h = report.harness;+ const costValue =+ h.cost_reported || h.total_cost_usd > 0+ ? `$${h.total_cost_usd.toFixed(4)}`+ : m.GOVERNANCE_COST_NOT_REPORTED;+ return [+ { label: m.GOVERNANCE_HARNESS_SPANS, value: h.span_count.toLocaleString() },+ { label: m.GOVERNANCE_HARNESS_TOOLS, value: h.tool_call_count.toLocaleString() },+ { label: m.GOVERNANCE_HARNESS_ERRORS, value: h.error_count.toLocaleString() },+ { label: m.GOVERNANCE_HARNESS_COST, value: costValue },+ {+ label: m.GOVERNANCE_HARNESS_TOKENS,+ value:+ h.total_tokens > 0+ ? h.total_tokens.toLocaleString()+ : m.GOVERNANCE_USAGE_NOT_REPORTED,+ },+ {+ label: m.GOVERNANCE_HARNESS_DURATION,+ value: formatDurationMs(h.total_duration_ms),+ },+ ];+ }, [report, m]);++ const filteredSecurity = useMemo(() => {+ if (!report) return [];+ const sorted = [...report.security].sort((a, b) => {+ const order: Record<GovernanceSeverity, number> = {+ critical: 0,+ major: 1,+ minor: 2,+ info: 3,+ };+ return order[a.severity] - order[b.severity];+ });+ if (severityFilter === "all") return sorted;+ return sorted.filter((finding) => finding.severity === severityFilter);+ }, [report, severityFilter]);++ const visibleFindings = filteredSecurity.slice(0, visibleCount);++ const severityCounts = useMemo(() => {+ const counts: Record<SeverityFilter, number> = {+ all: report?.security.length || 0,+ critical: 0,+ major: 0,+ minor: 0,+ info: 0,+ };+ for (const finding of report?.security || []) {+ counts[finding.severity] += 1;+ }+ return counts;+ }, [report]);++ const exportReport = useCallback(() => {+ if (!report) return;+ const blob = new Blob([JSON.stringify(report, null, 2)], {+ type: "application/json",+ });+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = `governance-${report.trace_id || hierarchySpanId}.json`;+ anchor.click();+ URL.revokeObjectURL(url);+ }, [report, hierarchySpanId]);++ const severityFilters: Array<{ key: SeverityFilter; label: string }> = [+ { key: "all", label: m.GOVERNANCE_FILTER_ALL },+ { key: "critical", label: m.GOVERNANCE_FILTER_CRITICAL },+ { key: "major", label: m.GOVERNANCE_FILTER_MAJOR },+ { key: "minor", label: m.GOVERNANCE_FILTER_MINOR },+ { key: "info", label: m.GOVERNANCE_FILTER_INFO },+ ];++ if (isLoading && !report) {+ return <GovernanceLoadingSkeleton />;+ }++ if (error && !report) {+ return (+ <div className="flex flex-col items-center gap-3 px-3 py-8">+ <div className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-200">+ <p>{m.GOVERNANCE_LOAD_FAILED}</p>+ {errorMessage && (+ <p className="mt-1 text-xs opacity-90">+ {m.GOVERNANCE_LOAD_FAILED_DETAIL.replace("{detail}", errorMessage)}+ </p>+ )}+ </div>+ <Button type="button" variant="outline" size="sm" onClick={load}>+ {m.GOVERNANCE_RETRY}+ </Button>+ </div>+ );+ }++ if (!report) {+ return (+ <div className="py-8 text-center text-sm text-stone-500">+ <p>{m.GOVERNANCE_LOADING_HINT}</p>+ </div>+ );+ }++ const hasSignals =+ report.finding_count > 0 ||+ report.rule_match_count > 0 ||+ report.evaluations.length > 0;+ const riskLevel =+ report.risk_level === "none" ? ("info" as const) : report.risk_level;++ return (+ <div className="flex flex-col gap-3 p-3 text-sm">+ <div+ className={cn(+ "flex items-start gap-2 rounded-md border border-stone-200 border-l-4 bg-white px-2.5 py-2 dark:border-stone-800 dark:bg-stone-950",+ severityBorder(riskLevel)+ )}+ >+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <span+ className={cn(+ "inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] font-medium",+ severityBadge(riskLevel)+ )}+ >+ {riskIcon(report.risk_level)}+ {riskLabel(report.risk_level)}+ </span>+ <span className="text-xs text-stone-600 dark:text-stone-400">+ {report.summary}+ </span>+ </div>+ {report.analysis_limited && (+ <p className="mt-1 text-[11px] text-stone-500">+ {m.GOVERNANCE_TRUNCATED_NOTE}+ </p>+ )}+ {report.harness.agent_loop && (+ <p className="mt-1 text-[11px] text-stone-600 dark:text-stone-400">+ {m.GOVERNANCE_AGENT_LOOP_BANNER.replace(+ "{tool}",+ report.harness.agent_loop.tool_name+ ).replace("{count}", String(report.harness.agent_loop.count))}+ </p>+ )}+ </div>+ <div className="flex shrink-0 gap-1">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-7 px-2"+ onClick={exportReport}+ aria-label={m.GOVERNANCE_EXPORT_JSON}+ title={m.GOVERNANCE_EXPORT_JSON}+ >+ <Download className="h-3.5 w-3.5" />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-7 px-2"+ onClick={load}+ aria-label={m.GOVERNANCE_REFRESH}+ title={m.GOVERNANCE_REFRESH}+ >+ <RefreshCw className="h-3.5 w-3.5" />+ </Button>+ </div>+ </div>++ <section>+ <dl className="flex flex-wrap gap-x-5 gap-y-2 rounded-md border border-stone-200 px-2.5 py-2 dark:border-stone-800">+ {harnessRows.map((row) => (+ <div key={row.label} className="min-w-0">+ <dt className="text-[10px] uppercase tracking-wide text-stone-500">+ {row.label}+ </dt>+ <dd className="mt-0.5 font-mono text-xs font-semibold tabular-nums text-stone-900 dark:text-stone-100">+ {row.value}+ </dd>+ </div>+ ))}+ </dl>+ {!report.harness.cost_reported && report.harness.total_tokens > 0 && (+ <p className="mt-1.5 text-[11px] text-stone-500">+ {m.GOVERNANCE_COST_CURSOR_HINT}+ </p>+ )}+ </section>++ {report.rules.length > 0 && (+ <section>+ <h3 className="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-stone-500">+ {m.GOVERNANCE_SECTION_RULES} ({report.rules.length})+ </h3>+ <div className="divide-y divide-stone-200 overflow-hidden rounded-md border border-stone-200 dark:divide-stone-800 dark:border-stone-800">+ {report.rules.slice(0, 20).map((rule, index) => (+ <div+ key={`${rule.rule_id}:${rule.span_id}:${index}`}+ className="flex flex-wrap items-center gap-2 px-2.5 py-1.5 text-xs"+ >+ <span className="font-medium text-stone-900 dark:text-stone-100">+ {rule.rule_name || rule.rule_id}+ </span>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="h-6 px-2 font-mono text-[10px]"+ onClick={() => onSelectSpan?.(rule.span_id)}+ >+ {rule.span_id.slice(0, 8)}+ </Button>+ <Link+ href={`/rule-engine/${rule.rule_id}`}+ className="text-[10px] text-primary hover:underline"+ >+ {m.GOVERNANCE_RULE_LINK}+ </Link>+ </div>+ ))}+ </div>+ </section>+ )}++ {report.security.length > 0 && (+ <section>+ <div className="mb-1.5 flex flex-wrap items-center justify-between gap-2">+ <h3 className="text-[11px] font-semibold uppercase tracking-wide text-stone-500">+ {m.GOVERNANCE_SECTION_SECURITY} ({report.security.length})+ </h3>+ <div className="flex flex-wrap gap-1">+ {severityFilters.map((filter) => {+ if (+ filter.key !== "all" &&+ severityCounts[filter.key] === 0+ ) {+ return null;+ }+ return (+ <button+ key={filter.key}+ type="button"+ className={cn(+ "rounded px-1.5 py-0.5 text-[10px] font-medium",+ severityFilter === filter.key+ ? "bg-stone-900 text-white dark:bg-stone-100 dark:text-stone-900"+ : "bg-stone-100 text-stone-600 hover:bg-stone-200 dark:bg-stone-900 dark:text-stone-300 dark:hover:bg-stone-800"+ )}+ onClick={() => setSeverityFilter(filter.key)}+ >+ {filter.label}+ {filter.key !== "all"+ ? ` ${severityCounts[filter.key]}`+ : ""}+ </button>+ );+ })}+ </div>+ </div>+ {filteredSecurity.length === 0 ? (+ <p className="text-xs text-stone-500">{m.GOVERNANCE_FILTER_EMPTY}</p>+ ) : (+ <>+ <div className="space-y-1.5">+ {visibleFindings.map((finding) => (+ <FindingCard+ key={finding.id}+ finding={finding}+ onSelectSpan={onSelectSpan}+ />+ ))}+ </div>+ {filteredSecurity.length > visibleCount && (+ <div className="mt-2 flex items-center justify-between gap-2">+ <p className="text-[11px] text-stone-500">+ {m.GOVERNANCE_SHOWING_OF.replace(+ "{shown}",+ String(visibleCount)+ ).replace("{total}", String(filteredSecurity.length))}+ </p>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="h-7 text-xs"+ onClick={() =>+ setVisibleCount((count) => count + FINDING_PAGE_SIZE)+ }+ >+ {m.GOVERNANCE_SHOW_MORE}+ </Button>+ </div>+ )}+ </>+ )}+ </section>+ )}++ {report.evaluations.length > 0 && (+ <section>+ <div className="mb-1.5 flex flex-wrap items-center justify-between gap-2">+ <h3 className="text-[11px] font-semibold uppercase tracking-wide text-stone-500">+ {m.GOVERNANCE_SECTION_EVALUATIONS} ({report.evaluations.length})+ </h3>+ <Link+ href="/evaluations"+ className="text-[10px] text-primary hover:underline"+ >+ {m.GOVERNANCE_EVALUATIONS_LINK}+ </Link>+ </div>+ <div className="divide-y divide-stone-200 overflow-hidden rounded-md border border-stone-200 dark:divide-stone-800 dark:border-stone-800">+ {report.evaluations.slice(0, 20).map((row, index) => (+ <div+ key={`${row.span_id}:${row.evaluation_type}:${index}`}+ className="flex flex-wrap items-center gap-2 px-2.5 py-1.5 text-xs"+ >+ <span className="font-medium text-stone-900 dark:text-stone-100">+ {row.evaluation_type}+ </span>+ {row.verdict && (+ <span className="text-stone-500">{row.verdict}</span>+ )}+ {typeof row.score === "number" && (+ <span className="text-stone-500">+ {m.GOVERNANCE_EVAL_SCORE_PREFIX} {row.score}+ </span>+ )}+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="h-6 px-2 font-mono text-[10px]"+ onClick={() => onSelectSpan?.(row.span_id)}+ >+ {row.span_id.slice(0, 8)}+ </Button>+ </div>+ ))}+ </div>+ </section>+ )}++ {!hasSignals && (+ <div className="py-6 text-center text-sm text-stone-500">+ <p className="font-medium">{m.GOVERNANCE_EMPTY_TITLE}</p>+ <p className="mt-1 text-xs">{m.GOVERNANCE_EMPTY_DESCRIPTION}</p>+ </div>+ )}+ </div>+ );+}diff --git a/src/client/src/constants/events.ts b/src/client/src/constants/events.tsindex 70fc7bfc..bf3d0e5e 100644--- a/src/client/src/constants/events.ts+++ b/src/client/src/constants/events.ts@@ -97,6 +97,9 @@ export const CLIENT_EVENTS = {AI_ANALYSIS_VIEWED: "AI_ANALYSIS_VIEWED",AI_ANALYSIS_RUN_SUCCESS: "AI_ANALYSIS_RUN_SUCCESS",AI_ANALYSIS_RUN_FAILURE: "AI_ANALYSIS_RUN_FAILURE",+ GOVERNANCE_TAB_VIEWED: "GOVERNANCE_TAB_VIEWED",+ GOVERNANCE_REPORT_LOADED: "GOVERNANCE_REPORT_LOADED",+ GOVERNANCE_REPORT_LOAD_FAILURE: "GOVERNANCE_REPORT_LOAD_FAILURE",// organisation — opaque organisation_id only; PostHog Groups// (`organisation`) power MAO. Never send org names or emails.@@ -303,6 +306,8 @@ export const SERVER_EVENTS = {RULE_FIELD_VALUES_FAILURE: "RULE_FIELD_VALUES_FAILURE",AI_ANALYSIS_GET_SUCCESS: "AI_ANALYSIS_GET_SUCCESS",AI_ANALYSIS_GET_FAILURE: "AI_ANALYSIS_GET_FAILURE",+ GOVERNANCE_REPORT_SUCCESS: "GOVERNANCE_REPORT_SUCCESS",+ GOVERNANCE_REPORT_FAILURE: "GOVERNANCE_REPORT_FAILURE",EVALUATION_GET_SUCCESS: "EVALUATION_GET_SUCCESS",EVALUATION_GET_FAILURE: "EVALUATION_GET_FAILURE",DASHBOARD_QUERY_RUN_SUCCESS: "DASHBOARD_QUERY_RUN_SUCCESS",diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.tsindex bd318b25..45ab3718 100644--- a/src/client/src/constants/messages/en.ts+++ b/src/client/src/constants/messages/en.ts@@ -372,6 +372,10 @@ export const OBSERVABILITY_HIERARCHY_UNAVAILABLE ="Span hierarchy is not available for this span.";export const OBSERVABILITY_TREE = "Tree";export const OBSERVABILITY_CHAT = "Chat";+export const OBSERVABILITY_AGENT_LOOP = "Agent Loop";+export const OBSERVABILITY_AGENT_LOOP_EMPTY =+ "No repeated identical tool calls on this hierarchy.";+export const OBSERVABILITY_AGENT_LOOP_SPANS = "Open looping spans";export const OBSERVABILITY_CHAT_FILTER_CONVERSATION = "Conversation";export const OBSERVABILITY_CHAT_FILTER_ALL = "All activity";export const OBSERVABILITY_CHAT_SUMMARY = (@@ -392,6 +396,7 @@ export const OBSERVABILITY_SPAN_NAME_EXAMPLE = "e.g. SpanName";export const OBSERVABILITY_ATTRIBUTE_KEY_EXAMPLE = "e.g. gen_ai.system";export const OBSERVABILITY_FULL_SCREEN = "Full screen";export const OBSERVABILITY_EVALUATION_PANEL = "Evaluation";+export const OBSERVABILITY_SPAN_DETAILS = "Span details";export const OBSERVABILITY_ROW = "row";export const OBSERVABILITY_TRACE = "trace";export const OBSERVABILITY_SPAN = "span";@@ -1988,6 +1993,241 @@ export const TRACE_AI_ANALYZE = "Analyze";export const TRACE_AI_RERUN = "Rerun";export const TRACE_AI_ANALYZE_TRACE = "Analyze Trace";export const TRACE_AI_TAB_TITLE = "AI Analysis";+export const GOVERNANCE_TAB_TITLE = "Governance";+export const GOVERNANCE_LOADING = "Building governance report…";+export const GOVERNANCE_LOAD_FAILED = "Failed to load governance report";+export const GOVERNANCE_LOAD_FAILED_DETAIL = "{detail}";+export const GOVERNANCE_EMPTY_TITLE = "No governance signals";+export const GOVERNANCE_EMPTY_DESCRIPTION =+ "This trace hierarchy has no rule matches, security findings, or evaluation results.";+export const GOVERNANCE_LOADING_HINT = "Building the governance report from this hierarchy…";+export const GOVERNANCE_SECTION_SUMMARY = "Summary";+export const GOVERNANCE_SECTION_HARNESS = "Session metrics";+export const GOVERNANCE_SECTION_RULES = "Matched rules";+export const GOVERNANCE_SECTION_SECURITY = "Security & policy";+export const GOVERNANCE_SECTION_EVALUATIONS = "Evaluations";+export const GOVERNANCE_RISK_NONE = "No elevated risk";+export const GOVERNANCE_RISK_INFO = "Informational";+export const GOVERNANCE_RISK_MINOR = "Minor risk";+export const GOVERNANCE_RISK_MAJOR = "Major risk";+export const GOVERNANCE_RISK_CRITICAL = "Critical risk";+export const GOVERNANCE_SUMMARY_CLEAN =+ "No security findings, rule matches, or evaluation flags on this hierarchy.";+export const GOVERNANCE_SUMMARY_FINDINGS = "{count} finding(s)";+export const GOVERNANCE_SUMMARY_RULES = "{count} rule match(es)";+export const GOVERNANCE_SUMMARY_EVALS = "{count} evaluation row(s)";+export const GOVERNANCE_SUMMARY_MIXED = "Governance signals detected on this trace.";+export const GOVERNANCE_FINDING_SPAN_ERROR_SUMMARY = "Span error: {name}";+export const GOVERNANCE_FINDING_SPAN_ERROR_DETAIL =+ "This span completed with an error status in the hierarchy.";+export const GOVERNANCE_FINDING_CLASSIFICATION_DISPUTED_SUMMARY =+ "Classification disputed";+export const GOVERNANCE_FINDING_CLASSIFICATION_DISPUTED_DETAIL =+ "A coding-agent session classification was disputed and may need review.";+export const GOVERNANCE_FINDING_CLASSIFICATION_PERSONAL_SUMMARY =+ "Personal-use classification";+export const GOVERNANCE_FINDING_CLASSIFICATION_PERSONAL_DETAIL =+ "This session was classified as personal use on a coding-agent span.";+export const GOVERNANCE_FINDING_PERMISSION_MODE_SUMMARY =+ "Permission mode: {mode}";+export const GOVERNANCE_FINDING_PERMISSION_MODE_DETAIL =+ "The coding agent reported a non-default permission mode for this session.";+export const GOVERNANCE_FINDING_AGENT_LOOP_SUMMARY =+ "Tool loop: {tool} × {count}";+export const GOVERNANCE_FINDING_AGENT_LOOP_DETAIL =+ "The same tool was called repeatedly with identical arguments, wasting {wasted_tokens} tokens (~${wasted_cost}).";+export const GOVERNANCE_FINDING_AGENT_LOOP_DETAIL_NO_USAGE =+ "The same tool was called {count} times with identical arguments. Cursor/tool spans do not carry per-call token or USD usage, so waste is measured by repeats{duration_suffix}.";+export const GOVERNANCE_FINDING_AGENT_LOOP_DURATION_SUFFIX =+ " (~{duration} of redundant tool time)";+export const GOVERNANCE_USAGE_NOT_REPORTED = "not reported";+export const GOVERNANCE_COST_NOT_REPORTED = "Not reported";+export const GOVERNANCE_HARNESS_TOKENS = "Tokens";+export const GOVERNANCE_COST_CURSOR_HINT =+ "No USD cost on these spans. Cursor never sends cost; tokens (when present) come from session/stop events, not from tool.call spans.";+export const GOVERNANCE_FINDING_TOOL_BURST_SUMMARY =+ "High tool volume ({count} tool spans)";+export const GOVERNANCE_FINDING_TOOL_BURST_DETAIL =+ "This hierarchy executed many tool spans, which can indicate runaway agent behavior.";+export const GOVERNANCE_FINDING_WIDE_BRANCH_SUMMARY = "Wide span branch";+export const GOVERNANCE_FINDING_WIDE_BRANCH_DETAIL =+ "One or more spans fan out into many child operations.";+export const GOVERNANCE_REMEDIATION_SPAN_ERROR =+ "Open the span details and Events tab, fix the failing operation, then re-run the agent step that produced the error.";+export const GOVERNANCE_REMEDIATION_GENERATION_HEALTH =+ "Inspect finish reasons and token limits on the span; raise max tokens or adjust the prompt when outputs are truncated or empty.";+export const GOVERNANCE_REMEDIATION_MODEL_SWAP =+ "Pin the requested model in the agent config, or accept the served model only if the swap is intentional.";+export const GOVERNANCE_REMEDIATION_PERMISSION_MODE =+ "Switch the coding-agent permission mode back to default, plan, or acceptEdits unless elevated access is intentional for this session.";+export const GOVERNANCE_REMEDIATION_CLASSIFICATION =+ "Confirm the session classification in Coding Agents and correct it if the dispute or personal tag is wrong.";+export const GOVERNANCE_REMEDIATION_AGENT_LOOP =+ "Coding agents like Cursor often cannot be interrupted mid-run. Add a durable rule to agent knowledge (AGENTS.md, .cursor/rules, or a skill) that forbids repeating this tool with identical arguments—require different path/args, a max attempt count, or escalate to the user. Use Copy agent rule or Ask Otter to draft it.";+export const GOVERNANCE_REMEDIATION_TOOL_BURST =+ "Review the tool list for redundant calls and add stop conditions or tighter tool policies before the next run.";+export const GOVERNANCE_REMEDIATION_WIDE_BRANCH =+ "Check whether fan-out is expected; otherwise limit parallel tool calls or subagent spawning.";+export const GOVERNANCE_REMEDIATION_EVALUATION =+ "Open Evaluations for this span, review the failing metric, and adjust the prompt, policy, or model before re-running.";+export const GOVERNANCE_FINDING_CAPTURE_FULL_SUMMARY =+ "Full content capture is enabled";+export const GOVERNANCE_FINDING_CAPTURE_FULL_DETAIL =+ "This session records prompts, tool arguments, and results. That is the highest-risk capture mode for secrets and personal data.";+export const GOVERNANCE_FINDING_CAPTURE_MINIMAL_SUMMARY =+ "Minimal content capture";+export const GOVERNANCE_FINDING_CAPTURE_MINIMAL_DETAIL =+ "Only session bookends and counters were captured, so this hierarchy has a weak audit trail.";+export const GOVERNANCE_REMEDIATION_CONTENT_CAPTURE =+ "Use metadata_only for normal work. Enable full capture only for an approved review, and keep secrets out of prompts and tool arguments.";+export const GOVERNANCE_FINDING_OUTCOME_ABANDONED_SUMMARY =+ "Session abandoned with uncommitted changes";+export const GOVERNANCE_FINDING_OUTCOME_ABANDONED_DETAIL =+ "The coding agent ended without a clean completion after making changes. Review leftover edits before they are committed or discarded.";+export const GOVERNANCE_FINDING_OUTCOME_CANCELLED_SUMMARY =+ "Session cancelled";+export const GOVERNANCE_FINDING_OUTCOME_CANCELLED_DETAIL =+ "The coding-agent session was cancelled before a completed outcome.";+export const GOVERNANCE_REMEDIATION_SESSION_OUTCOME =+ "Inspect the leftover diff, keep or revert the changes, and avoid leaving abandoned agent edits in the working tree.";+export const GOVERNANCE_FINDING_EDIT_REJECT_SUMMARY =+ "High edit rejection ({percent}%)";+export const GOVERNANCE_FINDING_EDIT_REJECT_DETAIL =+ "{rejected} of {total} recorded edit decisions were rejected.";+export const GOVERNANCE_REMEDIATION_EDIT_REJECT =+ "Tighten the task prompt or coding-agent rules so proposed edits match the intended files and style before the next run.";+export const GOVERNANCE_FINDING_VCS_DIRTY_SUMMARY =+ "Agent wrote on a dirty working tree";+export const GOVERNANCE_FINDING_VCS_DIRTY_DETAIL =+ "The repository already had uncommitted changes when the agent applied more edits, which mixes human and agent diffs.";+export const GOVERNANCE_REMEDIATION_VCS_DIRTY =+ "Commit or stash local work before launching the agent, then re-run so agent edits are reviewable on their own.";+export const GOVERNANCE_FINDING_MCP_SCOPE_SUMMARY =+ "User- or local-scoped MCP ({count})";+export const GOVERNANCE_FINDING_MCP_SCOPE_DETAIL =+ "MCP servers are bound outside project scope: {servers}.";+export const GOVERNANCE_FINDING_MCP_MARKETPLACE_SUMMARY =+ "Marketplace MCP server ({count})";+export const GOVERNANCE_FINDING_MCP_MARKETPLACE_DETAIL =+ "MCP servers from the marketplace were used: {servers}.";+export const GOVERNANCE_REMEDIATION_MCP =+ "Prefer project- or enterprise-scoped MCP servers, and review marketplace plugins before they can read the repo or secrets.";+export const GOVERNANCE_FINDING_GIT_BLAST_SUMMARY =+ "High git activity ({commits} commits, {prs} PRs)";+export const GOVERNANCE_FINDING_GIT_BLAST_DETAIL =+ "This session created several commits or pull requests. Confirm the changes were intended and reviewed.";+export const GOVERNANCE_REMEDIATION_GIT_BLAST =+ "Limit the agent to one focused commit or PR per task, and require human review before push.";+export const GOVERNANCE_FINDING_SUBAGENT_SUMMARY =+ "Subagent fan-out ({count})";+export const GOVERNANCE_FINDING_SUBAGENT_DETAIL =+ "This session spawned several subagents, which can multiply tool use, cost, and unreviewed edits.";+export const GOVERNANCE_REMEDIATION_SUBAGENT =+ "Cap parallel subagents in agent knowledge or settings unless fan-out is required for this task.";+export const GOVERNANCE_FINDING_SECRET_SUMMARY =+ "Possible secret or PII in captured payloads ({kinds})";+export const GOVERNANCE_FINDING_SECRET_DETAIL =+ "Tool or message payloads matched credential or PII patterns. The matching values are not stored on this finding.";+export const GOVERNANCE_REMEDIATION_SECRET =+ "Rotate any exposed credentials, switch capture mode to metadata_only, and keep secrets in a vault instead of prompts or tool arguments.";+export const GOVERNANCE_COPY_AGENT_RULE = "Copy agent rule";+export const GOVERNANCE_COPY_AGENT_RULE_DONE = "Copied";+export const GOVERNANCE_ASK_OTTER_FIX = "Ask Otter";+export const GOVERNANCE_ASK_OTTER_HIDE = "Hide Otter";+export const GOVERNANCE_ASK_OTTER_TITLE = "Ask Otter for a fix";+export const GOVERNANCE_ASK_OTTER_EMPTY =+ "Otter drafts a paste-ready AGENTS.md / .cursor/rules / skill rule so the next coding-agent run stops this identical tool loop.";+export const GOVERNANCE_ASK_OTTER_PLACEHOLDER =+ "Draft an agent knowledge rule that stops this tool loop…";+export const GOVERNANCE_ASK_OTTER_HINT =+ "Paste Otter’s rule into AGENTS.md, .cursor/rules, or a skill—do not rely on interrupting the live agent.";+export const GOVERNANCE_ASK_OTTER_SEND = "Get fix";+export const GOVERNANCE_ASK_OTTER_DEFAULT_QUESTION =+ "Draft a paste-ready coding-agent knowledge rule that prevents this identical tool retry loop.";+export const GOVERNANCE_AGENT_LOOP_KNOWLEDGE_RULE = (+ tool: string,+ resource: string,+ count: number+) =>+ [+ `## Tool-loop guard (${tool})`,+ "",+ `OpenLIT detected \`${tool}\` repeating identical arguments ${count} time(s)${resource ? ` on \`${resource}\`` : ""}.`,+ "",+ `Do not call \`${tool}\` again with the same arguments after a completed attempt.`,+ "If the previous result was incomplete or wrong:",+ "- change the path or arguments, or",+ "- stop and ask the user what to do next",+ `Never retry identical \`${tool}\` calls in a loop. Prefer at most one retry with different args, then escalate to the user.`,+ "",+ "Where to put this: AGENTS.md, `.cursor/rules/`, or a project skill so every coding-agent session loads it.",+ ].join("\n");+export const GOVERNANCE_AGENT_LOOP_OTTER_PROMPT = (+ tool: string,+ count: number,+ resource: string,+ fingerprint: string,+ question: string+) =>+ [+ "You are helping prevent a stuck coding-agent tool loop observed in OpenLIT telemetry.",+ "Operators usually cannot interrupt Cursor or similar agents mid-run, so the fix must be durable agent knowledge—not a live interrupt.",+ `Tool: ${tool}`,+ `Repeat count: ${count}`,+ resource ? `Resource: ${resource}` : "",+ fingerprint ? `Args fingerprint: ${fingerprint}` : "",+ "",+ "Draft a short, paste-ready rule for AGENTS.md, .cursor/rules, or a Cursor skill that stops the agent from repeating this identical tool call.",+ "Include concrete constraints: different path/args on retry, a max attempt count, and escalate to the user instead of looping.",+ "Output only the rule markdown (heading + bullets). No preamble.",+ "",+ `User request: ${question}`,+ ]+ .filter(Boolean)+ .join("\n");+export const GOVERNANCE_SPAN_REF = "Open span";+export const GOVERNANCE_RULE_LINK = "Open rule";+export const GOVERNANCE_HARNESS_SPANS = "Spans";+export const GOVERNANCE_HARNESS_DEPTH = "Max depth";+export const GOVERNANCE_HARNESS_LLM = "LLM calls";+export const GOVERNANCE_HARNESS_TOOLS = "Tool calls";+export const GOVERNANCE_HARNESS_RETRIEVAL = "Retrieval";+export const GOVERNANCE_HARNESS_ERRORS = "Errors";+export const GOVERNANCE_HARNESS_COST = "Trace cost";+export const GOVERNANCE_HARNESS_DURATION = "Duration";+export const GOVERNANCE_INVALID_SPAN_ID = "Invalid span id";+export const GOVERNANCE_MISSING_SPAN_ID = "No span id provided";+export const GOVERNANCE_RETRY = "Retry";+export const GOVERNANCE_REFRESH = "Refresh";+export const GOVERNANCE_EXPORT_JSON = "Export JSON";+export const GOVERNANCE_TRUNCATED_NOTE =+ "Large trace: rule and evaluation coverage was limited to protect performance.";+export const GOVERNANCE_AGENT_LOOP_BANNER =+ "Stuck tool loop detected: {tool} repeated {count} times with the same arguments.";+export const GOVERNANCE_EVAL_SCORE_PREFIX = "score";+export const GOVERNANCE_FILTER_ALL = "All";+export const GOVERNANCE_FILTER_CRITICAL = "Critical";+export const GOVERNANCE_FILTER_MAJOR = "Major";+export const GOVERNANCE_FILTER_MINOR = "Minor";+export const GOVERNANCE_FILTER_INFO = "Info";+export const GOVERNANCE_EVALUATIONS_LINK = "Open evaluations";+export const GOVERNANCE_FINDING_WHAT = "What happened";+export const GOVERNANCE_FINDING_WHERE = "Where";+export const GOVERNANCE_FINDING_FIX = "How to fix";+export const GOVERNANCE_FINDING_EVIDENCE = "Evidence";+export const GOVERNANCE_FINDING_SPANS = "Related spans";+export const GOVERNANCE_SHOW_MORE = "Show more";+export const GOVERNANCE_SHOWING_OF = "Showing {shown} of {total}";+export const GOVERNANCE_CATEGORY_AGENT_LOOP = "Tool loop";+export const GOVERNANCE_CATEGORY_POLICY = "Policy";+export const GOVERNANCE_CATEGORY_CODING_AGENT = "Coding agent";+export const GOVERNANCE_CATEGORY_SPAN_ERROR = "Span error";+export const GOVERNANCE_CATEGORY_GENERATION_HEALTH = "Generation health";+export const GOVERNANCE_CATEGORY_HARNESS = "Harness";+export const GOVERNANCE_CATEGORY_EVALUATION = "Evaluation";+export const GOVERNANCE_FILTER_EMPTY =+ "No findings match this severity filter.";+export const GOVERNANCE_SEVERITY_LABEL = "Severity";export const TRACE_AI_LOAD_FAILED = "Failed to load AI improvement analysis";export const TRACE_AI_RUN_FAILED = "Failed to run AI improvement analysis";export const TRACE_AI_TIMEOUT = "Analysis timed out. Please try again.";diff --git a/src/client/src/helpers/client/governance-analytics.ts b/src/client/src/helpers/client/governance-analytics.tsnew file mode 100644index 00000000..d5e77d5c--- /dev/null+++ b/src/client/src/helpers/client/governance-analytics.ts@@ -0,0 +1,21 @@+import type { GovernanceSeverity } from "@/types/governance-report";++export function governanceReportEventProps(input: {+ spanId: string;+ traceId?: string;+ riskLevel?: GovernanceSeverity | "none";+ findingCount?: number;+ ruleMatchCount?: number;+ evaluationCount?: number;+ analysisLimited?: boolean;+}) {+ return {+ span_id: input.spanId,+ trace_id: input.traceId,+ risk_level: input.riskLevel,+ finding_count: input.findingCount,+ rule_match_count: input.ruleMatchCount,+ evaluation_count: input.evaluationCount,+ analysis_limited: input.analysisLimited ?? false,+ };+}diff --git a/src/client/src/helpers/server/governance-analytics.ts b/src/client/src/helpers/server/governance-analytics.tsnew file mode 100644index 00000000..d79096a7--- /dev/null+++ b/src/client/src/helpers/server/governance-analytics.ts@@ -0,0 +1,40 @@+import { SERVER_EVENTS } from "@/constants/events";+import {+ governanceReportEventProps,+} from "@/helpers/client/governance-analytics";+import type { GovernanceSeverity } from "@/types/governance-report";+import PostHogServer from "@/lib/posthog";++export function fireGovernanceReportTelemetry(input: {+ success: boolean;+ startTimestamp: number;+ spanId: string;+ traceId?: string;+ reason?: string;+ error?: string;+ riskLevel?: GovernanceSeverity | "none";+ findingCount?: number;+ ruleMatchCount?: number;+ evaluationCount?: number;+ analysisLimited?: boolean;+}) {+ PostHogServer.fireEvent({+ event: input.success+ ? SERVER_EVENTS.GOVERNANCE_REPORT_SUCCESS+ : SERVER_EVENTS.GOVERNANCE_REPORT_FAILURE,+ startTimestamp: input.startTimestamp,+ properties: {+ ...governanceReportEventProps({+ spanId: input.spanId,+ traceId: input.traceId,+ riskLevel: input.riskLevel,+ findingCount: input.findingCount,+ ruleMatchCount: input.ruleMatchCount,+ evaluationCount: input.evaluationCount,+ analysisLimited: input.analysisLimited,+ }),+ reason: input.reason,+ error: input.error,+ },+ });+}diff --git a/src/client/src/lib/access/governance-route.ts b/src/client/src/lib/access/governance-route.tsnew file mode 100644index 00000000..6c271fd7--- /dev/null+++ b/src/client/src/lib/access/governance-route.ts@@ -0,0 +1,16 @@+/**+ * CE fallback for governance route protection and audit hooks.+ * Enterprise replaces this neutral module through its path aliases.+ */+export type GovernanceAction = "read";++export function withGovernanceAccess<THandler>(+ _action: GovernanceAction,+ handler: THandler+): THandler {+ return handler;+}++export function withGovernanceAudit<THandler>(handler: THandler): THandler {+ return handler;+}diff --git a/src/client/src/lib/platform/agents/materialize.ts b/src/client/src/lib/platform/agents/materialize.tsindex ddb20502..9f71da2a 100644--- a/src/client/src/lib/platform/agents/materialize.ts+++ b/src/client/src/lib/platform/agents/materialize.ts@@ -8,7 +8,7 @@* they read from the materialized tables.*/-import { intelligenceDataCollector, OTEL_TRACES_TABLE_NAME } from "@/lib/platform/common";+import { intelligenceDataCollector } from "@/lib/platform/common";import {CONTROLLER_DESIRED_STATES_V2_TABLE,CONTROLLER_SERVICES_TABLE,@@ -136,6 +136,12 @@ async function discoverAgents(? `AND cluster_id = '${escape(clusterFilter)}'`: "";+ const tracesDbConfigId = await resolveCodingClickHouseDbConfigId(dbConfigId);+ const { resolveTracesTableRef } = await import(+ "@/lib/platform/connectors/datasource/clickhouse/direct-read"+ );+ const tracesTable = await resolveTracesTableRef(tracesDbConfigId);+// SDK-side: deduplicate per (service_name, environment, cluster_id) over a// recent window. cluster_id defaults to 'default' for SDK-only agents.// workload_key comes from ResourceAttributes['service.workload.key'] which@@ -182,7 +188,7 @@ async function discoverAgents(ServiceName AS service_name,${DEPLOYMENT_ENV_SQL} AS environment,if(ResourceAttributes['k8s.cluster.name'] != '', ResourceAttributes['k8s.cluster.name'], 'default') AS cluster_id- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${tracesTable}WHERE Timestamp >= now() - INTERVAL ${SDK_DISCOVERY_LOOKBACK_MINUTES} MINUTEAND (ResourceAttributes['telemetry.distro.name'] = 'openlit-cli'@@ -200,7 +206,7 @@ async function discoverAgents(argMax(ResourceAttributes['telemetry.sdk.language'], Timestamp) AS sdk_language,min(Timestamp) AS first_seen,max(Timestamp) AS last_seen- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${tracesTable}WHERE Timestamp >= now() - INTERVAL ${SDK_DISCOVERY_LOOKBACK_MINUTES} MINUTEAND ServiceName != ''AND ResourceAttributes['telemetry.sdk.name'] = 'openlit'@@ -255,7 +261,11 @@ async function discoverAgents(SDK_DISCOVERY_LOOKBACK_MINUTES);} else {- const sdkRes = await intelligenceDataCollector({ query: sdkQuery }, "query", dbConfigId);+ const sdkRes = await intelligenceDataCollector(+ { query: sdkQuery },+ "query",+ tracesDbConfigId+ );if (sdkRes.err) {agentsLogger.error("materializer_sdk_discovery_failed", {err: sdkRes.err,@@ -595,6 +605,10 @@ async function discoverCodingAgents(window?: CodingAgentDiscoveryWindow): Promise<DiscoveredAgent[]> {const codingDbConfigId = await resolveCodingClickHouseDbConfigId(dbConfigId);+ const { resolveTracesTableRef } = await import(+ "@/lib/platform/connectors/datasource/clickhouse/direct-read"+ );+ const tracesTable = await resolveTracesTableRef(codingDbConfigId);// Cost rollup notes:// * `coding_agent.session.cost_usd` is only stamped on the@@ -760,7 +774,7 @@ async function discoverCodingAgents(min(Timestamp) AS chat_first_seen,max(Timestamp) AS chat_last_seen,argMax(SpanAttributes['coding_agent.client.version'], Timestamp) AS client_version- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${tracesTable}WHERE ${buildCodingWindowClause(window)}AND (SpanAttributes['coding_agent.session.id'] != ''@@ -913,6 +927,12 @@ async function fetchRequestCounts(}if (!traditional.length) return map;+ const tracesDbConfigId = await resolveCodingClickHouseDbConfigId(dbConfigId);+ const { resolveTracesTableRef } = await import(+ "@/lib/platform/connectors/datasource/clickhouse/direct-read"+ );+ const tracesTable = await resolveTracesTableRef(tracesDbConfigId);+const serviceNames = Array.from(new Set(traditional.map((a) => a.service_name)));const namesList = serviceNames.map((n) => `'${escape(n)}'`).join(", ");const query = `@@ -921,12 +941,12 @@ async function fetchRequestCounts(${DEPLOYMENT_ENV_SQL} AS environment,if(ResourceAttributes['k8s.cluster.name'] != '', ResourceAttributes['k8s.cluster.name'], 'default') AS cluster_id,count() AS request_count_24h- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${tracesTable}WHERE Timestamp >= now() - INTERVAL 24 HOURAND ServiceName IN (${namesList})GROUP BY service_name, environment, cluster_id`;- const res = await intelligenceDataCollector({ query }, "query", dbConfigId);+ const res = await intelligenceDataCollector({ query }, "query", tracesDbConfigId);if (res.err) {agentsLogger.error("materializer_request_count_failed", {err: res.err,diff --git a/src/client/src/lib/platform/coding-agents/table-details.ts b/src/client/src/lib/platform/coding-agents/table-details.tsindex 6d144120..a8c71d90 100644--- a/src/client/src/lib/platform/coding-agents/table-details.ts+++ b/src/client/src/lib/platform/coding-agents/table-details.ts@@ -45,6 +45,7 @@ export const CODING_AGENT_ATTR = {sessionOutcome: "coding_agent.session.outcome",sessionDurationMs: "coding_agent.session.duration_ms",sessionToolCallCount: "coding_agent.session.tool_call_count",+ sessionSubagentCount: "coding_agent.session.subagent_count",sessionCostUsd: "coding_agent.session.cost_usd",userClassification: "coding_agent.user.classification",userClassificationReason: "coding_agent.user.classification.reason",@@ -79,6 +80,7 @@ export const CODING_AGENT_ATTR = {gitPrTitle: "coding_agent.git.pull_request.title",mcpServerName: "coding_agent.mcp.server.name",mcpScope: "coding_agent.mcp.scope",+ mcpSource: "coding_agent.mcp.source",mcpTransport: "coding_agent.mcp.transport",vcsDirty: "coding_agent.vcs.dirty",hookEvent: "coding_agent.hook.event",diff --git a/src/client/src/lib/platform/common.ts b/src/client/src/lib/platform/common.tsindex ea131d90..08c2c45c 100644--- a/src/client/src/lib/platform/common.ts+++ b/src/client/src/lib/platform/common.ts@@ -209,6 +209,24 @@ export async function dataCollector();}+/**+ * Connector adapter reads that need full `otel_traces` rows (trace trees,+ * span lookup, session expansion). These bypass OpenPlait native SQL so the+ * ClickHouse datasource adapter resolves the configured database table directly.+ */+export async function connectorDataCollector(+ params: CollectorParams,+ clientQueryType: CollectorQueryType = "query",+ dbConfigId?: string+): Promise<DataCollectorType> {+ return collectClickHouseData(+ params,+ clientQueryType,+ dbConfigId,+ "direct"+ );+}+/*** Deliberate exception for OpenLIT's internal intelligence/materialization* layer. These queries read and write OpenLIT-owned ClickHouse state directly;diff --git a/src/client/src/lib/platform/connectors/datasource/clickhouse/adapter.ts b/src/client/src/lib/platform/connectors/datasource/clickhouse/adapter.tsindex f37a89c2..f33925e7 100644--- a/src/client/src/lib/platform/connectors/datasource/clickhouse/adapter.ts+++ b/src/client/src/lib/platform/connectors/datasource/clickhouse/adapter.ts@@ -14,11 +14,11 @@import { dataCollector } from "@/lib/platform/common";import {- OTEL_TRACES_TABLE_NAME,-} from "@/lib/platform/common";+ queryConnectorTraces,+ resolveTracesTableRef,+} from "./direct-read";import {getRequests,- getRequestViaSpanId,getAttributeKeys,} from "@/lib/platform/request";import {@@ -178,10 +178,11 @@ export class ClickHouseAdapter implements DataSourceAdapter {}async validateAISignal(window: QueryTimeRange): Promise<AISignalValidation> {+ const tracesTable = await resolveTracesTableRef(this.dbConfigId);const query = `SELECT CAST(COUNT(*) AS INTEGER) AS c- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${tracesTable}WHERE ${timeRangeClause(window)} AND ${aiSelectorToClickHouse()}`;- const { data, err } = await dataCollector({ query }, "query", this.dbConfigId);+ const { data, err } = await queryConnectorTraces(query, this.dbConfigId);const sampleCount = (data as { c?: number }[])?.[0]?.c ?? 0;return {ok: !err && sampleCount > 0,@@ -211,32 +212,40 @@ export class ClickHouseAdapter implements DataSourceAdapter {}async getSpan(spanId: string): Promise<NormalizedSpan | null> {- const result = await getRequestViaSpanId(spanId, this.dbConfigId);+ const tracesTable = await resolveTracesTableRef(this.dbConfigId);+ const query = `SELECT * FROM ${tracesTable}+ WHERE SpanId = '${escapeCH(spanId)}'+ LIMIT 1`;+ const result = await queryConnectorTraces(query, this.dbConfigId);assertLegacyReadSucceeded(result);- const { record } = result;- return record ? normalizeSpanRow(record as Record<string, unknown>) : null;+ const record = (result.data as unknown[])?.[0];+ return record+ ? normalizeSpanRow(record as Record<string, unknown>)+ : null;}async getTraceSpans(traceId: string): Promise<NormalizedSpan[]> {- const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME}+ const tracesTable = await resolveTracesTableRef(this.dbConfigId);+ const query = `SELECT * FROM ${tracesTable}WHERE TraceId = '${escapeCH(traceId)}'ORDER BY Timestamp ASCLIMIT 5000`;- const result = await dataCollector({ query }, "query", this.dbConfigId);+ const result = await queryConnectorTraces(query, this.dbConfigId);assertLegacyReadSucceeded(result);const { data } = result;return ((data as Record<string, unknown>[]) || []).map(normalizeSpanRow);}async getSpansBySession(sessionId: string): Promise<NormalizedSpan[]> {+ const tracesTable = await resolveTracesTableRef(this.dbConfigId);const s = escapeCH(sessionId);- const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME}+ const query = `SELECT * FROM ${tracesTable}WHERE SpanAttributes['${AI_SELECTOR_MARKERS.codingSessionId}'] = '${s}'OR ResourceAttributes['coding_agent.agent.parent_id'] = '${s}'OR SpanAttributes['coding_agent.agent.parent_id'] = '${s}'ORDER BY Timestamp ASCLIMIT 5000`;- const result = await dataCollector({ query }, "query", this.dbConfigId);+ const result = await queryConnectorTraces(query, this.dbConfigId);assertLegacyReadSucceeded(result);const { data } = result;return ((data as Record<string, unknown>[]) || []).map(normalizeSpanRow);@@ -265,10 +274,11 @@ export class ClickHouseAdapter implements DataSourceAdapter {].filter(Boolean).join(" AND ");- const sql = `SELECT ${selects} FROM ${OTEL_TRACES_TABLE_NAME}+ const tracesTable = await resolveTracesTableRef(this.dbConfigId);+ const sql = `SELECT ${selects} FROM ${tracesTable}WHERE ${where} ${groupBy}${query.limit ? `LIMIT ${Number(query.limit)}` : ""}`;- const result = await dataCollector({ query: sql }, "query", this.dbConfigId);+ const result = await queryConnectorTraces(sql, this.dbConfigId);assertLegacyReadSucceeded(result);const { data } = result;return {@@ -320,11 +330,12 @@ export class ClickHouseAdapter implements DataSourceAdapter {].filter(Boolean).join(" AND ");- const sql = `SELECT DISTINCT ${expr} AS v FROM ${OTEL_TRACES_TABLE_NAME}+ const tracesTable = await resolveTracesTableRef(this.dbConfigId);+ const sql = `SELECT DISTINCT ${expr} AS v FROM ${tracesTable}WHERE ${where} AND notEmpty(toString(${expr}))ORDER BY vLIMIT 1000`;- const result = await dataCollector({ query: sql }, "query", this.dbConfigId);+ const result = await queryConnectorTraces(sql, this.dbConfigId);assertLegacyReadSucceeded(result);const { data } = result;return ((data as { v?: unknown }[]) || [])@@ -482,6 +493,7 @@ export class ClickHouseAdapter implements DataSourceAdapter {// ---- Discovery --------------------------------------------------------async discoverServices(window: QueryTimeRange): Promise<DiscoveredService[]> {+ const tracesTable = await resolveTracesTableRef(this.dbConfigId);const sql = `SELECTServiceName AS serviceName,any(ResourceAttributes['deployment.environment']) AS environment,@@ -491,10 +503,10 @@ export class ClickHouseAdapter implements DataSourceAdapter {any(ResourceAttributes['telemetry.sdk.version']) AS sdkVersion,min(Timestamp) AS firstSeen,max(Timestamp) AS lastSeen- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${tracesTable}WHERE ${timeRangeClause(window)} AND ${aiSelectorToClickHouse()}GROUP BY ServiceName`;- const result = await dataCollector({ query: sql }, "query", this.dbConfigId);+ const result = await queryConnectorTraces(sql, this.dbConfigId);assertLegacyReadSucceeded(result);const { data } = result;return ((data as Record<string, unknown>[]) || []).map((r) => ({@@ -510,6 +522,7 @@ export class ClickHouseAdapter implements DataSourceAdapter {}async aggregateByService(window: QueryTimeRange): Promise<ServiceRollup[]> {+ const tracesTable = await resolveTracesTableRef(this.dbConfigId);const sql = `SELECTServiceName AS serviceName,any(ResourceAttributes['deployment.environment']) AS environment,@@ -517,10 +530,10 @@ export class ClickHouseAdapter implements DataSourceAdapter {CAST(COUNT(*) AS INTEGER) AS requestCount,groupUniqArray(SpanAttributes['gen_ai.request.model']) AS models,groupUniqArray(SpanAttributes['gen_ai.system']) AS providers- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${tracesTable}WHERE ${timeRangeClause(window)} AND ${aiSelectorToClickHouse()}GROUP BY ServiceName`;- const result = await dataCollector({ query: sql }, "query", this.dbConfigId);+ const result = await queryConnectorTraces(sql, this.dbConfigId);assertLegacyReadSucceeded(result);const { data } = result;return ((data as Record<string, unknown>[]) || []).map((r) => ({@@ -537,6 +550,7 @@ export class ClickHouseAdapter implements DataSourceAdapter {query: OpenLITQuery,maxTraces: number): Promise<NormalizedSpan[]> {+ const tracesTable = await resolveTracesTableRef(this.dbConfigId);const params = toMetricParams(query, this.dbConfigId);const where = [getFilterWhereCondition(params, true),@@ -544,15 +558,11 @@ export class ClickHouseAdapter implements DataSourceAdapter {].filter(Boolean).join(" AND ");- const traceIdSql = `SELECT DISTINCT TraceId FROM ${OTEL_TRACES_TABLE_NAME}+ const traceIdSql = `SELECT DISTINCT TraceId FROM ${tracesTable}WHERE ${where}ORDER BY TraceIdLIMIT ${Number(maxTraces) || 100}`;- const idResult = await dataCollector(- { query: traceIdSql },- "query",- this.dbConfigId- );+ const idResult = await queryConnectorTraces(traceIdSql, this.dbConfigId);assertLegacyReadSucceeded(idResult);const idRows = idResult.data;const traceIds = ((idRows as { TraceId?: string }[]) || [])@@ -560,11 +570,11 @@ export class ClickHouseAdapter implements DataSourceAdapter {.filter((id): id is string => !!id).map((id) => `'${escapeCH(id)}'`);if (traceIds.length === 0) return [];- const spanSql = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME}+ const spanSql = `SELECT * FROM ${tracesTable}WHERE TraceId IN (${traceIds.join(", ")})ORDER BY Timestamp ASCLIMIT 50000`;- const result = await dataCollector({ query: spanSql }, "query", this.dbConfigId);+ const result = await queryConnectorTraces(spanSql, this.dbConfigId);assertLegacyReadSucceeded(result);const { data } = result;return ((data as Record<string, unknown>[]) || []).map(normalizeSpanRow);diff --git a/src/client/src/lib/platform/connectors/datasource/clickhouse/direct-read.ts b/src/client/src/lib/platform/connectors/datasource/clickhouse/direct-read.tsnew file mode 100644index 00000000..d69fb736--- /dev/null+++ b/src/client/src/lib/platform/connectors/datasource/clickhouse/direct-read.ts@@ -0,0 +1,22 @@+import asaw from "@/utils/asaw";+import { getDBConfigByIdForBackground } from "@/lib/db-config";+import { connectorDataCollector } from "@/lib/platform/common";+import { qualifiedTracesTable } from "./sql";++/** Resolve the configured traces table reference for connector tree reads. */+export async function resolveTracesTableRef(+ dbConfigId?: string+): Promise<string> {+ if (!dbConfigId) return qualifiedTracesTable();+ const [err, cfg] = await asaw(getDBConfigByIdForBackground({ id: dbConfigId }));+ if (err || !cfg) return qualifiedTracesTable();+ return qualifiedTracesTable(cfg.database);+}++/** Run a connector-owned full-row trace read on the direct ClickHouse client. */+export async function queryConnectorTraces(+ query: string,+ dbConfigId?: string+) {+ return connectorDataCollector({ query }, "query", dbConfigId);+}diff --git a/src/client/src/lib/platform/connectors/datasource/clickhouse/sql.ts b/src/client/src/lib/platform/connectors/datasource/clickhouse/sql.tsnew file mode 100644index 00000000..0be79cb2--- /dev/null+++ b/src/client/src/lib/platform/connectors/datasource/clickhouse/sql.ts@@ -0,0 +1,20 @@+const SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;++/** Quote a ClickHouse identifier for safe table/column references. */+export function quoteClickHouseIdentifier(name: string): string {+ const trimmed = String(name || "").trim();+ if (!trimmed || !SAFE_IDENTIFIER.test(trimmed)) {+ throw new Error("Invalid ClickHouse identifier");+ }+ return `\`${trimmed}\``;+}++/** Resolve the traces table with optional database qualification. */+export function qualifiedTracesTable(database?: string | null): string {+ const table = quoteClickHouseIdentifier("otel_traces");+ const db = String(database || "").trim();+ if (db && SAFE_IDENTIFIER.test(db)) {+ return `${quoteClickHouseIdentifier(db)}.${table}`;+ }+ return table;+}diff --git a/src/client/src/lib/platform/governance/agent-loop-fix.ts b/src/client/src/lib/platform/governance/agent-loop-fix.tsnew file mode 100644index 00000000..2ef7acd5--- /dev/null+++ b/src/client/src/lib/platform/governance/agent-loop-fix.ts@@ -0,0 +1,68 @@+/**+ * Deterministic remediation helpers for agent-loop findings.+ * Builds paste-ready coding-agent knowledge and Otter prompts (no LLM here).+ */++import {+ GOVERNANCE_AGENT_LOOP_KNOWLEDGE_RULE,+ GOVERNANCE_AGENT_LOOP_OTTER_PROMPT,+ GOVERNANCE_ASK_OTTER_DEFAULT_QUESTION,+} from "@/constants/messages/en";+import type { GovernanceFinding } from "@/types/governance-report";++export type AgentLoopFixContext = {+ tool: string;+ count: number;+ resource: string;+ fingerprint: string;+};++function asText(value: unknown): string {+ if (value === undefined || value === null) return "";+ return String(value).trim();+}++function asCount(value: unknown): number {+ const n = typeof value === "number" ? value : Number(value);+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;+}++export function agentLoopFixContext(+ finding: Pick<GovernanceFinding, "resource" | "evidence">+): AgentLoopFixContext {+ const evidence = finding.evidence || {};+ return {+ tool: asText(evidence.tool_name) || "tool",+ count: asCount(evidence.count),+ resource: asText(finding.resource),+ fingerprint: asText(evidence.args_fingerprint),+ };+}++/** Paste-ready AGENTS.md / .cursor/rules / skill text for this loop. */+export function buildAgentLoopKnowledgeRule(+ finding: Pick<GovernanceFinding, "resource" | "evidence">+): string {+ const ctx = agentLoopFixContext(finding);+ return GOVERNANCE_AGENT_LOOP_KNOWLEDGE_RULE(+ ctx.tool,+ ctx.resource,+ ctx.count || 1+ );+}++/** Wrap an operator question with loop evidence for Ask Otter. */+export function buildAgentLoopOtterPrompt(+ question: string,+ finding: Pick<GovernanceFinding, "resource" | "evidence">+): string {+ const ctx = agentLoopFixContext(finding);+ const text = question.trim() || GOVERNANCE_ASK_OTTER_DEFAULT_QUESTION;+ return GOVERNANCE_AGENT_LOOP_OTTER_PROMPT(+ ctx.tool,+ ctx.count || 1,+ ctx.resource,+ ctx.fingerprint,+ text+ );+}diff --git a/src/client/src/lib/platform/governance/coding-agent-findings.ts b/src/client/src/lib/platform/governance/coding-agent-findings.tsnew file mode 100644index 00000000..f7b56325--- /dev/null+++ b/src/client/src/lib/platform/governance/coding-agent-findings.ts@@ -0,0 +1,376 @@+import { createHash } from "crypto";+import {+ CODING_AGENT_ATTR,+ CODING_AGENT_SPAN_GIT_COMMIT,+ CODING_AGENT_SPAN_GIT_PR,+ CODING_AGENT_SPAN_SESSION,+ CODING_AGENT_SPAN_SUBAGENT,+} from "@/lib/platform/coding-agents/table-details";+import getMessage from "@/constants/messages";+import type {+ GovernanceFinding,+ GovernanceSeverity,+} from "@/types/governance-report";+import type { TraceHeirarchySpan } from "@/types/trace";+import { readSpanAttr } from "./hierarchy";+import { scanSpanPayloads } from "./secret-scan";++export const GOVERNANCE_EDIT_REJECT_MIN_DECISIONS = 4;+export const GOVERNANCE_EDIT_REJECT_RATIO = 0.5;+export const GOVERNANCE_COMMIT_BLAST = 3;+export const GOVERNANCE_PR_BLAST = 2;+export const GOVERNANCE_SUBAGENT_FANOUT = 4;++const BROAD_MCP_SCOPES = new Set(["user", "local"]);+const RISKY_MCP_SOURCES = new Set(["marketplace"]);+const WRITE_EDIT_DECISIONS = new Set(["accept", "auto_accepted"]);+const FLAGGED_OUTCOMES = new Set(["abandoned_with_change", "cancelled"]);++function stableFindingId(parts: string[]): string {+ return createHash("sha1").update(parts.join("|")).digest("hex").slice(0, 12);+}++function uniqueSpanIds(ids: string[], limit = 12): string[] {+ const out: string[] = [];+ const seen = new Set<string>();+ for (const id of ids) {+ const trimmed = String(id || "").trim();+ if (!trimmed || seen.has(trimmed)) continue;+ seen.add(trimmed);+ out.push(trimmed);+ if (out.length >= limit) break;+ }+ return out;+}++function readNumericAttr(span: TraceHeirarchySpan, keys: string[]): number {+ const raw = readSpanAttr(span, keys);+ const numeric = Number(raw);+ return Number.isFinite(numeric) ? numeric : 0;+}++function isTruthyAttr(span: TraceHeirarchySpan, keys: string[]): boolean {+ const raw = readSpanAttr(span, keys).toLowerCase();+ return raw === "true" || raw === "1" || raw === "yes";+}++function maxNumeric(+ spans: TraceHeirarchySpan[],+ keys: string[],+ fallbackCount: number+): { value: number; spanIds: string[] } {+ let value = fallbackCount;+ const spanIds: string[] = [];+ for (const span of spans) {+ const n = readNumericAttr(span, keys);+ if (n > 0) spanIds.push(span.SpanId);+ if (n > value) value = n;+ }+ return { value, spanIds };+}++export function buildCodingAgentFindings(+ spans: TraceHeirarchySpan[]+): GovernanceFinding[] {+ const m = getMessage();+ const findings: GovernanceFinding[] = [];+ const captureModes = new Map<string, string[]>();+ const outcomes = new Map<string, string[]>();+ const mcpBroad = new Map<string, string[]>();+ const mcpMarketplace = new Map<string, string[]>();+ const secretHits = new Map<string, string[]>();+ const dirtyWriteIds: string[] = [];+ const subagentIds: string[] = [];+ const gitCommitIds: string[] = [];+ const gitPrIds: string[] = [];+ let acceptCount = 0;+ let rejectCount = 0;++ for (const span of spans) {+ const capture = readSpanAttr(span, [CODING_AGENT_ATTR.contentCaptureMode]);+ if (capture === "full" || capture === "minimal") {+ const ids = captureModes.get(capture) || [];+ ids.push(span.SpanId);+ captureModes.set(capture, ids);+ }++ const outcome = readSpanAttr(span, [CODING_AGENT_ATTR.sessionOutcome]);+ if (FLAGGED_OUTCOMES.has(outcome)) {+ const ids = outcomes.get(outcome) || [];+ ids.push(span.SpanId);+ outcomes.set(outcome, ids);+ }++ const mcpScope = readSpanAttr(span, [CODING_AGENT_ATTR.mcpScope]);+ const mcpSource = readSpanAttr(span, [CODING_AGENT_ATTR.mcpSource]);+ const mcpServer =+ readSpanAttr(span, [CODING_AGENT_ATTR.mcpServerName]) || "unknown";+ if (BROAD_MCP_SCOPES.has(mcpScope)) {+ const ids = mcpBroad.get(mcpServer) || [];+ ids.push(span.SpanId);+ mcpBroad.set(mcpServer, ids);+ }+ if (RISKY_MCP_SOURCES.has(mcpSource)) {+ const ids = mcpMarketplace.get(mcpServer) || [];+ ids.push(span.SpanId);+ mcpMarketplace.set(mcpServer, ids);+ }++ const kinds = scanSpanPayloads(span.SpanAttributes);+ for (const kind of kinds) {+ const ids = secretHits.get(kind) || [];+ ids.push(span.SpanId);+ secretHits.set(kind, ids);+ }++ const decision = readSpanAttr(span, [CODING_AGENT_ATTR.editDecision]);+ if (decision === "reject") rejectCount += 1;+ if (WRITE_EDIT_DECISIONS.has(decision)) acceptCount += 1;++ const madeWrites =+ readNumericAttr(span, [CODING_AGENT_ATTR.sessionLinesAdded]) > 0 ||+ readNumericAttr(span, [CODING_AGENT_ATTR.sessionCommitCount]) > 0 ||+ WRITE_EDIT_DECISIONS.has(decision);+ if (isTruthyAttr(span, [CODING_AGENT_ATTR.vcsDirty]) && madeWrites) {+ dirtyWriteIds.push(span.SpanId);+ }++ const isSubagentRoot =+ span.SpanName === CODING_AGENT_SPAN_SUBAGENT ||+ (span.SpanName === CODING_AGENT_SPAN_SESSION &&+ (isTruthyAttr(span, [CODING_AGENT_ATTR.sessionIsSubagent]) ||+ readSpanAttr(span, ["coding_agent.agent.type"]) ===+ "subagent" ||+ Boolean(readSpanAttr(span, [CODING_AGENT_ATTR.agentParentId]))));+ if (isSubagentRoot) subagentIds.push(span.SpanId);++ if (span.SpanName === CODING_AGENT_SPAN_GIT_COMMIT) {+ gitCommitIds.push(span.SpanId);+ }+ if (span.SpanName === CODING_AGENT_SPAN_GIT_PR) {+ gitPrIds.push(span.SpanId);+ }+ }++ for (const [mode, spanIds] of Array.from(captureModes.entries())) {+ const full = mode === "full";+ findings.push({+ id: stableFindingId(["content_capture", mode]),+ category: "policy",+ severity: full ? "major" : "info",+ summary: full+ ? m.GOVERNANCE_FINDING_CAPTURE_FULL_SUMMARY+ : m.GOVERNANCE_FINDING_CAPTURE_MINIMAL_SUMMARY,+ detail: full+ ? m.GOVERNANCE_FINDING_CAPTURE_FULL_DETAIL+ : m.GOVERNANCE_FINDING_CAPTURE_MINIMAL_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_CONTENT_CAPTURE,+ span_refs: uniqueSpanIds(spanIds),+ evidence: { content_capture_mode: mode, span_count: spanIds.length },+ });+ }++ for (const [outcome, spanIds] of Array.from(outcomes.entries())) {+ const abandoned = outcome === "abandoned_with_change";+ findings.push({+ id: stableFindingId(["session_outcome", outcome]),+ category: "coding_agent",+ severity: abandoned ? "major" : "info",+ summary: abandoned+ ? m.GOVERNANCE_FINDING_OUTCOME_ABANDONED_SUMMARY+ : m.GOVERNANCE_FINDING_OUTCOME_CANCELLED_SUMMARY,+ detail: abandoned+ ? m.GOVERNANCE_FINDING_OUTCOME_ABANDONED_DETAIL+ : m.GOVERNANCE_FINDING_OUTCOME_CANCELLED_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_SESSION_OUTCOME,+ span_refs: uniqueSpanIds(spanIds),+ evidence: { session_outcome: outcome },+ });+ }++ const sessionReject = maxNumeric(+ spans,+ [CODING_AGENT_ATTR.sessionEditRejectCount],+ rejectCount+ );+ const sessionAccept = maxNumeric(+ spans,+ [CODING_AGENT_ATTR.sessionEditAcceptCount],+ acceptCount+ );+ const totalEdits = sessionAccept.value + sessionReject.value;+ if (+ totalEdits >= GOVERNANCE_EDIT_REJECT_MIN_DECISIONS &&+ sessionReject.value / totalEdits >= GOVERNANCE_EDIT_REJECT_RATIO+ ) {+ const percent = Math.round((sessionReject.value / totalEdits) * 100);+ findings.push({+ id: stableFindingId(["edit_reject"]),+ category: "coding_agent",+ severity: percent >= 80 ? "major" : "minor",+ summary: m.GOVERNANCE_FINDING_EDIT_REJECT_SUMMARY.replace(+ "{percent}",+ String(percent)+ ),+ detail: m.GOVERNANCE_FINDING_EDIT_REJECT_DETAIL.replace(+ "{rejected}",+ String(sessionReject.value)+ ).replace("{total}", String(totalEdits)),+ remediation: m.GOVERNANCE_REMEDIATION_EDIT_REJECT,+ span_refs: uniqueSpanIds([+ ...sessionReject.spanIds,+ ...sessionAccept.spanIds,+ ]),+ evidence: {+ edit_reject_count: sessionReject.value,+ edit_accept_count: sessionAccept.value,+ },+ });+ }++ if (dirtyWriteIds.length) {+ findings.push({+ id: stableFindingId(["vcs_dirty_write"]),+ category: "coding_agent",+ severity: "minor",+ summary: m.GOVERNANCE_FINDING_VCS_DIRTY_SUMMARY,+ detail: m.GOVERNANCE_FINDING_VCS_DIRTY_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_VCS_DIRTY,+ span_refs: uniqueSpanIds(dirtyWriteIds),+ evidence: { vcs_dirty: true },+ });+ }++ if (mcpBroad.size) {+ const servers = Array.from(mcpBroad.keys()).sort();+ const spanIds = Array.from(mcpBroad.values()).flat();+ findings.push({+ id: stableFindingId(["mcp_broad", servers.join(",")]),+ category: "policy",+ severity: "info",+ summary: m.GOVERNANCE_FINDING_MCP_SCOPE_SUMMARY.replace(+ "{count}",+ String(servers.length)+ ),+ detail: m.GOVERNANCE_FINDING_MCP_SCOPE_DETAIL.replace(+ "{servers}",+ servers.join(", ")+ ),+ remediation: m.GOVERNANCE_REMEDIATION_MCP,+ span_refs: uniqueSpanIds(spanIds),+ evidence: {+ mcp_servers: servers.join(", "),+ mcp_scope: "user_or_local",+ },+ });+ }++ if (mcpMarketplace.size) {+ const servers = Array.from(mcpMarketplace.keys()).sort();+ const spanIds = Array.from(mcpMarketplace.values()).flat();+ findings.push({+ id: stableFindingId(["mcp_marketplace", servers.join(",")]),+ category: "policy",+ severity: "minor",+ summary: m.GOVERNANCE_FINDING_MCP_MARKETPLACE_SUMMARY.replace(+ "{count}",+ String(servers.length)+ ),+ detail: m.GOVERNANCE_FINDING_MCP_MARKETPLACE_DETAIL.replace(+ "{servers}",+ servers.join(", ")+ ),+ remediation: m.GOVERNANCE_REMEDIATION_MCP,+ span_refs: uniqueSpanIds(spanIds),+ evidence: {+ mcp_source: "marketplace",+ mcp_servers: servers.join(", "),+ },+ });+ }++ const commitRollup = maxNumeric(+ spans,+ [CODING_AGENT_ATTR.sessionCommitCount],+ gitCommitIds.length+ );+ const prRollup = maxNumeric(+ spans,+ [CODING_AGENT_ATTR.sessionPrCount],+ gitPrIds.length+ );+ if (+ commitRollup.value >= GOVERNANCE_COMMIT_BLAST ||+ prRollup.value >= GOVERNANCE_PR_BLAST+ ) {+ findings.push({+ id: stableFindingId(["git_blast"]),+ category: "coding_agent",+ severity:+ commitRollup.value >= 6 || prRollup.value >= 4 ? "major" : "minor",+ summary: m.GOVERNANCE_FINDING_GIT_BLAST_SUMMARY.replace(+ "{commits}",+ String(commitRollup.value)+ ).replace("{prs}", String(prRollup.value)),+ detail: m.GOVERNANCE_FINDING_GIT_BLAST_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_GIT_BLAST,+ span_refs: uniqueSpanIds([+ ...commitRollup.spanIds,+ ...prRollup.spanIds,+ ...gitCommitIds,+ ...gitPrIds,+ ]),+ evidence: {+ commit_count: commitRollup.value,+ pr_count: prRollup.value,+ },+ });+ }++ const subagentRollup = maxNumeric(+ spans,+ [CODING_AGENT_ATTR.sessionSubagentCount],+ subagentIds.length+ );+ if (subagentRollup.value >= GOVERNANCE_SUBAGENT_FANOUT) {+ findings.push({+ id: stableFindingId(["subagent_fanout"]),+ category: "harness",+ severity: subagentRollup.value >= 8 ? "major" : "minor",+ summary: m.GOVERNANCE_FINDING_SUBAGENT_SUMMARY.replace(+ "{count}",+ String(subagentRollup.value)+ ),+ detail: m.GOVERNANCE_FINDING_SUBAGENT_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_SUBAGENT,+ span_refs: uniqueSpanIds([...subagentRollup.spanIds, ...subagentIds]),+ evidence: { subagent_count: subagentRollup.value },+ });+ }++ if (secretHits.size) {+ const kinds = Array.from(secretHits.keys()).sort();+ const spanIds = Array.from(secretHits.values()).flat();+ const severity: GovernanceSeverity = kinds.includes("private_key")+ ? "critical"+ : "major";+ findings.push({+ id: stableFindingId(["secret_payload", kinds.join(",")]),+ category: "policy",+ severity,+ summary: m.GOVERNANCE_FINDING_SECRET_SUMMARY.replace(+ "{kinds}",+ kinds.join(", ")+ ),+ detail: m.GOVERNANCE_FINDING_SECRET_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_SECRET,+ span_refs: uniqueSpanIds(spanIds),+ evidence: {+ secret_kinds: kinds.join(", "),+ span_count: spanIds.length,+ },+ });+ }++ return findings;+}diff --git a/src/client/src/lib/platform/governance/evidence.ts b/src/client/src/lib/platform/governance/evidence.tsnew file mode 100644index 00000000..1dfa203a--- /dev/null+++ b/src/client/src/lib/platform/governance/evidence.ts@@ -0,0 +1,91 @@+import {+ fingerprintToolArgs,+ toolArgsOf,+ toolNameOf,+ spanLoopAttrs,+ type AgentLoopSpan,+} from "@/lib/platform/agent-loop/classify";+import type { TraceHeirarchySpan } from "@/types/trace";++const FILE_ATTR_KEYS = [+ "code.file.path",+ "coding_agent.edit.file.path",+ "gen_ai.tool.target",+];++const FILE_ARG_KEYS = [+ "path",+ "file",+ "file_path",+ "filepath",+ "target_file",+ "target",+ "uri",+];++function firstString(+ attrs: Record<string, unknown> | undefined,+ keys: string[]+): string {+ if (!attrs) return "";+ for (const key of keys) {+ const value = attrs[key];+ if (value === undefined || value === null) continue;+ const text = String(value).trim();+ if (text && text !== "-") return text;+ }+ return "";+}++function tryParseObject(raw: string): Record<string, unknown> | null {+ const trimmed = raw.trim();+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return null;+ try {+ const parsed = JSON.parse(trimmed);+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ return parsed as Record<string, unknown>;+ }+ } catch {+ return null;+ }+ return null;+}++/** Best-effort file/path hint from span attributes or tool arguments (no LLM). */+export function extractResourceHint(+ span: TraceHeirarchySpan | AgentLoopSpan+): string {+ const attrs = spanLoopAttrs(span as AgentLoopSpan);+ const direct = firstString(attrs, FILE_ATTR_KEYS);+ if (direct) return direct;++ const argsRaw = toolArgsOf(attrs);+ if (!argsRaw) return "";+ const parsed = tryParseObject(argsRaw);+ if (parsed) {+ const fromKeys = firstString(parsed, FILE_ARG_KEYS);+ if (fromKeys) return fromKeys;+ }++ // Fallback: pull a path-looking token from the fingerprint string.+ const fp = fingerprintToolArgs(argsRaw);+ const match = fp.match(+ /(?:^|["'\s=])((?:\/|~\/|\.\/|[A-Za-z]:\\)[^\s"'`,;]{2,240})/+ );+ return match?.[1] || "";+}++export function matchingLoopSpans(+ spans: TraceHeirarchySpan[],+ toolName: string,+ fingerprint: string+): TraceHeirarchySpan[] {+ return spans.filter((span) => {+ const attrs = spanLoopAttrs({+ SpanAttributes: span.SpanAttributes,+ ResourceAttributes: span.ResourceAttributes,+ });+ if (toolNameOf(attrs) !== toolName) return false;+ return fingerprintToolArgs(toolArgsOf(attrs)) === fingerprint;+ });+}diff --git a/src/client/src/lib/platform/governance/hierarchy.ts b/src/client/src/lib/platform/governance/hierarchy.tsnew file mode 100644index 00000000..eed4f235--- /dev/null+++ b/src/client/src/lib/platform/governance/hierarchy.ts@@ -0,0 +1,213 @@+import type { TraceHeirarchySpan, TraceRow } from "@/types/trace";++const RULE_FIELD_NAMES = [+ "ServiceName",+ "SpanName",+ "SpanKind",+ "StatusCode",+ "deployment.environment",+ "service.name",+ "gen_ai.system",+ "gen_ai.request.model",+ "gen_ai.usage.input_tokens",+ "gen_ai.usage.output_tokens",+ "gen_ai.usage.total_cost",+ "gen_ai.request.temperature",+] as const;++function ruleFieldValue(row: TraceRow, field: string): string {+ const attributeFields: Record<+ string,+ ["SpanAttributes" | "ResourceAttributes", string]+ > = {+ "service.name": ["ResourceAttributes", "service.name"],+ "gen_ai.system": ["SpanAttributes", "gen_ai.system"],+ "gen_ai.request.model": ["SpanAttributes", "gen_ai.request.model"],+ "gen_ai.usage.input_tokens": ["SpanAttributes", "gen_ai.usage.input_tokens"],+ "gen_ai.usage.output_tokens": ["SpanAttributes", "gen_ai.usage.output_tokens"],+ "gen_ai.usage.total_cost": ["SpanAttributes", "gen_ai.usage.total_cost"],+ "gen_ai.request.temperature": ["SpanAttributes", "gen_ai.request.temperature"],+ };+ if (field === "deployment.environment") {+ return String(+ row.ResourceAttributes["deployment.environment"] ??+ row.SpanAttributes["deployment.environment"] ??+ row.SpanAttributes["gen_ai.environment"] ??+ ""+ );+ }+ const attribute = attributeFields[field];+ if (attribute) {+ const [scope, key] = attribute;+ return String(row[scope][key] ?? "");+ }+ const directFields: Record<string, string> = {+ ServiceName: row.ServiceName,+ SpanName: row.SpanName,+ SpanKind: row.SpanKind,+ Duration: row.Duration,+ StatusCode: row.StatusCode,+ };+ return String(directFields[field] ?? "");+}++function parseTimestamp(value?: string | Date): Date {+ if (value instanceof Date && !Number.isNaN(value.getTime())) return value;+ if (typeof value === "string" && value) {+ const parsed = new Date(value);+ if (!Number.isNaN(parsed.getTime())) return parsed;+ }+ return new Date(0);+}++function stringRecord(+ source?: Record<string, string | number>+): Record<string, string> {+ return Object.fromEntries(+ Object.entries(source || {}).map(([key, value]) => [key, String(value)])+ );+}++export function flattenHierarchy(span: TraceHeirarchySpan): TraceHeirarchySpan[] {+ return [span, ...(span.children || []).flatMap(flattenHierarchy)];+}++export function hierarchySpanToTraceRow(span: TraceHeirarchySpan): TraceRow {+ return {+ Timestamp: parseTimestamp(span.Timestamp),+ TraceId: span.TraceId || "",+ SpanId: span.SpanId,+ ParentSpanId: span.ParentSpanId || "",+ TraceState: "",+ SpanName: span.SpanName,+ SpanKind: span.SpanKind || "SPAN_KIND_INTERNAL",+ ServiceName: span.ServiceName || "",+ ResourceAttributes: stringRecord(span.ResourceAttributes),+ ScopeName: span.ScopeName || "",+ ScopeVersion: span.ScopeVersion || "",+ SpanAttributes: span.SpanAttributes || {},+ Duration: String(span.Duration || ""),+ StatusCode: span.StatusCode || "",+ StatusMessage: span.StatusMessage || "",+ Events: (span.Events || []).map((event) => ({+ Timestamp: parseTimestamp(event.Timestamp),+ Name: event.Name || "",+ Attributes: stringRecord(event.Attributes),+ })),+ Links: (span.Links || []).map((link) => ({+ TraceId: link.TraceId || "",+ SpanId: link.SpanId || "",+ TraceState: link.TraceState || "",+ Attributes: stringRecord(link.Attributes),+ })),+ };+}++/** Fields aligned with rule-engine field discovery (`getRuleTraceFieldValue`). */+export function ruleFieldsFromHierarchySpan(+ span: TraceHeirarchySpan+): Record<string, string | number | boolean> {+ const row = hierarchySpanToTraceRow(span);+ const fields: Record<string, string | number | boolean> = {};+ for (const field of RULE_FIELD_NAMES) {+ const value = ruleFieldValue(row, field);+ if (!value) continue;+ if (field === "gen_ai.usage.input_tokens" || field === "gen_ai.usage.output_tokens") {+ const numeric = Number(value);+ if (Number.isFinite(numeric)) fields[field] = numeric;+ continue;+ }+ if (field === "gen_ai.usage.total_cost" || field === "gen_ai.request.temperature") {+ const numeric = Number(value);+ if (Number.isFinite(numeric)) fields[field] = numeric;+ continue;+ }+ fields[field] = value;+ }+ return fields;+}++export function spanDurationMs(span: TraceHeirarchySpan): number {+ const value = Number(span.Duration);+ if (!Number.isFinite(value)) return 0;+ if (value > 1_000_000) return value / 1e6;+ if (value > 10_000) return value / 1e3;+ return value;+}++export function readSpanAttr(+ span: TraceHeirarchySpan,+ keys: string[]+): string {+ const sources = [span.SpanAttributes, span.ResourceAttributes];+ for (const source of sources) {+ if (!source) continue;+ for (const key of keys) {+ const value = source[key];+ if (value === undefined || value === null) continue;+ const text = String(value).trim();+ if (text && text !== "-") return text;+ }+ }+ return "";+}++export type SpanRole =+ | "llm"+ | "tool"+ | "retrieval"+ | "embedding"+ | "database"+ | "http"+ | "orchestrator"+ | "unknown";++export function classifySpanRole(span: TraceHeirarchySpan): SpanRole {+ const attrs = span.SpanAttributes || {};+ const name = (span.SpanName || "").toLowerCase();+ const model = readSpanAttr(span, [+ "gen_ai.request.model",+ "gen_ai.response.model",+ ]);++ if (name.includes("embed")) return "embedding";+ if (+ name.includes("retriev") ||+ name.includes("search") ||+ name.includes("vector")+ ) {+ return "retrieval";+ }+ if (+ readSpanAttr(span, [+ "gen_ai.tool.name",+ "gen_ai.tool.call.name",+ "tool.name",+ "coding_agent.tool.name",+ ]) ||+ name.includes("tool")+ ) {+ return "tool";+ }+ if (+ readSpanAttr(span, ["db.query.text", "db.system.name", "db.operation.name"]) ||+ name.includes("db.")+ ) {+ return "database";+ }+ if (+ readSpanAttr(span, ["http.method", "http.url", "url.full"]) ||+ name.includes("http")+ ) {+ return "http";+ }+ if (model || readSpanAttr(span, ["gen_ai.system"])) return "llm";+ if ((span.children || []).length > 0) return "orchestrator";+ return "unknown";+}++export function maxHierarchyDepth(span: TraceHeirarchySpan, depth = 1): number {+ const children = span.children || [];+ if (!children.length) return depth;+ return Math.max(...children.map((child) => maxHierarchyDepth(child, depth + 1)));+}diff --git a/src/client/src/lib/platform/governance/secret-scan.ts b/src/client/src/lib/platform/governance/secret-scan.tsnew file mode 100644index 00000000..58b827de--- /dev/null+++ b/src/client/src/lib/platform/governance/secret-scan.ts@@ -0,0 +1,89 @@+/**+ * High-confidence credential/PII detectors for governance. Findings must+ * never persist the matched secret — only a kind label.+ */++export type SecretKind =+ | "aws_access_key"+ | "github_token"+ | "openai_api_key"+ | "anthropic_api_key"+ | "google_api_key"+ | "slack_token"+ | "private_key"+ | "jwt"+ | "password_assignment"+ | "pii_ssn";++const DETECTORS: Array<{ kind: SecretKind; pattern: RegExp }> = [+ { kind: "aws_access_key", pattern: /\bAKIA[0-9A-Z]{16}\b/ },+ {+ kind: "github_token",+ pattern: /\b(?:ghp_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{20,}|gho_[A-Za-z0-9]{36,})\b/,+ },+ { kind: "anthropic_api_key", pattern: /\bsk-ant-[A-Za-z0-9\-_]{20,}\b/ },+ { kind: "openai_api_key", pattern: /\bsk-[A-Za-z0-9]{20,}\b/ },+ { kind: "google_api_key", pattern: /\bAIza[0-9A-Za-z\-_]{35}\b/ },+ { kind: "slack_token", pattern: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/ },+ {+ kind: "private_key",+ pattern: /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/,+ },+ {+ kind: "jwt",+ pattern: /\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,+ },+ {+ kind: "password_assignment",+ pattern:+ /["']?(?:password|passwd|secret|api[_-]?key|access[_-]?token)["']?\s*[=:]\s*["']?[^\s"'\\]{12,}/i,+ },+ { kind: "pii_ssn", pattern: /\b\d{3}-\d{2}-\d{4}\b/ },+];++const PAYLOAD_KEYS = [+ "gen_ai.tool.args",+ "gen_ai.tool.call.arguments",+ "gen_ai.tool.arguments",+ "gen_ai.tool.input",+ "gen_ai.tool.result",+ "gen_ai.tool.output",+ "gen_ai.input.messages",+ "gen_ai.output.messages",+ "coding_agent.tool.error_message",+];++export function detectSecretKinds(text: string): SecretKind[] {+ if (!text) return [];+ const found: SecretKind[] = [];+ const seen = new Set<SecretKind>();+ for (const detector of DETECTORS) {+ if (seen.has(detector.kind)) continue;+ if (!detector.pattern.test(text)) continue;+ // OpenAI pattern also matches sk-ant-*; skip if Anthropic already hit.+ if (+ detector.kind === "openai_api_key" &&+ seen.has("anthropic_api_key")+ ) {+ continue;+ }+ seen.add(detector.kind);+ found.push(detector.kind);+ }+ return found;+}++export function scanSpanPayloads(+ attrs: Record<string, string | number> | undefined+): SecretKind[] {+ if (!attrs) return [];+ const kinds = new Set<SecretKind>();+ for (const key of PAYLOAD_KEYS) {+ const value = attrs[key];+ if (value === undefined || value === null) continue;+ for (const kind of detectSecretKinds(String(value))) {+ kinds.add(kind);+ }+ }+ return Array.from(kinds);+}diff --git a/src/client/src/lib/platform/governance/security-checks.ts b/src/client/src/lib/platform/governance/security-checks.tsnew file mode 100644index 00000000..ca96dc91--- /dev/null+++ b/src/client/src/lib/platform/governance/security-checks.ts@@ -0,0 +1,524 @@+import { createHash } from "crypto";+import {+ classifyGenerationHealth,+ matchesGenerationHealthChip,+} from "@/lib/platform/generation-health/classify";+import { fillTemplate } from "@/lib/platform/generation-health/format";+import {+ detectAgentLoops,+ spanCostOf,+ spanTokensOf,+ type AgentLoopSpan,+} from "@/lib/platform/agent-loop/classify";+import getMessage from "@/constants/messages";+import type {+ GovernanceFinding,+ GovernanceSeverity,+} from "@/types/governance-report";+import type { TraceHeirarchySpan } from "@/types/trace";+import { CODING_AGENT_ATTR } from "@/lib/platform/coding-agents/table-details";+import {+ classifySpanRole,+ readSpanAttr,+ spanDurationMs,+} from "./hierarchy";+import { extractResourceHint, matchingLoopSpans } from "./evidence";+import { buildCodingAgentFindings } from "./coding-agent-findings";++function stableFindingId(parts: string[]): string {+ return createHash("sha1").update(parts.join("|")).digest("hex").slice(0, 12);+}++function worstSeverity(+ findings: GovernanceFinding[]+): GovernanceSeverity | "none" {+ for (const level of ["critical", "major", "minor", "info"] as const) {+ if (findings.some((f) => f.severity === level)) return level;+ }+ return "none";+}++function uniqueSpanIds(ids: string[], limit = 12): string[] {+ const out: string[] = [];+ const seen = new Set<string>();+ for (const id of ids) {+ const trimmed = String(id || "").trim();+ if (!trimmed || seen.has(trimmed)) continue;+ seen.add(trimmed);+ out.push(trimmed);+ if (out.length >= limit) break;+ }+ return out;+}++export function buildSecurityFindings(+ spans: TraceHeirarchySpan[]+): GovernanceFinding[] {+ const m = getMessage();+ const findings: GovernanceFinding[] = [];+ const permissionModes = new Map<+ string,+ { spanIds: string[]; resource?: string }+ >();+ const classifications = new Map<+ string,+ { spanIds: string[]; kind: "disputed" | "personal" }+ >();++ for (const span of spans) {+ if (span.StatusCode === "STATUS_CODE_ERROR" || span.StatusCode === "ERROR") {+ findings.push({+ id: stableFindingId(["span_error", span.SpanId]),+ category: "span_error",+ severity: "major",+ summary: m.GOVERNANCE_FINDING_SPAN_ERROR_SUMMARY.replace(+ "{name}",+ span.SpanName || span.SpanId+ ),+ detail:+ span.StatusMessage ||+ m.GOVERNANCE_FINDING_SPAN_ERROR_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_SPAN_ERROR,+ resource: extractResourceHint(span) || undefined,+ span_refs: [span.SpanId],+ evidence: { status_code: span.StatusCode || "" },+ });+ }++ const health = classifyGenerationHealth(span.SpanAttributes || {});+ if (matchesGenerationHealthChip(health, "truncated")) {+ findings.push({+ id: stableFindingId(["truncated", span.SpanId]),+ category: "generation_health",+ severity: "minor",+ summary: m.GENERATION_HEALTH_TRUNCATED,+ detail: m.GENERATION_HEALTH_DETAIL_TRUNCATED,+ remediation: m.GOVERNANCE_REMEDIATION_GENERATION_HEALTH,+ span_refs: [span.SpanId],+ });+ }+ if (matchesGenerationHealthChip(health, "filtered")) {+ findings.push({+ id: stableFindingId(["filtered", span.SpanId]),+ category: "generation_health",+ severity: "minor",+ summary: m.GENERATION_HEALTH_FILTERED,+ detail: m.GENERATION_HEALTH_DETAIL_FILTERED,+ remediation: m.GOVERNANCE_REMEDIATION_GENERATION_HEALTH,+ span_refs: [span.SpanId],+ });+ }+ if (matchesGenerationHealthChip(health, "empty")) {+ findings.push({+ id: stableFindingId(["empty", span.SpanId]),+ category: "generation_health",+ severity: "major",+ summary: m.GENERATION_HEALTH_EMPTY,+ detail: m.GENERATION_HEALTH_DETAIL_EMPTY,+ remediation: m.GOVERNANCE_REMEDIATION_GENERATION_HEALTH,+ span_refs: [span.SpanId],+ });+ }+ if (health.modelSwap) {+ findings.push({+ id: stableFindingId(["swapped", span.SpanId]),+ category: "generation_health",+ severity: "major",+ summary: m.GENERATION_HEALTH_SWAPPED,+ detail: fillTemplate(m.GENERATION_HEALTH_DETAIL_SWAPPED, {+ requested: health.requestedModel,+ served: health.servedModel,+ }),+ remediation: m.GOVERNANCE_REMEDIATION_MODEL_SWAP,+ span_refs: [span.SpanId],+ evidence: {+ requested_model: health.requestedModel || "",+ served_model: health.servedModel || "",+ },+ });+ }++ const classification = readSpanAttr(span, [+ CODING_AGENT_ATTR.userClassification,+ ]);+ if (classification === "disputed" || classification === "personal") {+ const entry = classifications.get(classification) || {+ spanIds: [],+ kind: classification,+ };+ entry.spanIds.push(span.SpanId);+ classifications.set(classification, entry);+ }++ const permissionMode = readSpanAttr(span, [+ CODING_AGENT_ATTR.policyPermissionMode,+ ]);+ if (+ permissionMode &&+ !["default", "plan", "acceptEdits"].includes(permissionMode)+ ) {+ const entry = permissionModes.get(permissionMode) || {+ spanIds: [],+ resource: extractResourceHint(span) || undefined,+ };+ entry.spanIds.push(span.SpanId);+ if (!entry.resource) {+ entry.resource = extractResourceHint(span) || undefined;+ }+ permissionModes.set(permissionMode, entry);+ }+ }++ for (const [mode, entry] of Array.from(permissionModes.entries())) {+ findings.push({+ id: stableFindingId(["permission_mode", mode]),+ category: "policy",+ severity: "info",+ summary: m.GOVERNANCE_FINDING_PERMISSION_MODE_SUMMARY.replace(+ "{mode}",+ mode+ ),+ detail: m.GOVERNANCE_FINDING_PERMISSION_MODE_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_PERMISSION_MODE,+ resource: entry.resource,+ span_refs: uniqueSpanIds(entry.spanIds),+ evidence: {+ permission_mode: mode,+ span_count: entry.spanIds.length,+ },+ });+ }++ for (const [kind, entry] of Array.from(classifications.entries())) {+ if (kind === "disputed") {+ findings.push({+ id: stableFindingId(["classification_disputed"]),+ category: "coding_agent",+ severity: "major",+ summary: m.GOVERNANCE_FINDING_CLASSIFICATION_DISPUTED_SUMMARY,+ detail: m.GOVERNANCE_FINDING_CLASSIFICATION_DISPUTED_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_CLASSIFICATION,+ span_refs: uniqueSpanIds(entry.spanIds),+ });+ } else {+ findings.push({+ id: stableFindingId(["classification_personal"]),+ category: "coding_agent",+ severity: "info",+ summary: m.GOVERNANCE_FINDING_CLASSIFICATION_PERSONAL_SUMMARY,+ detail: m.GOVERNANCE_FINDING_CLASSIFICATION_PERSONAL_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_CLASSIFICATION,+ span_refs: uniqueSpanIds(entry.spanIds),+ });+ }+ }++ const loopSpans: AgentLoopSpan[] = spans.map((span) => ({+ traceId: span.TraceId,+ SpanId: span.SpanId,+ SpanAttributes: span.SpanAttributes,+ ResourceAttributes: span.ResourceAttributes,+ Timestamp: span.Timestamp,+ }));+ const loops = detectAgentLoops(loopSpans);+ for (const loop of loops) {+ const matched = matchingLoopSpans(spans, loop.toolName, loop.fingerprint);+ const spanIds = uniqueSpanIds(matched.map((s) => s.SpanId));+ if (!spanIds.length) continue;+ const sample = matched[0];+ const resource =+ (sample && extractResourceHint(sample)) ||+ extractResourceHint({+ SpanAttributes: {+ "gen_ai.tool.args": loop.fingerprint,+ "gen_ai.tool.name": loop.toolName,+ },+ }) ||+ undefined;+ const ordered = matched+ .slice()+ .sort(+ (a, b) =>+ new Date(String(a.Timestamp || 0)).getTime() -+ new Date(String(b.Timestamp || 0)).getTime()+ );+ const wastedDurationMs = ordered+ .slice(1)+ .reduce((sum, span) => sum + spanDurationMs(span), 0);+ const usageReported = loop.wastedTokens > 0 || loop.wastedCost > 0;+ const evidence: Record<string, string | number | boolean> = {+ tool_name: loop.toolName,+ count: loop.count,+ args_fingerprint: loop.fingerprint.slice(0, 180),+ usage_reported: usageReported,+ };+ if (usageReported) {+ evidence.wasted_tokens = loop.wastedTokens;+ evidence.wasted_cost = loop.wastedCost;+ }+ if (wastedDurationMs > 0) {+ evidence.wasted_duration_ms = Math.round(wastedDurationMs);+ }+ const detail = usageReported+ ? m.GOVERNANCE_FINDING_AGENT_LOOP_DETAIL.replace(+ "{wasted_tokens}",+ String(loop.wastedTokens)+ ).replace("{wasted_cost}", loop.wastedCost.toFixed(4))+ : m.GOVERNANCE_FINDING_AGENT_LOOP_DETAIL_NO_USAGE.replace(+ "{count}",+ String(loop.count)+ ).replace(+ "{duration_suffix}",+ wastedDurationMs > 0+ ? m.GOVERNANCE_FINDING_AGENT_LOOP_DURATION_SUFFIX.replace(+ "{duration}",+ `${Math.round(wastedDurationMs)}ms`+ )+ : ""+ );+ findings.push({+ id: stableFindingId(["agent_loop", loop.toolName, loop.fingerprint]),+ category: "agent_loop",+ severity: loop.count >= 8 ? "critical" : loop.count >= 5 ? "major" : "minor",+ summary: m.GOVERNANCE_FINDING_AGENT_LOOP_SUMMARY+ .replace("{tool}", loop.toolName)+ .replace("{count}", String(loop.count)),+ detail,+ remediation: m.GOVERNANCE_REMEDIATION_AGENT_LOOP,+ resource,+ span_refs: spanIds,+ evidence,+ });+ }++ const toolCount = spans.filter((s) => classifySpanRole(s) === "tool").length;+ if (toolCount >= 25) {+ findings.push({+ id: stableFindingId(["harness_tool_burst"]),+ category: "harness",+ severity: "minor",+ summary: m.GOVERNANCE_FINDING_TOOL_BURST_SUMMARY.replace(+ "{count}",+ String(toolCount)+ ),+ detail: m.GOVERNANCE_FINDING_TOOL_BURST_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_TOOL_BURST,+ span_refs: uniqueSpanIds(+ spans+ .filter((s) => classifySpanRole(s) === "tool")+ .map((s) => s.SpanId)+ ),+ });+ }++ const deepSpans = spans.filter((s) => (s.children || []).length >= 8);+ if (deepSpans.length) {+ findings.push({+ id: stableFindingId(["harness_wide_branch"]),+ category: "harness",+ severity: "info",+ summary: m.GOVERNANCE_FINDING_WIDE_BRANCH_SUMMARY,+ detail: m.GOVERNANCE_FINDING_WIDE_BRANCH_DETAIL,+ remediation: m.GOVERNANCE_REMEDIATION_WIDE_BRANCH,+ span_refs: uniqueSpanIds(deepSpans.map((s) => s.SpanId)),+ });+ }++ findings.push(...buildCodingAgentFindings(spans));+ return findings;+}++export function buildHarnessMetrics(+ root: TraceHeirarchySpan,+ spans: TraceHeirarchySpan[]+): import("@/types/governance-report").GovernanceHarnessReport {+ const models = new Set<string>();+ const tools = new Set<string>();+ let llmCallCount = 0;+ let toolCallCount = 0;+ let retrievalCallCount = 0;+ let embeddingCallCount = 0;+ let databaseCallCount = 0;+ let httpCallCount = 0;+ let errorCount = 0;+ let summedCostUsd = 0;+ let summedTokens = 0;+ let totalDurationMs = 0;++ for (const span of spans) {+ const role = classifySpanRole(span);+ if (role === "llm") llmCallCount++;+ if (role === "tool") toolCallCount++;+ if (role === "retrieval") retrievalCallCount++;+ if (role === "embedding") embeddingCallCount++;+ if (role === "database") databaseCallCount++;+ if (role === "http") httpCallCount++;+ if (+ span.StatusCode === "STATUS_CODE_ERROR" ||+ span.StatusCode === "ERROR"+ ) {+ errorCount++;+ }+ totalDurationMs += spanDurationMs(span);+ const model = readSpanAttr(span, [+ "gen_ai.request.model",+ "gen_ai.response.model",+ ]);+ if (model) models.add(model);+ const tool = readSpanAttr(span, [+ "gen_ai.tool.name",+ "gen_ai.tool.call.name",+ "coding_agent.tool.name",+ ]);+ if (tool) tools.add(tool);++ const attrs = {+ ...(span.ResourceAttributes || {}),+ ...(span.SpanAttributes || {}),+ };+ const attrCost = spanCostOf(attrs);+ const rowCost = Number(span.Cost);+ const cost =+ Number.isFinite(rowCost) && rowCost > 0+ ? rowCost+ : attrCost > 0+ ? attrCost+ : 0;+ if (cost > 0) summedCostUsd += cost;+ summedTokens += spanTokensOf(attrs);+ }++ // Coding-agent session roots carry authoritative rollups (tokens always+ // for Cursor; USD only when the vendor sends it). Prefer the greater of+ // the session rollup vs summed child attrs so we do not under-count.+ const sessionCost = Number(+ readSpanAttr(root, [CODING_AGENT_ATTR.sessionCostUsd, "gen_ai.usage.cost"]) ||+ 0+ );+ const sessionTokens = Number(+ readSpanAttr(root, [+ "gen_ai.usage.total_tokens",+ ]) || 0+ );+ const sessionInput = Number(+ readSpanAttr(root, ["gen_ai.usage.input_tokens"]) || 0+ );+ const sessionOutput = Number(+ readSpanAttr(root, ["gen_ai.usage.output_tokens"]) || 0+ );+ const sessionTokenTotal =+ sessionTokens > 0 ? sessionTokens : sessionInput + sessionOutput;+ const totalCostUsd = Math.max(+ summedCostUsd,+ Number.isFinite(sessionCost) ? sessionCost : 0+ );+ const totalTokens = Math.max(summedTokens, sessionTokenTotal);++ const loopSpans: AgentLoopSpan[] = spans.map((span) => ({+ traceId: span.TraceId,+ SpanAttributes: span.SpanAttributes,+ ResourceAttributes: span.ResourceAttributes,+ Timestamp: span.Timestamp,+ }));+ const loops = detectAgentLoops(loopSpans);+ const topLoop = loops[0];+ let topLoopDurationMs = 0;+ if (topLoop) {+ const matched = matchingLoopSpans(+ spans,+ topLoop.toolName,+ topLoop.fingerprint+ );+ const ordered = matched+ .slice()+ .sort(+ (a, b) =>+ new Date(String(a.Timestamp || 0)).getTime() -+ new Date(String(b.Timestamp || 0)).getTime()+ );+ topLoopDurationMs = ordered+ .slice(1)+ .reduce((sum, span) => sum + spanDurationMs(span), 0);+ }++ return {+ span_count: spans.length,+ max_depth: maxHierarchyDepth(root),+ llm_call_count: llmCallCount,+ tool_call_count: toolCallCount,+ retrieval_call_count: retrievalCallCount,+ embedding_call_count: embeddingCallCount,+ database_call_count: databaseCallCount,+ http_call_count: httpCallCount,+ error_count: errorCount,+ total_cost_usd: totalCostUsd,+ cost_reported: totalCostUsd > 0,+ total_tokens: totalTokens,+ total_duration_ms: totalDurationMs,+ models_used: Array.from(models).sort(),+ tools_used: Array.from(tools).sort(),+ permission_mode: readSpanAttr(root, [CODING_AGENT_ATTR.policyPermissionMode]),+ content_capture_mode: readSpanAttr(root, [+ CODING_AGENT_ATTR.contentCaptureMode,+ ]),+ user_classification: readSpanAttr(root, [+ CODING_AGENT_ATTR.userClassification,+ ]),+ agent_loop: topLoop+ ? {+ tool_name: topLoop.toolName,+ count: topLoop.count,+ wasted_tokens: topLoop.wastedTokens,+ wasted_cost: topLoop.wastedCost,+ wasted_duration_ms: topLoopDurationMs+ ? Math.round(topLoopDurationMs)+ : undefined,+ usage_reported:+ topLoop.wastedTokens > 0 || topLoop.wastedCost > 0,+ }+ : undefined,+ };+}++function maxHierarchyDepth(span: TraceHeirarchySpan, depth = 1): number {+ const children = span.children || [];+ if (!children.length) return depth;+ return Math.max(...children.map((child) => maxHierarchyDepth(child, depth + 1)));+}++export function summarizeGovernanceReport(+ findings: GovernanceFinding[],+ ruleMatchCount: number,+ evaluationCount: number+): { risk_level: GovernanceSeverity | "none"; summary: string } {+ const risk_level = worstSeverity(findings);+ const m = getMessage();+ if (risk_level === "none" && ruleMatchCount === 0 && evaluationCount === 0) {+ return {+ risk_level: "none",+ summary: m.GOVERNANCE_SUMMARY_CLEAN,+ };+ }+ const parts: string[] = [];+ if (findings.length) {+ parts.push(+ m.GOVERNANCE_SUMMARY_FINDINGS.replace("{count}", String(findings.length))+ );+ }+ if (ruleMatchCount) {+ parts.push(+ m.GOVERNANCE_SUMMARY_RULES.replace("{count}", String(ruleMatchCount))+ );+ }+ if (evaluationCount) {+ parts.push(+ m.GOVERNANCE_SUMMARY_EVALS.replace("{count}", String(evaluationCount))+ );+ }+ return {+ risk_level,+ summary: parts.join(" · ") || m.GOVERNANCE_SUMMARY_MIXED,+ };+}++export { worstSeverity };diff --git a/src/client/src/lib/platform/governance/trace-report.ts b/src/client/src/lib/platform/governance/trace-report.tsnew file mode 100644index 00000000..ecb214cb--- /dev/null+++ b/src/client/src/lib/platform/governance/trace-report.ts@@ -0,0 +1,282 @@+import Sanitizer from "@/utils/sanitizer";+import { escapeClickHouseString } from "@/lib/clickhouse-escape";+import { dataCollector } from "../common";+import { evaluateRules } from "../rule-engine/evaluate";+import { OPENLIT_RULES_TABLE_NAME } from "../rule-engine/table-details";+import { OPENLIT_EVALUATION_TABLE_NAME } from "../evaluation/table-details";+import { EVALUATION_SOURCE } from "@/constants/evaluation-sources";+import getMessage from "@/constants/messages";+import { getTraceHierarchy } from "../traces/read";+import type {+ GovernanceEvaluationRow,+ GovernanceRuleEntityType,+ GovernanceRuleMatch,+ TraceGovernanceReport,+} from "@/types/governance-report";+import type { TraceHeirarchySpan } from "@/types/trace";+import {+ flattenHierarchy,+ ruleFieldsFromHierarchySpan,+} from "./hierarchy";+import {+ buildHarnessMetrics,+ buildSecurityFindings,+ summarizeGovernanceReport,+} from "./security-checks";+import { createHash } from "crypto";++export const GOVERNANCE_MAX_SPANS_RULE_EVAL = 100;+export const GOVERNANCE_MAX_SPAN_IDS_EVAL_QUERY = 200;++const RULE_ENTITY_TYPES: GovernanceRuleEntityType[] = [+ "context",+ "prompt",+ "evaluation",+ "alert",+];++const EVAL_FAIL_VERDICTS = new Set([+ "fail",+ "failed",+ "no",+ "unsafe",+ "toxic",+ "biased",+ "hallucinated",+]);++async function loadRuleNames(+ ruleIds: string[],+ databaseConfigId?: string+): Promise<Map<string, string>> {+ const names = new Map<string, string>();+ if (!ruleIds.length) return names;+ const safeIds = ruleIds+ .map((id) => `'${escapeClickHouseString(Sanitizer.sanitizeValue(id))}'`)+ .join(",");+ const query = `+ SELECT id, name FROM ${OPENLIT_RULES_TABLE_NAME}+ WHERE id IN (${safeIds});+ `;+ const { data, err } = await dataCollector({ query }, "query", databaseConfigId);+ if (err || !data) return names;+ for (const row of data as Array<{ id?: string; name?: string }>) {+ if (row.id) names.set(row.id, row.name || row.id);+ }+ return names;+}++type RuleMatchTemplate = Omit<GovernanceRuleMatch, "span_id" | "matched_fields">;++async function evaluateRulesForFields(+ fields: Record<string, string | number | boolean>,+ databaseConfigId?: string+): Promise<RuleMatchTemplate[]> {+ if (!Object.keys(fields).length) return [];++ const matches: RuleMatchTemplate[] = [];+ const seenRules = new Set<string>();++ for (const entityType of RULE_ENTITY_TYPES) {+ try {+ const result = await evaluateRules(+ { fields, entity_type: entityType, include_entity_data: false },+ databaseConfigId+ );+ for (const ruleId of result.matchingRuleIds || []) {+ if (seenRules.has(ruleId)) continue;+ seenRules.add(ruleId);+ const entities = (result.entities || [])+ .filter((e) => e.rule_id === ruleId)+ .map((e) => ({+ entity_type: e.entity_type as GovernanceRuleEntityType,+ entity_id: e.entity_id,+ }));+ matches.push({+ rule_id: ruleId,+ entities,+ });+ }+ } catch {+ // Rule evaluation is best-effort for governance surfacing.+ }+ }++ return matches;+}++async function loadEvaluationsForSpans(+ spanIds: string[],+ databaseConfigId?: string+): Promise<GovernanceEvaluationRow[]> {+ if (!spanIds.length) return [];+ const safeIds = spanIds+ .map((id) => `'${escapeClickHouseString(Sanitizer.sanitizeValue(id))}'`)+ .join(",");+ const query = `+ SELECT+ span_id AS span_id,+ arrayMap(+ (e, c, ex, v) ->+ map(+ 'evaluation', e,+ 'score', if(mapContains(scores, e), toString(scores[e]), ''),+ 'classification', c,+ 'explanation', ex,+ 'verdict', v+ ),+ evaluationData.evaluation,+ evaluationData.classification,+ evaluationData.explanation,+ evaluationData.verdict+ ) AS evaluations+ FROM ${OPENLIT_EVALUATION_TABLE_NAME}+ WHERE span_id IN (${safeIds})+ AND meta['source'] NOT IN (+ '${EVALUATION_SOURCE.MANUAL_FEEDBACK}',+ '${EVALUATION_SOURCE.AUTO_SKIPPED}'+ )+ ORDER BY created_at DESC+ LIMIT 200;+ `;+ const { data, err } = await dataCollector({ query }, "query", databaseConfigId);+ if (err || !data) return [];++ const rows: GovernanceEvaluationRow[] = [];+ for (const row of data as Array<Record<string, unknown>>) {+ const spanId = String(row.span_id || "");+ const evaluations = (row.evaluations as Array<Record<string, string>>) || [];+ for (const item of evaluations) {+ const evaluationType = String(item.evaluation || "").trim();+ if (!evaluationType) continue;+ const scoreRaw = item.score;+ const score =+ scoreRaw && scoreRaw !== ""+ ? Number(scoreRaw)+ : undefined;+ rows.push({+ span_id: spanId,+ evaluation_type: evaluationType,+ score: Number.isFinite(score) ? score : undefined,+ classification: item.classification,+ verdict: item.verdict,+ explanation: item.explanation,+ });+ }+ }+ return rows;+}++function evaluationFindings(+ evaluations: GovernanceEvaluationRow[]+): import("@/types/governance-report").GovernanceFinding[] {+ const findings: import("@/types/governance-report").GovernanceFinding[] = [];+ for (const row of evaluations) {+ const verdict = String(row.verdict || row.classification || "").toLowerCase();+ if (!verdict || !EVAL_FAIL_VERDICTS.has(verdict)) continue;+ findings.push({+ id: createHash("sha1")+ .update(`${row.span_id}:${row.evaluation_type}:${verdict}`)+ .digest("hex")+ .slice(0, 12),+ category: "evaluation",+ severity:+ row.evaluation_type === "toxicity" ||+ row.evaluation_type === "safety"+ ? "critical"+ : "major",+ summary: `${row.evaluation_type} flagged on span`,+ detail: row.explanation || `Verdict: ${verdict}`,+ remediation: getMessage().GOVERNANCE_REMEDIATION_EVALUATION,+ span_refs: [row.span_id],+ evidence: {+ evaluation_type: row.evaluation_type,+ verdict,+ },+ });+ }+ return findings;+}++export async function buildTraceGovernanceReport(+ spanId: string,+ opts?: { traceId?: string; environment?: string; databaseConfigId?: string }+): Promise<{ err?: string; report?: TraceGovernanceReport }> {+ const hierarchyResult = await getTraceHierarchy(spanId, {+ traceId: opts?.traceId,+ environment: opts?.environment,+ });+ if (hierarchyResult.err) {+ return { err: String(hierarchyResult.err) };+ }+ const root = hierarchyResult.record as TraceHeirarchySpan;+ if (!root?.SpanId) {+ return { err: "Hierarchy root not found" };+ }++ const spans = flattenHierarchy(root);+ const spanIds = spans.map((s) => s.SpanId).filter(Boolean);+ const spansForRules = spans.slice(0, GOVERNANCE_MAX_SPANS_RULE_EVAL);+ const spanIdsForEval = spanIds.slice(0, GOVERNANCE_MAX_SPAN_IDS_EVAL_QUERY);+ const analysisLimited =+ spans.length > GOVERNANCE_MAX_SPANS_RULE_EVAL ||+ spanIds.length > GOVERNANCE_MAX_SPAN_IDS_EVAL_QUERY;++ // Rule evaluation with field-map deduplication across spans+ const fieldsCache = new Map<string, RuleMatchTemplate[]>();+ const ruleMatches: GovernanceRuleMatch[] = [];++ for (const span of spansForRules) {+ const fields = ruleFieldsFromHierarchySpan(span);+ const cacheKey = createHash("sha1").update(JSON.stringify(fields)).digest("hex");+ let templates = fieldsCache.get(cacheKey);+ if (!templates) {+ templates = await evaluateRulesForFields(fields, opts?.databaseConfigId);+ fieldsCache.set(cacheKey, templates);+ }+ for (const template of templates) {+ ruleMatches.push({+ ...template,+ span_id: span.SpanId,+ matched_fields: fields,+ });+ }+ }++ const ruleIds = Array.from(new Set(ruleMatches.map((m) => m.rule_id)));+ const ruleNames = await loadRuleNames(ruleIds, opts?.databaseConfigId);+ for (const match of ruleMatches) {+ match.rule_name = ruleNames.get(match.rule_id) || match.rule_id;+ }++ const evaluations = await loadEvaluationsForSpans(+ spanIdsForEval,+ opts?.databaseConfigId+ );+ const security = [+ ...buildSecurityFindings(spans),+ ...evaluationFindings(evaluations),+ ];+ const harness = buildHarnessMetrics(root, spans);+ const { risk_level, summary } = summarizeGovernanceReport(+ security,+ ruleMatches.length,+ evaluations.length+ );++ return {+ report: {+ trace_id: root.TraceId || opts?.traceId || spanId,+ root_span_id: root.SpanId,+ risk_level,+ summary,+ harness,+ rules: ruleMatches,+ security,+ evaluations,+ finding_count: security.length,+ rule_match_count: ruleMatches.length,+ analysis_limited: analysisLimited || undefined,+ },+ };+}diff --git a/src/client/src/lib/platform/governance/validate.ts b/src/client/src/lib/platform/governance/validate.tsnew file mode 100644index 00000000..fa626779--- /dev/null+++ b/src/client/src/lib/platform/governance/validate.ts@@ -0,0 +1,18 @@+export const GOVERNANCE_SPAN_ID_MAX_LENGTH = 128;++const SPAN_ID_PATTERN = /^[a-zA-Z0-9._-]+$/;++/**+ * Validates span identifiers before governance queries. Rejects empty,+ * oversized, or injection-prone values while allowing standard OTel ids.+ */+export function validateGovernanceSpanId(spanId: string): string | null {+ const trimmed = String(spanId || "").trim();+ if (!trimmed || trimmed.length > GOVERNANCE_SPAN_ID_MAX_LENGTH) {+ return null;+ }+ if (!SPAN_ID_PATTERN.test(trimmed)) {+ return null;+ }+ return trimmed;+}diff --git a/src/client/src/lib/platform/intelligence/source.ts b/src/client/src/lib/platform/intelligence/source.tsnew file mode 100644index 00000000..565d20c1--- /dev/null+++ b/src/client/src/lib/platform/intelligence/source.ts@@ -0,0 +1,24 @@+import { resolveSignalSource } from "@/lib/telemetry-source";++/** Resolve the ClickHouse that owns intelligence-layer tables (rules, evals, chat). */+export async function resolveIntelligenceClickHouseDbConfigId(options?: {+ environment?: string | null;+ projectId?: string | null;+ dbConfigId?: string;+}): Promise<string | null> {+ const resolution = await resolveSignalSource("intelligence", {+ environment: options?.environment ?? undefined,+ ...(options?.projectId !== undefined+ ? { projectId: options.projectId }+ : {}),+ ...(options?.dbConfigId ? { dbConfigId: options.dbConfigId } : {}),+ });+ if (+ resolution.hasSource &&+ resolution.descriptor.type === "clickhouse" &&+ resolution.descriptor.dbConfigId+ ) {+ return resolution.descriptor.dbConfigId;+ }+ return null;+}diff --git a/src/client/src/lib/platform/openplait/index.ts b/src/client/src/lib/platform/openplait/index.tsindex befcf524..f9294522 100644--- a/src/client/src/lib/platform/openplait/index.ts+++ b/src/client/src/lib/platform/openplait/index.ts@@ -7,6 +7,7 @@ import {import {ClickHouseAdapter,OPENLIT_CLICKHOUSE_DATASETS,+ OTEL_CLICKHOUSE_DATASETS,type ClickHouseAdapterConfig,} from "@openplait/adapter-clickhouse";import { DatasourceRegistry, OpenPlaitRuntime } from "@openplait/runtime";@@ -98,7 +99,7 @@ function connectionConfig(process.env.OPENPLAIT_CLICKHOUSE_MAX_ROWS_TO_READ,DEFAULT_MAX_ROWS_TO_READ),- datasets: [...OPENLIT_CLICKHOUSE_DATASETS],+ datasets: [...OTEL_CLICKHOUSE_DATASETS, ...OPENLIT_CLICKHOUSE_DATASETS],};}diff --git a/src/client/src/lib/platform/request/index.ts b/src/client/src/lib/platform/request/index.tsindex 1af63234..da76a0b3 100644--- a/src/client/src/lib/platform/request/index.ts+++ b/src/client/src/lib/platform/request/index.ts@@ -1,4 +1,5 @@-import { MetricParams, dataCollector, OTEL_TRACES_TABLE_NAME } from "../common";+import { MetricParams } from "../common";+import { queryTracesSql, tracesTableRef } from "../traces/clickhouse-read";import {getTraceMappingKeyFullPath,getTraceMappingKeyFullPaths,@@ -70,13 +71,14 @@ export function getGroupByExpression(groupBy: string): string | null {export async function getRequestPerTime(params: MetricParams) {const { start, end } = params.timeLimit;const dateTrunc = dateTruncGroupingLogic(end as Date, start as Date);+ const table = await tracesTableRef(params.databaseConfigId);const query = `SELECTCAST(COUNT(*) AS INTEGER) AS total,formatDateTime(DATE_TRUNC('${dateTrunc}', Timestamp), '%Y/%m/%d %R') AS request_timeFROM- ${OTEL_TRACES_TABLE_NAME}+ ${table}WHERE ${getFilterWhereCondition({ ...params, operationType: "llm" }, true)}GROUP BYrequest_time@@ -84,15 +86,16 @@ export async function getRequestPerTime(params: MetricParams) {request_time;`;- return dataCollector({ query }, "query", params.databaseConfigId);+ return queryTracesSql(query, params.databaseConfigId);}export async function getTotalRequests(params: MetricParams) {+ const table = await tracesTableRef(params.databaseConfigId);const commonQuery = (parameters: MetricParams) => `SELECTCOUNT(*) AS total_requests,'${params.timeLimit.start}' as start_date- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${table}WHERE ${getFilterWhereCondition(parameters, true)}`;@@ -113,17 +116,18 @@ export async function getTotalRequests(params: MetricParams) {current_data.start_date = previous_day.start_date;`;- return dataCollector({ query }, "query", params.databaseConfigId);+ return queryTracesSql(query, params.databaseConfigId);}export async function getAverageRequestDuration(params: MetricParams) {+ const table = await tracesTableRef(params.databaseConfigId);const keyPath = `${getTraceMappingKeyFullPath("requestDuration")}`;const commonQuery = (parameters: MetricParams) => `SELECTAVG(${keyPath}) AS average_duration,'${params.timeLimit.start}' as start_date- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${table}WHERE ${getFilterWhereCondition(parameters, true)} AND isFinite(${keyPath})`;@@ -146,10 +150,11 @@ export async function getAverageRequestDuration(params: MetricParams) {current_data.start_date = previous_day.start_date;`;- return dataCollector({ query }, "query", params.databaseConfigId);+ return queryTracesSql(query, params.databaseConfigId);}export async function getRequestsConfig(params: MetricParams) {+ const table = await tracesTableRef(params.databaseConfigId);const select: string[] = [];// Provider filter source list. Folds three attribute namespaces@@ -226,13 +231,14 @@ export async function getRequestsConfig(params: MetricParams) {`arrayFilter(x -> x != '', ARRAY_AGG(DISTINCT ResourceAttributes['deployment.environment'])) AS environments`);- const query = `SELECT ${select.join(", ")} FROM ${OTEL_TRACES_TABLE_NAME}+ const query = `SELECT ${select.join(", ")} FROM ${table}WHERE ${getFilterWhereCondition(params, true)}`;- return dataCollector({ query }, "query", params.databaseConfigId);+ return queryTracesSql(query, params.databaseConfigId);}export async function getRequests(params: MetricParams) {+ const table = await tracesTableRef(params.databaseConfigId);const { limit = 10, offset = 0 } = params;const oneRowPerTrace =hasGenerationHealthFilter(params.selectedConfig?.generationHealth) ||@@ -241,12 +247,11 @@ export async function getRequests(params: MetricParams) {? "CAST(uniqExact(TraceId) AS INTEGER)": "CAST(COUNT(*) AS INTEGER)";- const countQuery = `SELECT ${totalExpr} AS total FROM ${OTEL_TRACES_TABLE_NAME}+ const countQuery = `SELECT ${totalExpr} AS total FROM ${table}WHERE ${getFilterWhereCondition(params, true)}`;- const { data: dataTotal, err: errTotal } = await dataCollector(- { query: countQuery },- "query",+ const { data: dataTotal, err: errTotal } = await queryTracesSql(+ countQuery,params.databaseConfigId);if (errTotal) {@@ -255,7 +260,7 @@ export async function getRequests(params: MetricParams) {};}- const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME}+ const query = `SELECT * FROM ${table}WHERE ${getFilterWhereCondition(params, true)}${params.sorting && params.sorting.type && params.sorting.direction? params.sorting.type.includes("cost")@@ -269,11 +274,7 @@ export async function getRequests(params: MetricParams) {LIMIT ${limit}OFFSET ${offset}`;- const { data, err } = await dataCollector(- { query },- "query",- params.databaseConfigId- );+ const { data, err } = await queryTracesSql(query, params.databaseConfigId);return {err,records: data,@@ -282,11 +283,12 @@ export async function getRequests(params: MetricParams) {}export async function getRequestViaSpanId(spanId: string, databaseConfigId?: string) {+ const table = await tracesTableRef(databaseConfigId);const safeSpanId = escapeClickHouseString(String(spanId ?? ""));- const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME}+ const query = `SELECT * FROM ${table}WHERE SpanId='${safeSpanId}'`;- const { data, err } = await dataCollector({ query }, "query", databaseConfigId);+ const { data, err } = await queryTracesSql(query, databaseConfigId);return {err,record: (data as unknown[])?.[0],@@ -294,12 +296,13 @@ export async function getRequestViaSpanId(spanId: string, databaseConfigId?: str}export async function getRequestViaTraceId(traceId: string, databaseConfigId?: string) {+ const table = await tracesTableRef(databaseConfigId);const safeTraceId = escapeClickHouseString(String(traceId ?? ""));- const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME} WHERE ${getTraceMappingKeyFullPath(+ const query = `SELECT * FROM ${table} WHERE ${getTraceMappingKeyFullPath("id")}='${safeTraceId}'`;- const { data, err } = await dataCollector({ query }, "query", databaseConfigId);+ const { data, err } = await queryTracesSql(query, databaseConfigId);return {err,record: (data as unknown[])?.[0],@@ -307,6 +310,7 @@ export async function getRequestViaTraceId(traceId: string, databaseConfigId?: s}export async function getHeirarchyViaSpanId(spanId: string, databaseConfigId?: string) {+ const table = await tracesTableRef(databaseConfigId);// Step 1: resolve the source span. We need:// - TraceId (the usual "show every span in the trace" path)// - coding_agent.session.id (so coding-agent sessions whose CLI@@ -326,13 +330,12 @@ export async function getHeirarchyViaSpanId(spanId: string, databaseConfigId?: snullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),nullIf(SpanAttributes['coding_agent.agent.parent_id'], '')) AS CodingParentId- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${table}WHERE SpanId = '${safeSpanId}'LIMIT 1`;- const { data: sourceData, err: sourceErr } = await dataCollector(- { query: sourceSpanQuery },- "query",+ const { data: sourceData, err: sourceErr } = await queryTracesSql(+ sourceSpanQuery,databaseConfigId);@@ -399,7 +402,7 @@ export async function getHeirarchyViaSpanId(spanId: string, databaseConfigId?: s? `SELECT * FROM (SELECT ${spanSelectColumns}- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${table}WHERE ${filterClause}ORDER BY Timestamp DESCLIMIT 8000@@ -407,7 +410,7 @@ export async function getHeirarchyViaSpanId(spanId: string, databaseConfigId?: sUNION DISTINCTSELECT * FROM (SELECT ${spanSelectColumns}- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${table}WHERE ${filterClause}AND (notEmpty(SpanAttributes['gen_ai.input.messages'])@@ -420,14 +423,13 @@ export async function getHeirarchyViaSpanId(spanId: string, databaseConfigId?: s`: `SELECT ${spanSelectColumns}- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${table}WHERE ${filterClause}ORDER BY Timestamp ASCLIMIT 5000`;- const { data: allSpansRaw, err: allSpansErr } = await dataCollector(- { query: allSpansQuery },- "query",+ const { data: allSpansRaw, err: allSpansErr } = await queryTracesSql(+ allSpansQuery,databaseConfigId);@@ -554,14 +556,16 @@ function buildCodingSessionHierarchy(spans: any[], sessionId: string) {}export async function getRequestExist(databaseConfigId?: string) {- const query = `SELECT COUNT(*) AS total_requests FROM ${OTEL_TRACES_TABLE_NAME}`;- return dataCollector({ query }, "query", databaseConfigId);+ const table = await tracesTableRef(databaseConfigId);+ const query = `SELECT COUNT(*) AS total_requests FROM ${table}`;+ return queryTracesSql(query, databaseConfigId);}export async function getAttributeKeys(params: MetricParams) {+ const table = await tracesTableRef(params.databaseConfigId);const spanKeysQuery = `SELECT DISTINCT arrayJoin(mapKeys(SpanAttributes)) AS key- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${table}WHERE ${getFilterWhereCondition(params, true)}ORDER BY keyLIMIT 500@@ -569,19 +573,15 @@ export async function getAttributeKeys(params: MetricParams) {const resourceKeysQuery = `SELECT DISTINCT arrayJoin(mapKeys(ResourceAttributes)) AS key- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${table}WHERE ${getFilterWhereCondition(params, true)}ORDER BY keyLIMIT 500`;const [spanResult, resourceResult] = await Promise.all([- dataCollector({ query: spanKeysQuery }, "query", params.databaseConfigId),- dataCollector(- { query: resourceKeysQuery },- "query",- params.databaseConfigId- ),+ queryTracesSql(spanKeysQuery, params.databaseConfigId),+ queryTracesSql(resourceKeysQuery, params.databaseConfigId),]);return {@@ -592,6 +592,7 @@ export async function getAttributeKeys(params: MetricParams) {}export async function getGroupedRequests(params: MetricParams, groupBy: string) {+ const table = await tracesTableRef(params.databaseConfigId);const expr = getGroupByExpression(groupBy);if (!expr) {return {@@ -606,10 +607,10 @@ export async function getGroupedRequests(params: MetricParams, groupBy: string)CAST(SUM(toFloat64OrZero(SpanAttributes['gen_ai.usage.cost'])) AS FLOAT) AS total_cost,CAST(SUM(toInt64OrZero(SpanAttributes['gen_ai.usage.total_tokens'])) AS INTEGER) AS total_tokens,CAST(AVG(Duration) * 1e-9 AS FLOAT) AS avg_duration_seconds- FROM ${OTEL_TRACES_TABLE_NAME}+ FROM ${table}WHERE ${getFilterWhereCondition(params, true)}GROUP BY group_valueORDER BY count DESC`;- return dataCollector({ query }, "query", params.databaseConfigId);+ return queryTracesSql(query, params.databaseConfigId);}diff --git a/src/client/src/lib/platform/traces/clickhouse-read.ts b/src/client/src/lib/platform/traces/clickhouse-read.tsnew file mode 100644index 00000000..1fc1cf08--- /dev/null+++ b/src/client/src/lib/platform/traces/clickhouse-read.ts@@ -0,0 +1,39 @@+import { connectorDataCollector, type DataCollectorType } from "../common";+import {+ queryConnectorTraces,+ resolveTracesTableRef,+} from "@/lib/platform/connectors/datasource/clickhouse/direct-read";++/** Qualified `database.otel_traces` for the traces signal ClickHouse binding. */+export async function tracesTableRef(databaseConfigId?: string): Promise<string> {+ return resolveTracesTableRef(databaseConfigId);+}++/** Run trace-table SQL on the direct ClickHouse client (bypasses OpenPlait). */+export async function queryTracesSql(+ query: string,+ databaseConfigId?: string+): Promise<DataCollectorType> {+ return queryConnectorTraces(query, databaseConfigId);+}++/** Convenience for intelligence/cron callers that need traces routing first. */+export async function queryTracesSqlForProject(+ query: string,+ options?: {+ environment?: string | null;+ projectId?: string | null;+ dbConfigId?: string;+ }+): Promise<DataCollectorType> {+ const { resolveCodingAgentsClickHouseDbConfigId } = await import(+ "@/lib/platform/coding-agents/source"+ );+ const routed =+ await resolveCodingAgentsClickHouseDbConfigId({+ environment: options?.environment,+ projectId: options?.projectId,+ dbConfigId: options?.dbConfigId,+ });+ return connectorDataCollector({ query }, "query", routed || options?.dbConfigId);+}diff --git a/src/client/src/types/governance-report.ts b/src/client/src/types/governance-report.tsnew file mode 100644index 00000000..e0c2172f--- /dev/null+++ b/src/client/src/types/governance-report.ts@@ -0,0 +1,94 @@+export type GovernanceSeverity = "info" | "minor" | "major" | "critical";++export type GovernanceFindingCategory =+ | "span_error"+ | "generation_health"+ | "agent_loop"+ | "evaluation"+ | "coding_agent"+ | "harness"+ | "policy";++export type GovernanceRuleEntityType =+ | "context"+ | "prompt"+ | "evaluation"+ | "alert";++export type GovernanceFinding = {+ id: string;+ category: GovernanceFindingCategory;+ severity: GovernanceSeverity;+ summary: string;+ detail: string;+ /** Deterministic next-step guidance derived from the finding category (no LLM). */+ remediation?: string;+ /** File path or other resource implicated by the finding, when known. */+ resource?: string;+ span_refs: string[];+ evidence?: Record<string, string | number | boolean>;+};++export type GovernanceRuleMatch = {+ rule_id: string;+ rule_name?: string;+ span_id: string;+ matched_fields: Record<string, string | number | boolean>;+ entities: Array<{+ entity_type: GovernanceRuleEntityType;+ entity_id: string;+ }>;+};++export type GovernanceEvaluationRow = {+ span_id: string;+ evaluation_type: string;+ score?: number;+ classification?: string;+ verdict?: string;+ explanation?: string;+};++export type GovernanceHarnessReport = {+ span_count: number;+ max_depth: number;+ llm_call_count: number;+ tool_call_count: number;+ retrieval_call_count: number;+ embedding_call_count: number;+ database_call_count: number;+ http_call_count: number;+ error_count: number;+ total_cost_usd: number;+ /** True when at least one span reported a positive USD cost attribute. */+ cost_reported?: boolean;+ total_tokens: number;+ total_duration_ms: number;+ models_used: string[];+ tools_used: string[];+ permission_mode?: string;+ content_capture_mode?: string;+ user_classification?: string;+ agent_loop?: {+ tool_name: string;+ count: number;+ wasted_tokens: number;+ wasted_cost: number;+ wasted_duration_ms?: number;+ usage_reported?: boolean;+ };+};++export type TraceGovernanceReport = {+ trace_id: string;+ root_span_id: string;+ risk_level: GovernanceSeverity | "none";+ summary: string;+ harness: GovernanceHarnessReport;+ rules: GovernanceRuleMatch[];+ security: GovernanceFinding[];+ evaluations: GovernanceEvaluationRow[];+ finding_count: number;+ rule_match_count: number;+ analysis_limited?: boolean;+};