Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: deepen Trace Governance with Otter merge, policy packs, and passport export (#1530)

Aman Agarwal6b3146685a3f
diff --git a/docs/docs.json b/docs/docs.json
index ed04a7b5..da6f93a9 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -89,6 +89,7 @@
"latest/openlit/observability/telemetry/overview",
"latest/openlit/observability/telemetry/traces",
"latest/openlit/observability/telemetry/ai-analysis",
+ "latest/openlit/observability/telemetry/trace-governance",
"latest/openlit/observability/telemetry/metrics",
"latest/openlit/observability/telemetry/logs"
]
@@ -116,7 +117,9 @@
"latest/openlit/coding-agents/sessions",
"latest/openlit/coding-agents/users",
"latest/openlit/coding-agents/privacy-and-governance",
- "latest/openlit/coding-agents/troubleshooting"
+ "latest/openlit/coding-agents/troubleshooting",
+ "latest/openlit/coding-agents/onboarding",
+ "latest/openlit/coding-agents/architecture"
]
}
]
diff --git a/docs/latest/openlit/coding-agents/privacy-and-governance.mdx b/docs/latest/openlit/coding-agents/privacy-and-governance.mdx
index e6d42a2d..c7e8b2da 100644
--- a/docs/latest/openlit/coding-agents/privacy-and-governance.mdx
+++ b/docs/latest/openlit/coding-agents/privacy-and-governance.mdx
@@ -26,6 +26,10 @@ Two redaction tiers run on every export, regardless of capture mode:
The active capture mode is stamped as a resource attribute (`coding_agent.content_capture_mode`) on every span, so you can audit what a given session was recorded under after the fact.
+## Trace Governance Passport
+
+Coding-agent sessions also appear in the product **Trace Governance** view: open a session or request trace → hierarchy explorer → **Governance** tab. That report surfaces permission mode, capture mode, classification, agent loops, and related findings, with optional JSON passport export for evidence packages. See [Trace Governance](/latest/openlit/observability/telemetry/trace-governance).
+
## Attribution safeguards
Per-user attribution is capped by a cohort floor: viewer-tier accounts cannot see per-user metrics for a user with fewer than five sessions in the selected window. Admin-tier accounts see the full breakdown. This prevents singling out an individual developer from a small sample on the [Users](/latest/openlit/coding-agents/users) tab.
diff --git a/docs/latest/openlit/observability/telemetry/ai-analysis.mdx b/docs/latest/openlit/observability/telemetry/ai-analysis.mdx
index 7a252cbf..435ee730 100644
--- a/docs/latest/openlit/observability/telemetry/ai-analysis.mdx
+++ b/docs/latest/openlit/observability/telemetry/ai-analysis.mdx
@@ -20,6 +20,10 @@ Each run is broken into dimension tabs:
- **Cost**: cost per call, the most expensive span, and where spend concentrates.
- **Token efficiency**: input/output/cache/reasoning token usage, duplicate tool or retrieval inputs, and repeated context.
- **Path**: the request's execution path across services, tools, databases, and HTTP calls.
+- **Prompt injection**: signs the model or agent followed untrusted instructions.
+- **Tool misuse**: unsafe, redundant, or out-of-policy tool use along the path.
+
+When a hierarchy analysis run exists, Trace Governance merges the **prompt injection** and **tool misuse** findings into the same passport (no extra LLM call). See [Trace Governance](/latest/openlit/observability/telemetry/trace-governance).
## Run analysis from trace details
diff --git a/docs/latest/openlit/observability/telemetry/trace-governance.mdx b/docs/latest/openlit/observability/telemetry/trace-governance.mdx
new file mode 100644
index 00000000..0191ceec
--- /dev/null
+++ b/docs/latest/openlit/observability/telemetry/trace-governance.mdx
@@ -0,0 +1,121 @@
+---
+title: "Trace Governance"
+sidebarTitle: "Trace Governance"
+description: "Per-trace governance passport, security findings, policy controls, and evidence export"
+---
+
+Trace Governance turns a request hierarchy into a **read-only passport**: which rules matched, what security and harness risks appeared, how evaluations scored, and which policy controls those findings implicate.
+
+Open it from **Trace detail → Governance tab** in the hierarchy explorer. This is **operational** governance from production telemetry — not a questionnaire-based GRC product.
+
+## Prerequisites
+
+- A project with a working telemetry source (traces)
+- For rule matches and stored evaluations: the OpenLIT intelligence ClickHouse binding for the environment
+- Optional: a prior [AI Analysis](/latest/openlit/observability/telemetry/ai-analysis) run so Otter `prompt_injection` / `tool_misuse` findings can merge into the same report
+
+## Governance tab on a trace
+
+1. Open a trace from Telemetry → Traces (or from a widget / Otter pill).
+2. In the hierarchy explorer, select the **Governance** tab (shield icon).
+3. Review:
+ - **Risk summary** and session metrics (spans, tools, errors, cost when reported)
+ - **Security & policy** findings (deterministic checks + evaluation fails + Otter security dims when available)
+ - **Matched rules** with links into the Rule Engine
+ - **Policy controls** mapped to NIST AI RMF, EU AI Act, and OWASP ASI categories
+ - **Evaluations** stored for spans in the tree
+4. Click a span chip to jump selection in the hierarchy.
+5. Use **Export JSON** to download a passport envelope (schema version, `report_id`, report body).
+
+Each report includes a stable `report_id`. Stamp the same value on CI or release metadata with the OpenTelemetry attribute `openlit.governance.report_id` when you want exports correlated to a build.
+
+```python
+from openlit.semcov import SemanticConvention
+
+# After you export a passport and read passport["report_id"]:
+span.set_attribute(
+ SemanticConvention.OPENLIT_GOVERNANCE_REPORT_ID,
+ report_id,
+)
+```
+
+```typescript
+span.setAttribute('openlit.governance.report_id', reportId);
+```
+
+## What the report includes
+
+| Section | Source |
+|---|---|
+| Harness metrics | Hierarchy walk (depth, LLM/tool/retrieval/HTTP/DB counts, coding-agent modes) |
+| Rule matches | Rule Engine evaluation per unique span field map (`context`, `prompt`, `evaluation`, `alert`) |
+| Deterministic security | Span errors, generation health, agent loops, coding-agent policy signals |
+| Otter security | Latest stored AI Analysis `prompt_injection` and `tool_misuse` (no extra LLM call) |
+| Evaluations | Rows from OpenLIT evaluation storage for spans in the tree |
+| Policy controls | Modular packs under `policy-packs/` (NIST AI RMF, EU AI Act, OWASP ASI) |
+
+Large trees may truncate rule evaluation and evaluation queries; the UI shows a truncated note when that happens.
+
+## Extending policy pack coverage
+
+Policy control mappings live as one file per framework under the OpenLIT client:
+
+```text
+src/client/src/lib/platform/governance/policy-packs/
+ index.ts # registry + matcher
+ types.ts # definePolicyPack helpers
+ nist-ai-rmf.ts
+ eu-ai-act.ts
+ owasp-asi.ts
+```
+
+To deepen coverage for an existing framework, append controls to that framework’s file (`control_id`, `title`, `finding_categories`, optional `min_severity` / `rationale`).
+
+To add a new pack:
+
+1. Create `policy-packs/<name>.ts` with `definePolicyPack({ id, framework, version, controls })`.
+2. Import it in `policy-packs/index.ts` and append it to `POLICY_PACKS`.
+3. If the framework id is new, extend `GovernancePolicyFramework` in `types/governance-report.ts`.
+
+The Governance tab and passport export pick up registered packs automatically — no other wiring.
+
+## Rule Engine fields for coding agents
+
+Governance and the Rule Engine condition builder share extended fields so policies can match coding-agent and tool attributes, including:
+
+- `gen_ai.tool.name` / `gen_ai.tool.call.name`
+- `coding_agent.client`
+- `coding_agent.policy.permission_mode`
+- `coding_agent.content_capture_mode`
+- `coding_agent.user.classification`
+- `coding_agent.session.outcome`
+- `coding_agent.tool.name`
+
+Author rules in the Rule Engine, then confirm matches on the Governance tab for a live trace.
+
+## APIs
+
+| Method | Path | Purpose |
+|---|---|---|
+| `GET` | `/api/telemetry/request/span/:id/governance` | Build report JSON |
+| `GET` | `/api/telemetry/request/span/:id/governance/export` | Passport envelope for evidence download |
+
+Enterprise deployments audit report views and passport exports (metadata only — never raw prompts or secrets).
+
+## Related
+
+- [AI Analysis](/latest/openlit/observability/telemetry/ai-analysis) — Otter improvement + security dimensions
+- [Traces](/latest/openlit/observability/telemetry/traces) — hierarchy explorer hosting the Governance tab
+- [Privacy & Governance (coding agents)](/latest/openlit/coding-agents/privacy-and-governance) — capture modes and redaction
+- [Agent Governance Toolkit](/latest/sdk/integrations/agent-governance-toolkit) — Microsoft policy span integration (separate from this UI)
+
+---
+
+<CardGroup cols={2}>
+ <Card title="AI Analysis" href="/latest/openlit/observability/telemetry/ai-analysis" icon="sparkles">
+ Run Otter analysis so prompt injection and tool misuse fold into the passport
+ </Card>
+ <Card title="Rule Engine" href="/latest/sdk/features/rule-engine" icon="git-branch">
+ Author conditions on coding-agent and tool fields that Governance will surface
+ </Card>
+</CardGroup>
diff --git a/sdk/python/src/openlit/semcov/__init__.py b/sdk/python/src/openlit/semcov/__init__.py
index 09d22a7c..03459d84 100644
--- a/sdk/python/src/openlit/semcov/__init__.py
+++ b/sdk/python/src/openlit/semcov/__init__.py
@@ -701,6 +701,9 @@ class SemanticConvention:
# every chat span/event so the server can group traffic by version.
OPENLIT_AGENT_VERSION_HASH = "openlit.agent.version_hash"
+ # Correlate CI / evidence packages with a Trace Governance Passport export.
+ OPENLIT_GOVERNANCE_REPORT_ID = "openlit.governance.report_id"
+
GEN_AI_AGENT_TYPE = "gen_ai.agent.type"
GEN_AI_AGENT_TASK_ID = "gen_ai.agent.task.id"
GEN_AI_AGENT_ROLE = "gen_ai.agent.role"
diff --git a/sdk/python/tests/test_anthropic_stream_span_lifecycle.py b/sdk/python/tests/test_anthropic_stream_span_lifecycle.py
index a879c4d5..86043799 100644
--- a/sdk/python/tests/test_anthropic_stream_span_lifecycle.py
+++ b/sdk/python/tests/test_anthropic_stream_span_lifecycle.py
@@ -1,4 +1,4 @@
-# pylint: disable=protected-access
+# pylint: disable=protected-access, missing-function-docstring
"""Regression tests: the Anthropic streaming wrappers must end their span on
every exit path.
diff --git a/sdk/typescript/src/semantic-convention.ts b/sdk/typescript/src/semantic-convention.ts
index 6ef4ecd2..b4a7c267 100644
--- a/sdk/typescript/src/semantic-convention.ts
+++ b/sdk/typescript/src/semantic-convention.ts
@@ -180,6 +180,8 @@ export default class SemanticConvention {
// (system prompt + tools + primary model + sampling config). Stamped on
// every chat span/event so the server can group traffic by version.
static OPENLIT_AGENT_VERSION_HASH = 'openlit.agent.version_hash';
+ /** Correlate CI / evidence packages with a Trace Governance Passport export. */
+ static OPENLIT_GOVERNANCE_REPORT_ID = 'openlit.governance.report_id';
static GEN_AI_AGENT_SOURCE = 'gen_ai.agent.source';
static GEN_AI_AGENT_ACTION_TOOL = 'gen_ai.agent.action.tool';
static GEN_AI_AGENT_ACTION_TOOL_INPUT = 'gen_ai.agent.action.tool_input';
diff --git a/src/client/scripts/agents/materialize.js b/src/client/scripts/agents/materialize.js
index 9a8580fc..f8b095dc 100644
--- a/src/client/scripts/agents/materialize.js
+++ b/src/client/scripts/agents/materialize.js
@@ -20,6 +20,7 @@ async function tick() {
try {
const response = await fetch(`${API_URL}/api/agents/materialize`, {
method: "POST",
+ redirect: "manual",
headers: {
"Content-Type": "application/json",
// Matches the middleware cron-auth check: send the configured
@@ -31,6 +32,12 @@ async function tick() {
body: JSON.stringify({ cronId: CRON_ID }),
});
+ if (response.status >= 300 && response.status < 400) {
+ throw new Error(
+ `HTTP ${response.status} redirect to ${response.headers.get("location") || "?"}`
+ );
+ }
+
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
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.ts
index 7ba40391..f6499470 100644
--- 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.ts
@@ -9,6 +9,15 @@ jest.mock("@/lib/platform/intelligence/source", () => ({
.fn()
.mockResolvedValue("intel-db-1"),
}));
+// Keep wrappers isolated so EE sync (real ee/ access + next-auth/jose) does
+// not pull ESM-only deps into this handler unit test.
+jest.mock("@/lib/access/governance-route", () => ({
+ withGovernanceAccess: (_action: unknown, handler: unknown) => handler,
+ withGovernanceAudit: (handler: unknown) => handler,
+}));
+jest.mock("@/lib/access/route-access", () => ({
+ withRouteAccess: (_access: unknown, handler: unknown) => handler,
+}));
jest.mock("@/lib/rbac/route", () => ({
withDbConfigAccess: (handler: unknown) => handler,
}));
@@ -16,6 +25,7 @@ jest.mock("@/lib/rbac/route", () => ({
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 { resolveIntelligenceClickHouseDbConfigId } from "@/lib/platform/intelligence/source";
import {
GOVERNANCE_INVALID_SPAN_ID,
GOVERNANCE_MISSING_SPAN_ID,
@@ -213,4 +223,23 @@ describe("GET /api/metrics/request/span/[id]/governance", () => {
})
);
});
+
+ it("returns a controlled error when intelligence config resolution throws", async () => {
+ (resolveIntelligenceClickHouseDbConfigId as jest.Mock).mockRejectedValueOnce(
+ new Error("connector unavailable")
+ );
+
+ const response = await GET(makeRequest("span-1"), {
+ params: { id: "span-1" },
+ });
+ expect(response.status).toBe(500);
+ expect(buildTraceGovernanceReport).not.toHaveBeenCalled();
+ expect(fireGovernanceReportTelemetry).toHaveBeenCalledWith(
+ expect.objectContaining({
+ success: false,
+ spanId: "span-1",
+ error: expect.stringContaining("connector unavailable"),
+ })
+ );
+ });
});
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.ts
index 875f7532..8d65d0fe 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
@@ -65,6 +65,17 @@ describe("new implementation route access wraps", () => {
expect(source).not.toMatch(/"[a-z_]+:[a-z_]+"/);
});
+ it("wraps governance export route with governance hooks", () => {
+ const source = readFileSync(
+ join(API_ROOT, "metrics/request/span/[id]/governance/export/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/platform/agents/index.test.ts b/src/client/src/__tests__/lib/platform/agents/index.test.ts
index c6366352..d4097a3f 100644
--- a/src/client/src/__tests__/lib/platform/agents/index.test.ts
+++ b/src/client/src/__tests__/lib/platform/agents/index.test.ts
@@ -519,6 +519,47 @@ describe("listAgents", () => {
expect(result.data[0].coding_commit_count_24h).toBe(2);
});
+ it("surfaces live coding discovery when the summary table has no coding rows", async () => {
+ mockedDataCollector
+ .mockResolvedValueOnce({ data: [] })
+ .mockResolvedValueOnce({
+ data: [
+ {
+ vendor: "cursor",
+ client_version: "1.0.0",
+ first_seen: "2026-05-11 20:00:00",
+ last_seen: "2026-05-11 22:30:00",
+ session_count_24h: 4,
+ cost_usd_24h: 0.5,
+ active_users_24h: 2,
+ lines_added_24h: 3,
+ lines_removed_24h: 1,
+ lines_accepted_24h: 2,
+ lines_rejected_24h: 0,
+ edit_accept_24h: 1,
+ edit_reject_24h: 0,
+ commit_count_24h: 1,
+ pr_count_24h: 0,
+ },
+ ],
+ });
+
+ const result = await listAgents({
+ filters: { source: ["coding"] },
+ timeStart: "2026-05-11 00:00:00",
+ timeEnd: "2026-05-11 23:59:59",
+ });
+
+ expect(result.data).toHaveLength(1);
+ expect(result.data[0].source).toBe("coding");
+ expect(result.data[0].service_name).toBe("cursor");
+ expect(result.data[0].coding_session_count_24h).toBe(4);
+ expect(result.data[0].coding_cost_usd_24h).toBe(0.5);
+ expect(result.data[0].agent_key).toBe(
+ computeAgentKey("coding", "default", "cursor")
+ );
+ });
+
it("swallows coding overlay failures without failing the list", async () => {
mockedDataCollector
.mockResolvedValueOnce({
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.ts
index ea9db7e5..d8f33e6a 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
@@ -346,6 +346,18 @@ describe("ClickHouseAdapter", () => {
expect(sql).toContain("ResourceAttributes['deployment.environment'] AS g0");
});
+ it("aggregateSpans coalesces gen_ai.provider.name with legacy gen_ai.system", async () => {
+ mockDataCollector.mockResolvedValue({ data: [] });
+ await adapter.aggregateSpans({
+ ...baseQuery,
+ groupBy: ["gen_ai.provider.name"],
+ });
+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;
+ expect(sql).toContain("SpanAttributes['gen_ai.provider.name']");
+ expect(sql).toContain("SpanAttributes['gen_ai.system']");
+ expect(sql).toContain("coalesce");
+ });
+
it("aggregateSpans resolves the duration field to seconds", async () => {
mockDataCollector.mockResolvedValue({ data: [] });
await adapter.aggregateSpans({
@@ -355,7 +367,8 @@ describe("ClickHouseAdapter", () => {
});
const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;
expect(sql).toContain("Duration / 1000000000 AS g0");
- expect(sql).toContain("avg(toFloat64OrZero(Duration / 1000000000)) AS avgDur");
+ expect(sql).toContain("avg(Duration / 1000000000) AS avgDur");
+ expect(sql).not.toContain("toFloat64OrZero(Duration / 1000000000)");
});
it("aggregateSpans resolves plain allowed field names (SpanName/ServiceName/Duration)", async () => {
diff --git a/src/client/src/__tests__/lib/platform/evaluation/rule-engine-context.test.ts b/src/client/src/__tests__/lib/platform/evaluation/rule-engine-context.test.ts
index 2a2bd8b8..e256cb3d 100644
--- a/src/client/src/__tests__/lib/platform/evaluation/rule-engine-context.test.ts
+++ b/src/client/src/__tests__/lib/platform/evaluation/rule-engine-context.test.ts
@@ -47,6 +47,35 @@ describe('extractRuleEngineFieldsFromTrace', () => {
expect(fields['gen_ai.request.model']).toBe('gpt-4');
});
+ it('maps gen_ai.tool.call.name as its own rule field', () => {
+ const fields = extractRuleEngineFieldsFromTrace(
+ makeTrace({
+ SpanAttributes: {
+ 'gen_ai.system': 'openai',
+ 'gen_ai.request.model': 'gpt-4',
+ 'gen_ai.tool.call.name': 'search_docs',
+ },
+ })
+ );
+ expect(fields['gen_ai.tool.call.name']).toBe('search_docs');
+ expect(fields['gen_ai.tool.name']).toBe('search_docs');
+ });
+
+ it('prefers gen_ai.tool.name over call.name for the tool.name field', () => {
+ const fields = extractRuleEngineFieldsFromTrace(
+ makeTrace({
+ SpanAttributes: {
+ 'gen_ai.system': 'openai',
+ 'gen_ai.request.model': 'gpt-4',
+ 'gen_ai.tool.name': 'legacy_tool',
+ 'gen_ai.tool.call.name': 'search_docs',
+ },
+ })
+ );
+ expect(fields['gen_ai.tool.name']).toBe('legacy_tool');
+ expect(fields['gen_ai.tool.call.name']).toBe('search_docs');
+ });
+
it('skips fields with null values', () => {
const trace = makeTrace({ ServiceName: null });
const fields = extractRuleEngineFieldsFromTrace(trace);
diff --git a/src/client/src/__tests__/lib/platform/governance/governance.test.ts b/src/client/src/__tests__/lib/platform/governance/governance.test.ts
index 392ef581..77163d38 100644
--- a/src/client/src/__tests__/lib/platform/governance/governance.test.ts
+++ b/src/client/src/__tests__/lib/platform/governance/governance.test.ts
@@ -43,9 +43,13 @@ describe("governance hierarchy", () => {
SpanAttributes: {
"gen_ai.request.model": "gpt-4o",
"gen_ai.system": "openai",
+ "gen_ai.tool.name": "Shell",
+ "coding_agent.policy.permission_mode": "bypassPermissions",
+ "coding_agent.client": "cursor",
},
ResourceAttributes: {
"deployment.environment": "production",
+ "coding_agent.content_capture_mode": "metadata_only",
},
});
const fields = ruleFieldsFromHierarchySpan(span);
@@ -53,6 +57,12 @@ describe("governance hierarchy", () => {
expect(fields.SpanName).toBe("chat");
expect(fields["gen_ai.request.model"]).toBe("gpt-4o");
expect(fields["deployment.environment"]).toBe("production");
+ expect(fields["gen_ai.tool.name"]).toBe("Shell");
+ expect(fields["coding_agent.policy.permission_mode"]).toBe(
+ "bypassPermissions"
+ );
+ expect(fields["coding_agent.client"]).toBe("cursor");
+ expect(fields["coding_agent.content_capture_mode"]).toBe("metadata_only");
});
it("classifies tool spans", () => {
diff --git a/src/client/src/__tests__/lib/platform/governance/otter-findings.test.ts b/src/client/src/__tests__/lib/platform/governance/otter-findings.test.ts
new file mode 100644
index 00000000..7262d7f3
--- /dev/null
+++ b/src/client/src/__tests__/lib/platform/governance/otter-findings.test.ts
@@ -0,0 +1,74 @@
+jest.mock("@/lib/platform/chat/improvement", () => ({
+ getTraceAnalysisRuns: jest.fn(),
+}));
+
+import { getTraceAnalysisRuns } from "@/lib/platform/chat/improvement";
+import { loadOtterSecurityFindings } from "@/lib/platform/governance/otter-findings";
+
+const mockedRuns = getTraceAnalysisRuns as jest.MockedFunction<
+ typeof getTraceAnalysisRuns
+>;
+
+describe("loadOtterSecurityFindings", () => {
+ beforeEach(() => {
+ mockedRuns.mockReset();
+ });
+
+ it("returns empty when no runs exist", async () => {
+ mockedRuns.mockResolvedValue({ data: [] });
+ const result = await loadOtterSecurityFindings("root");
+ expect(result.findings).toEqual([]);
+ expect(result.otter_run_id).toBeUndefined();
+ });
+
+ it("maps prompt_injection and tool_misuse from the latest run", async () => {
+ mockedRuns.mockResolvedValue({
+ data: [
+ {
+ id: "run-1",
+ rootSpanId: "root",
+ selectedSpanId: "root",
+ runNumber: 1,
+ analysisJson: JSON.stringify({
+ prompt_injection: [
+ {
+ id: "pi-1",
+ severity: "critical",
+ summary: "Injection risk",
+ detail: "Untrusted instruction followed",
+ span_refs: ["s1"],
+ suggested_fix: "Harden the system prompt",
+ },
+ ],
+ tool_misuse: [
+ {
+ id: "tm-1",
+ severity: "major",
+ summary: "Risky tool",
+ detail: "Shell without allowlist",
+ span_refs: ["s2"],
+ },
+ ],
+ }),
+ summary: "",
+ modelProvider: "openai",
+ modelName: "gpt-4o",
+ promptTokens: 0,
+ completionTokens: 0,
+ cost: 0,
+ worstSeverity: "critical",
+ createdAt: new Date().toISOString(),
+ },
+ ],
+ });
+
+ const result = await loadOtterSecurityFindings("root", "db-1");
+ expect(mockedRuns).toHaveBeenCalledWith("root", "db-1", "trace_analysis");
+ expect(result.otter_run_id).toBe("run-1");
+ expect(result.findings).toHaveLength(2);
+ expect(result.findings[0].category).toBe("prompt_injection");
+ expect(result.findings[0].remediation).toBe("Harden the system prompt");
+ expect(result.findings[1].category).toBe("tool_misuse");
+ expect(result.findings[1].evidence?.source).toBe("otter");
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/governance/phase3.test.ts b/src/client/src/__tests__/lib/platform/governance/phase3.test.ts
new file mode 100644
index 00000000..77cb06c8
--- /dev/null
+++ b/src/client/src/__tests__/lib/platform/governance/phase3.test.ts
@@ -0,0 +1,169 @@
+import {
+ computeGovernanceReportId,
+ buildGovernancePassport,
+ GOVERNANCE_REPORT_ID_ATTR,
+} from "@/lib/platform/governance/passport";
+import {
+ GOVERNANCE_POLICY_PACK,
+ POLICY_PACKS,
+ listPolicyPacks,
+ policyControlsForFindings,
+} from "@/lib/platform/governance/policy-packs";
+import type { GovernanceFinding } from "@/types/governance-report";
+
+describe("governance passport", () => {
+ it("computes a stable report id", () => {
+ const base = {
+ trace_id: "t1",
+ root_span_id: "s1",
+ risk_level: "major" as const,
+ finding_count: 2,
+ rule_match_count: 1,
+ summary: "two findings",
+ };
+ expect(computeGovernanceReportId(base)).toBe(
+ computeGovernanceReportId(base)
+ );
+ expect(computeGovernanceReportId(base)).toHaveLength(24);
+ });
+
+ it("builds a passport envelope", () => {
+ const passport = buildGovernancePassport({
+ trace_id: "t1",
+ root_span_id: "s1",
+ risk_level: "critical",
+ summary: "critical",
+ 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_tokens: 0,
+ total_duration_ms: 0,
+ models_used: [],
+ tools_used: [],
+ },
+ rules: [],
+ security: [],
+ evaluations: [],
+ finding_count: 0,
+ rule_match_count: 0,
+ });
+ expect(passport.attribute_key).toBe(GOVERNANCE_REPORT_ID_ATTR);
+ expect(passport.report_id).toBeTruthy();
+ expect(passport.report.report_id).toBe(passport.report_id);
+ expect(passport.schema_version).toBe("1.0.0");
+ });
+});
+
+describe("governance policy packs", () => {
+ it("registers modular packs for NIST, EU AI Act, and OWASP ASI", () => {
+ const listed = listPolicyPacks();
+ expect(listed.map((p) => p.id).sort()).toEqual([
+ "eu-ai-act",
+ "nist-ai-rmf",
+ "owasp-asi",
+ ]);
+ expect(POLICY_PACKS.length).toBe(3);
+ expect(GOVERNANCE_POLICY_PACK.length).toBeGreaterThan(20);
+ });
+
+ it("maps prompt injection to OWASP and EU controls", () => {
+ const findings: GovernanceFinding[] = [
+ {
+ id: "1",
+ category: "prompt_injection",
+ severity: "critical",
+ summary: "injection",
+ detail: "detail",
+ span_refs: ["s1"],
+ },
+ ];
+ const controls = policyControlsForFindings(findings);
+ expect(controls.some((c) => c.framework === "owasp_asi")).toBe(true);
+ expect(controls.some((c) => c.framework === "eu_ai_act")).toBe(true);
+ expect(controls.some((c) => c.control_id === "ASI01")).toBe(true);
+ expect(controls.some((c) => c.control_id === "Art.15")).toBe(true);
+ expect(controls.some((c) => c.control_id === "MEASURE-2.6")).toBe(true);
+ });
+
+ it("maps coding-agent / policy findings across frameworks", () => {
+ const findings: GovernanceFinding[] = [
+ {
+ id: "1",
+ category: "policy",
+ severity: "major",
+ summary: "Full content capture",
+ detail: "detail",
+ span_refs: ["s1"],
+ },
+ {
+ id: "2",
+ category: "coding_agent",
+ severity: "minor",
+ summary: "shell",
+ detail: "detail",
+ span_refs: ["s2"],
+ },
+ ];
+ const controls = policyControlsForFindings(findings);
+ expect(controls.some((c) => c.control_id === "Art.12")).toBe(true);
+ expect(controls.some((c) => c.control_id === "ASI05")).toBe(true);
+ expect(controls.some((c) => c.control_id === "GOVERN-1.2")).toBe(true);
+ expect(controls.some((c) => c.control_id === "MEASURE-2.7")).toBe(true);
+ expect(controls.every((c) => c.pack_id)).toBe(true);
+ });
+
+ it("respects min_severity on pack entries", () => {
+ const infoOnly: GovernanceFinding[] = [
+ {
+ id: "1",
+ category: "policy",
+ severity: "info",
+ summary: "note",
+ detail: "detail",
+ span_refs: ["s1"],
+ },
+ ];
+ const major: GovernanceFinding[] = [
+ {
+ id: "1",
+ category: "policy",
+ severity: "major",
+ summary: "note",
+ detail: "detail",
+ span_refs: ["s1"],
+ },
+ ];
+ const infoControls = policyControlsForFindings(infoOnly);
+ const majorControls = policyControlsForFindings(major);
+ expect(infoControls.some((c) => c.control_id === "MANAGE-1.1")).toBe(
+ false
+ );
+ expect(majorControls.some((c) => c.control_id === "MANAGE-1.1")).toBe(
+ true
+ );
+ });
+
+ it("dedupes identical framework+control_id pairs", () => {
+ const findings: GovernanceFinding[] = [
+ {
+ id: "1",
+ category: "prompt_injection",
+ severity: "critical",
+ summary: "injection",
+ detail: "detail",
+ span_refs: ["s1"],
+ },
+ ];
+ const controls = policyControlsForFindings(findings);
+ const keys = controls.map((c) => `${c.framework}:${c.control_id}`);
+ expect(keys.length).toBe(new Set(keys).size);
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/manage-dashboard/widget.test.ts b/src/client/src/__tests__/lib/platform/manage-dashboard/widget.test.ts
index 7c05dce7..d04f4869 100644
--- a/src/client/src/__tests__/lib/platform/manage-dashboard/widget.test.ts
+++ b/src/client/src/__tests__/lib/platform/manage-dashboard/widget.test.ts
@@ -287,6 +287,55 @@ describe("runWidgetQuery", () => {
);
});
+ it("expands {{#filter.*}} sections without a template engine", async () => {
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({
+ data: [{ id: "w1", config: JSON.stringify({ query: "SELECT 1" }) }],
+ err: null,
+ })
+ .mockResolvedValueOnce({ data: [{ n: 1 }], err: null });
+
+ const result = await runWidgetQuery("w1", {
+ userQuery:
+ "SELECT 1 WHERE 1=1 {{#filter.vendor}}AND vendor = '{{filter.vendor}}'{{/filter.vendor}} {{#filter.user}}AND user = '{{filter.user}}'{{/filter.user}}",
+ filter: { vendor: "cursor" } as any,
+ });
+
+ expect(result).toEqual({ data: [{ n: 1 }] });
+ expect(dataCollector).toHaveBeenLastCalledWith(
+ {
+ query: "SELECT 1 WHERE 1=1 AND vendor = 'cursor' ",
+ enable_readonly: true,
+ },
+ "query",
+ undefined
+ );
+ });
+
+ it("drops {{#filter.*}} sections when the filter value is empty", async () => {
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({
+ data: [{ id: "w1", config: JSON.stringify({ query: "SELECT 1" }) }],
+ err: null,
+ })
+ .mockResolvedValueOnce({ data: [], err: null });
+
+ await runWidgetQuery("w1", {
+ userQuery:
+ "SELECT 1 WHERE 1=1 {{#filter.vendor}}AND vendor = '{{filter.vendor}}'{{/filter.vendor}}",
+ filter: {} as any,
+ });
+
+ expect(dataCollector).toHaveBeenLastCalledWith(
+ {
+ query: "SELECT 1 WHERE 1=1 ",
+ enable_readonly: true,
+ },
+ "query",
+ undefined
+ );
+ });
+
it("ignores non-filter mustache-like tags so they cannot run as code", async () => {
(dataCollector as jest.Mock)
.mockResolvedValueOnce({
diff --git a/src/client/src/app/api/metrics/request/span/[id]/governance/export/route.ts b/src/client/src/app/api/metrics/request/span/[id]/governance/export/route.ts
new file mode 100644
index 00000000..0d33d1b1
--- /dev/null
+++ b/src/client/src/app/api/metrics/request/span/[id]/governance/export/route.ts
@@ -0,0 +1,120 @@
+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 { buildGovernancePassport } from "@/lib/platform/governance/passport";
+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);
+
+ try {
+ 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!;
+ const passport = buildGovernancePassport(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(
+ { passport },
+ {
+ headers: {
+ "Content-Disposition": `attachment; filename="governance-passport-${passport.report_id}.json"`,
+ },
+ }
+ );
+ } catch (error) {
+ fireGovernanceReportTelemetry({
+ success: false,
+ startTimestamp,
+ spanId,
+ traceId,
+ error: String(error),
+ });
+ return errorResponse(error, String(error), 500);
+ }
+}
+
+export const GET = withGovernanceAudit(
+ withRouteAccess(
+ "traces.read",
+ withGovernanceAccess("export", GETHandler),
+ { requireDbConfig: true }
+ )
+);
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.ts
index 77a2acd3..6c06f926 100644
--- 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.ts
@@ -53,44 +53,55 @@ async function GETHandler(
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;
+ try {
+ // 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,
- });
+ 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,
+ });
- if (result.err) {
+ return Response.json({ report });
+ } catch (error) {
fireGovernanceReportTelemetry({
success: false,
startTimestamp,
spanId,
traceId,
- error: String(result.err),
+ error: String(error),
});
- return errorResponse(result.err, String(result.err), 400);
+ return errorResponse(error, String(error), 500);
}
-
- 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(
diff --git a/src/client/src/app/api/rule-engine/field-values/route.ts b/src/client/src/app/api/rule-engine/field-values/route.ts
index 0009285f..2e4d2c3f 100644
--- a/src/client/src/app/api/rule-engine/field-values/route.ts
+++ b/src/client/src/app/api/rule-engine/field-values/route.ts
@@ -10,6 +10,10 @@ const SUPPORTED_FIELDS = new Set([
"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",
+ "gen_ai.tool.name", "gen_ai.tool.call.name",
+ "coding_agent.client", "coding_agent.policy.permission_mode",
+ "coding_agent.content_capture_mode", "coding_agent.user.classification",
+ "coding_agent.session.outcome", "coding_agent.tool.name",
]);
export async function GET(request: NextRequest) {
diff --git a/src/client/src/app/api/telemetry/[...segments]/route.ts b/src/client/src/app/api/telemetry/[...segments]/route.ts
index 1453e3fb..7ac742ed 100644
--- a/src/client/src/app/api/telemetry/[...segments]/route.ts
+++ b/src/client/src/app/api/telemetry/[...segments]/route.ts
@@ -61,6 +61,18 @@ async function GETHandler(request: NextRequest, context: RouteContext) {
const handler = (await import("@/app/api/metrics/request/span/[id]/governance/route")).GET;
return handler(request, { params: { id: segments[2] } });
}
+ if (
+ segments.length === 5 &&
+ segments[0] === "request" &&
+ segments[1] === "span" &&
+ segments[3] === "governance" &&
+ segments[4] === "export"
+ ) {
+ const handler = (
+ await import("@/app/api/metrics/request/span/[id]/governance/export/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)/observability/trace-detail-page.tsx b/src/client/src/components/(playground)/observability/trace-detail-page.tsx
index cd96067e..2ae312cc 100644
--- a/src/client/src/components/(playground)/observability/trace-detail-page.tsx
+++ b/src/client/src/components/(playground)/observability/trace-detail-page.tsx
@@ -1012,9 +1012,9 @@ export function TraceDetailView({
)}
<GenerationHealthNote spanAttributes={spanAttributes} />
<AgentLoopNote hit={asAgentLoopHit(raw?.agentLoop)} />
- <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">
+ <div className="min-h-0 flex-1 overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950">
<ResizablePanelGroup direction="horizontal" className="h-full">
- <ResizablePanel defaultSize={48} minSize={32} maxSize={68}>
+ <ResizablePanel defaultSize={48} minSize={28} maxSize={72}>
<div className="h-full min-h-0 overflow-hidden p-2">
<SpanHierarchyExplorer
hierarchySpanId={hierarchySpanIdRef.current}
@@ -1026,7 +1026,7 @@ export function TraceDetailView({
</div>
</ResizablePanel>
<ResizableHandle withHandle />
- <ResizablePanel defaultSize={52} minSize={32}>
+ <ResizablePanel defaultSize={52} minSize={28}>
<div className="h-full min-h-0 overflow-auto p-2">
<DetailObjectTabs
tabs={detailTabs}
@@ -1037,19 +1037,6 @@ export function TraceDetailView({
</ResizablePanel>
</ResizablePanelGroup>
</div>
- <div className="grid min-h-0 flex-1 gap-3 overflow-auto lg:hidden">
- <SpanHierarchyExplorer
- hierarchySpanId={hierarchySpanIdRef.current}
- selectedSpanId={selectedSpanId}
- traceId={knownTraceId || trace?.id}
- onSelectSpan={selectSpanInCurrentTrace}
- />
- <DetailObjectTabs
- tabs={detailTabs}
- extraTabs={extraDetailTabs}
- 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.tsx
index e9706c62..da590c29 100644
--- a/src/client/src/components/(playground)/observability/trace-governance-panel.tsx
+++ b/src/client/src/components/(playground)/observability/trace-governance-panel.tsx
@@ -35,6 +35,7 @@ import {
import AskOtterPanel from "@/components/(playground)/chat/ask-otter-panel";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
+import { toast } from "sonner";
type SeverityFilter = "all" | GovernanceSeverity;
@@ -131,6 +132,10 @@ function categoryLabel(category: GovernanceFindingCategory): string {
return m.GOVERNANCE_CATEGORY_HARNESS;
case "evaluation":
return m.GOVERNANCE_CATEGORY_EVALUATION;
+ case "prompt_injection":
+ return m.GOVERNANCE_CATEGORY_PROMPT_INJECTION;
+ case "tool_misuse":
+ return m.GOVERNANCE_CATEGORY_TOOL_MISUSE;
default:
return category;
}
@@ -478,18 +483,41 @@ export default function TraceGovernancePanel({
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 exportReport = useCallback(async () => {
+ if (!hierarchySpanId) return;
+ const m = getMessage();
+ const params = new URLSearchParams();
+ if (traceId) params.set("traceId", traceId);
+ if (environment) params.set("environment", environment);
+ const qs = params.toString();
+ const url = `/api/telemetry/request/span/${encodeURIComponent(
+ hierarchySpanId
+ )}/governance/export${qs ? `?${qs}` : ""}`;
+ try {
+ const response = await fetch(url, { credentials: "include" });
+ if (!response.ok) {
+ toast.error(m.GOVERNANCE_EXPORT_FAILED, { id: "governance-export" });
+ return;
+ }
+ const payload = await response.json();
+ const passport = payload.passport || payload;
+ if (!passport?.schema_version || !passport?.report_id) {
+ toast.error(m.GOVERNANCE_EXPORT_FAILED, { id: "governance-export" });
+ return;
+ }
+ const blob = new Blob([JSON.stringify(passport, null, 2)], {
+ type: "application/json",
+ });
+ const objectUrl = URL.createObjectURL(blob);
+ const anchor = document.createElement("a");
+ anchor.href = objectUrl;
+ anchor.download = `governance-passport-${passport.report_id}.json`;
+ anchor.click();
+ URL.revokeObjectURL(objectUrl);
+ } catch {
+ toast.error(m.GOVERNANCE_EXPORT_FAILED, { id: "governance-export" });
+ }
+ }, [hierarchySpanId, traceId, environment]);
const severityFilters: Array<{ key: SeverityFilter; label: string }> = [
{ key: "all", label: m.GOVERNANCE_FILTER_ALL },
@@ -564,6 +592,16 @@ export default function TraceGovernancePanel({
{m.GOVERNANCE_TRUNCATED_NOTE}
</p>
)}
+ {report.otter_run_id && (
+ <p className="mt-1 text-[11px] text-stone-500">
+ {m.GOVERNANCE_OTTER_MERGED}
+ </p>
+ )}
+ {report.report_id && (
+ <p className="mt-1 font-mono text-[10px] text-stone-500">
+ {m.GOVERNANCE_REPORT_ID_LABEL}: {report.report_id}
+ </p>
+ )}
{report.harness.agent_loop && (
<p className="mt-1 text-[11px] text-stone-600 dark:text-stone-400">
{m.GOVERNANCE_AGENT_LOOP_BANNER.replace(
@@ -728,6 +766,39 @@ export default function TraceGovernancePanel({
</section>
)}
+ {(report.policy_controls?.length || 0) > 0 && (
+ <section>
+ <h3 className="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-stone-500">
+ {m.GOVERNANCE_SECTION_POLICY} ({report.policy_controls!.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.policy_controls!.map((control) => (
+ <div
+ key={`${control.framework}:${control.control_id}`}
+ className="flex flex-col gap-0.5 px-2.5 py-1.5 text-xs"
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="rounded bg-stone-100 px-1.5 py-0.5 font-mono text-[10px] uppercase text-stone-700 dark:bg-stone-800 dark:text-stone-300">
+ {control.framework}
+ </span>
+ <span className="font-mono text-[11px] font-medium text-stone-900 dark:text-stone-100">
+ {control.control_id}
+ </span>
+ <span className="text-stone-600 dark:text-stone-400">
+ {control.title}
+ </span>
+ </div>
+ {control.rationale ? (
+ <p className="pl-0.5 text-[10px] leading-snug text-stone-500 dark:text-stone-500">
+ {control.rationale}
+ </p>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ </section>
+ )}
+
{report.evaluations.length > 0 && (
<section>
<div className="mb-1.5 flex flex-wrap items-center justify-between gap-2">
diff --git a/src/client/src/components/(playground)/rule-engine/condition-builder.tsx b/src/client/src/components/(playground)/rule-engine/condition-builder.tsx
index 5d9bb73f..53659241 100644
--- a/src/client/src/components/(playground)/rule-engine/condition-builder.tsx
+++ b/src/client/src/components/(playground)/rule-engine/condition-builder.tsx
@@ -49,6 +49,14 @@ export const CONDITION_FIELDS = () => {
{ value: "gen_ai.usage.output_tokens", label: m.RULE_FIELD_OUTPUT_TOKENS, dataType: "number", description: m.RULE_FIELD_OUTPUT_TOKENS_DESC },
{ value: "gen_ai.usage.total_cost", label: m.RULE_FIELD_TOTAL_COST, dataType: "number", description: m.RULE_FIELD_TOTAL_COST_DESC },
{ value: "gen_ai.request.temperature", label: m.RULE_FIELD_TEMPERATURE, dataType: "number", description: m.RULE_FIELD_TEMPERATURE_DESC },
+ { value: "gen_ai.tool.name", label: m.RULE_FIELD_TOOL_NAME, dataType: "string", description: m.RULE_FIELD_TOOL_NAME_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "gen_ai.tool.call.name", label: m.RULE_FIELD_TOOL_CALL_NAME, dataType: "string", description: m.RULE_FIELD_TOOL_CALL_NAME_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "coding_agent.client", label: m.RULE_FIELD_CODING_CLIENT, dataType: "string", description: m.RULE_FIELD_CODING_CLIENT_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "coding_agent.policy.permission_mode", label: m.RULE_FIELD_CODING_PERMISSION_MODE, dataType: "string", description: m.RULE_FIELD_CODING_PERMISSION_MODE_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "coding_agent.content_capture_mode", label: m.RULE_FIELD_CODING_CAPTURE_MODE, dataType: "string", description: m.RULE_FIELD_CODING_CAPTURE_MODE_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "coding_agent.user.classification", label: m.RULE_FIELD_CODING_CLASSIFICATION, dataType: "string", description: m.RULE_FIELD_CODING_CLASSIFICATION_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "coding_agent.session.outcome", label: m.RULE_FIELD_CODING_SESSION_OUTCOME, dataType: "string", description: m.RULE_FIELD_CODING_SESSION_OUTCOME_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "coding_agent.tool.name", label: m.RULE_FIELD_CODING_TOOL_NAME, dataType: "string", description: m.RULE_FIELD_CODING_TOOL_NAME_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
];
};
diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.ts
index 7244df18..368eed19 100644
--- a/src/client/src/constants/messages/en.ts
+++ b/src/client/src/constants/messages/en.ts
@@ -1632,6 +1632,26 @@ export const RULE_FIELD_TOTAL_COST = "Total Cost ($)";
export const RULE_FIELD_TOTAL_COST_DESC = "Total cost of the request in USD.";
export const RULE_FIELD_TEMPERATURE = "Temperature";
export const RULE_FIELD_TEMPERATURE_DESC = "Sampling temperature used for the request (0\u20132).";
+export const RULE_FIELD_TOOL_NAME = "Tool name";
+export const RULE_FIELD_TOOL_NAME_DESC = "gen_ai.tool.name on tool or function-call spans.";
+export const RULE_FIELD_TOOL_CALL_NAME = "Tool call name";
+export const RULE_FIELD_TOOL_CALL_NAME_DESC = "gen_ai.tool.call.name for individual tool invocations.";
+export const RULE_FIELD_CODING_CLIENT = "Coding agent client";
+export const RULE_FIELD_CODING_CLIENT_DESC = "coding_agent.client (cursor, claude_code, codex, \u2026).";
+export const RULE_FIELD_CODING_PERMISSION_MODE = "Permission mode";
+export const RULE_FIELD_CODING_PERMISSION_MODE_DESC =
+ "coding_agent.policy.permission_mode (default, plan, acceptEdits, bypassPermissions, \u2026).";
+export const RULE_FIELD_CODING_CAPTURE_MODE = "Content capture mode";
+export const RULE_FIELD_CODING_CAPTURE_MODE_DESC =
+ "coding_agent.content_capture_mode (minimal, metadata_only, full).";
+export const RULE_FIELD_CODING_CLASSIFICATION = "User classification";
+export const RULE_FIELD_CODING_CLASSIFICATION_DESC =
+ "coding_agent.user.classification (work, personal, disputed).";
+export const RULE_FIELD_CODING_SESSION_OUTCOME = "Session outcome";
+export const RULE_FIELD_CODING_SESSION_OUTCOME_DESC =
+ "coding_agent.session.outcome (completed, abandoned, cancelled, \u2026).";
+export const RULE_FIELD_CODING_TOOL_NAME = "Coding agent tool";
+export const RULE_FIELD_CODING_TOOL_NAME_DESC = "coding_agent.tool.name on coding-agent tool spans.";
// Context
export const CONTEXT_CREATED = "Context created successfully!";
@@ -2206,6 +2226,8 @@ 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_EXPORT_FAILED =
+ "Could not export the governance passport. Try again.";
export const GOVERNANCE_TRUNCATED_NOTE =
"Large trace: rule and evaluation coverage was limited to protect performance.";
export const GOVERNANCE_AGENT_LOOP_BANNER =
@@ -2231,6 +2253,17 @@ 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_CATEGORY_PROMPT_INJECTION = "Prompt injection";
+export const GOVERNANCE_CATEGORY_TOOL_MISUSE = "Tool misuse";
+export const GOVERNANCE_REMEDIATION_PROMPT_INJECTION =
+ "Harden system prompts, constrain tools, and re-run AI Analysis after mitigations.";
+export const GOVERNANCE_REMEDIATION_TOOL_MISUSE =
+ "Tighten tool allowlists, argument validation, and permission mode before re-running.";
+export const GOVERNANCE_SECTION_POLICY = "Policy controls";
+export const GOVERNANCE_POLICY_EMPTY = "No policy controls implicated by current findings.";
+export const GOVERNANCE_OTTER_MERGED =
+ "Includes Otter AI Analysis security dimensions (prompt injection, tool misuse) when a prior run exists.";
+export const GOVERNANCE_REPORT_ID_LABEL = "Report ID";
export const GOVERNANCE_FILTER_EMPTY =
"No findings match this severity filter.";
export const GOVERNANCE_SEVERITY_LABEL = "Severity";
diff --git a/src/client/src/helpers/server/cron-auth.ts b/src/client/src/helpers/server/cron-auth.ts
index 98ab7bab..5cac69b0 100644
--- a/src/client/src/helpers/server/cron-auth.ts
+++ b/src/client/src/helpers/server/cron-auth.ts
@@ -1,12 +1,16 @@
-import crypto from "crypto";
-
+/**
+ * Cron route auth. This module is imported by Edge middleware, so it must not
+ * use Node.js `crypto` or `Buffer`.
+ */
function timingSafeEqualString(a: string, b: string): boolean {
- const aBuf = Buffer.from(a);
- const bBuf = Buffer.from(b);
- if (aBuf.length !== bBuf.length) {
+ if (a.length !== b.length) {
return false;
}
- return crypto.timingSafeEqual(aBuf, bBuf);
+ let mismatch = 0;
+ for (let i = 0; i < a.length; i++) {
+ mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
+ }
+ return mismatch === 0;
}
/**
diff --git a/src/client/src/lib/access/governance-route.ts b/src/client/src/lib/access/governance-route.ts
index 6c271fd7..eb125f79 100644
--- a/src/client/src/lib/access/governance-route.ts
+++ b/src/client/src/lib/access/governance-route.ts
@@ -2,7 +2,7 @@
* CE fallback for governance route protection and audit hooks.
* Enterprise replaces this neutral module through its path aliases.
*/
-export type GovernanceAction = "read";
+export type GovernanceAction = "read" | "export";
export function withGovernanceAccess<THandler>(
_action: GovernanceAction,
diff --git a/src/client/src/lib/platform/agents/index.ts b/src/client/src/lib/platform/agents/index.ts
index 32db8b81..a76d3ac7 100644
--- a/src/client/src/lib/platform/agents/index.ts
+++ b/src/client/src/lib/platform/agents/index.ts
@@ -488,6 +488,72 @@ async function loadAgents(params: ListAgentsParams): Promise<ListAgentsResult> {
);
const overlay = new Map<string, (typeof liveRows)[number]>();
for (const r of liveRows) overlay.set(r.agent_key, r);
+
+ // Summary is filled by the materialize cron. If cron auth fails or
+ // never ran, Telemetry can still show coding spans while this tab
+ // is empty — surface live discovery instead of overlaying nothing.
+ if (rows.length === 0 && liveRows.length > 0) {
+ const liveAgents = liveRows
+ .map((live) =>
+ rowToAgent({
+ agent_key: live.agent_key,
+ service_name: live.service_name,
+ environment: live.environment,
+ cluster_id: live.cluster_id,
+ workload_key: live.workload_key || "",
+ source: "coding",
+ controller_service_id: "",
+ controller_instance_id: "",
+ primary_model: "",
+ models: [],
+ providers: [],
+ tool_names: [],
+ tool_count: 0,
+ request_count_24h: 0,
+ current_version_hash: "",
+ current_version_number: 0,
+ sdk_version: live.sdk_version || "",
+ sdk_language: live.sdk_language || "",
+ instrumentation_status:
+ live.instrumentation_status || "instrumented",
+ first_seen: live.first_seen,
+ last_seen: live.last_seen,
+ updated_at: live.last_seen,
+ last_materialized_at: live.last_seen,
+ coding_agent_vendor: live.coding_agent_vendor,
+ coding_session_count_24h: live.coding_session_count_24h,
+ coding_cost_usd_24h: live.coding_cost_usd_24h,
+ coding_active_users_24h: live.coding_active_users_24h,
+ coding_lines_added_24h: live.coding_lines_added_24h,
+ coding_lines_removed_24h: live.coding_lines_removed_24h,
+ coding_lines_accepted_24h: live.coding_lines_accepted_24h,
+ coding_lines_rejected_24h: live.coding_lines_rejected_24h,
+ coding_edit_accept_24h: live.coding_edit_accept_24h,
+ coding_edit_reject_24h: live.coding_edit_reject_24h,
+ coding_commit_count_24h: live.coding_commit_count_24h,
+ coding_pr_count_24h: live.coding_pr_count_24h,
+ })
+ )
+ .map(redactControllerProduct)
+ .filter((agent): agent is UnifiedAgent => agent !== null)
+ .sort((a, b) => {
+ const bySeen =
+ new Date(b.last_seen).getTime() - new Date(a.last_seen).getTime();
+ if (bySeen !== 0) return bySeen;
+ return b.agent_key.localeCompare(a.agent_key);
+ });
+ return {
+ data: liveAgents.slice(0, limit),
+ nextCursor:
+ liveAgents.length > limit
+ ? {
+ last_seen: liveAgents[limit - 1].last_seen,
+ agent_key: liveAgents[limit - 1].agent_key,
+ }
+ : null,
+ };
+ }
+
for (let i = 0; i < rows.length; i++) {
const liveRow = overlay.get(rows[i].agent_key);
if (!liveRow) continue;
diff --git a/src/client/src/lib/platform/connectors/datasource/clickhouse/adapter.ts b/src/client/src/lib/platform/connectors/datasource/clickhouse/adapter.ts
index f33925e7..44bd87cf 100644
--- a/src/client/src/lib/platform/connectors/datasource/clickhouse/adapter.ts
+++ b/src/client/src/lib/platform/connectors/datasource/clickhouse/adapter.ts
@@ -100,16 +100,31 @@ function timeRangeClause(range: QueryTimeRange, column = "Timestamp"): string {
)}'`;
}
+/**
+ * Map attribute lookups are String-typed; Duration and arithmetic on it are
+ * already numeric. `toFloat64OrZero` / `OrNull` only accept String arguments
+ * in ClickHouse — wrapping `Duration / 1e9` breaks group-by aggregations.
+ */
+function coerceNumericExpr(expr: string): string {
+ if (
+ expr.startsWith("SpanAttributes[") ||
+ expr.startsWith("ResourceAttributes[")
+ ) {
+ return `toFloat64OrZero(${expr})`;
+ }
+ return expr;
+}
+
const AGG_FN_MAP: Record<string, (field: string) => string> = {
count: () => "count()",
- sum: (f) => `sum(toFloat64OrZero(${f}))`,
- avg: (f) => `avg(toFloat64OrZero(${f}))`,
- min: (f) => `min(toFloat64OrZero(${f}))`,
- max: (f) => `max(toFloat64OrZero(${f}))`,
- p50: (f) => `quantile(0.5)(toFloat64OrZero(${f}))`,
- p90: (f) => `quantile(0.9)(toFloat64OrZero(${f}))`,
- p95: (f) => `quantile(0.95)(toFloat64OrZero(${f}))`,
- p99: (f) => `quantile(0.99)(toFloat64OrZero(${f}))`,
+ sum: (f) => `sum(${coerceNumericExpr(f)})`,
+ avg: (f) => `avg(${coerceNumericExpr(f)})`,
+ min: (f) => `min(${coerceNumericExpr(f)})`,
+ max: (f) => `max(${coerceNumericExpr(f)})`,
+ p50: (f) => `quantile(0.5)(${coerceNumericExpr(f)})`,
+ p90: (f) => `quantile(0.9)(${coerceNumericExpr(f)})`,
+ p95: (f) => `quantile(0.95)(${coerceNumericExpr(f)})`,
+ p99: (f) => `quantile(0.99)(${coerceNumericExpr(f)})`,
cardinality: (f) => `uniqExact(${f})`,
};
@@ -127,6 +142,11 @@ function fieldToExpr(field: string): string {
if (field === "deployment.environment") {
return "ResourceAttributes['deployment.environment']";
}
+ // OTel GenAI renamed gen_ai.system → gen_ai.provider.name (1.30+). Coalesce
+ // so group-by / filters work for both legacy and current SDK emits.
+ if (field === "gen_ai.provider.name" || field === "gen_ai.system") {
+ return `nullIf(coalesce(nullIf(SpanAttributes['gen_ai.provider.name'], ''), nullIf(SpanAttributes['gen_ai.system'], '')), '')`;
+ }
if (field === "SpanName" || field === "ServiceName" || field === "Duration") {
return field;
}
diff --git a/src/client/src/lib/platform/evaluation/rule-engine-context.ts b/src/client/src/lib/platform/evaluation/rule-engine-context.ts
index 6afa903a..a0bd8c82 100644
--- a/src/client/src/lib/platform/evaluation/rule-engine-context.ts
+++ b/src/client/src/lib/platform/evaluation/rule-engine-context.ts
@@ -36,6 +36,50 @@ const TRACE_TO_RULE_FIELDS: Array<{
field: "gen_ai.request.model",
getValue: (t) => (t as any).SpanAttributes?.["gen_ai.request.model"],
},
+ {
+ field: "gen_ai.tool.name",
+ getValue: (t) =>
+ (t as any).SpanAttributes?.["gen_ai.tool.name"] ??
+ (t as any).SpanAttributes?.["gen_ai.tool.call.name"],
+ },
+ {
+ field: "gen_ai.tool.call.name",
+ getValue: (t) => (t as any).SpanAttributes?.["gen_ai.tool.call.name"],
+ },
+ {
+ field: "coding_agent.client",
+ getValue: (t) =>
+ (t as any).SpanAttributes?.["coding_agent.client"] ??
+ (t as any).ResourceAttributes?.["coding_agent.client"],
+ },
+ {
+ field: "coding_agent.policy.permission_mode",
+ getValue: (t) =>
+ (t as any).SpanAttributes?.["coding_agent.policy.permission_mode"] ??
+ (t as any).ResourceAttributes?.["coding_agent.policy.permission_mode"],
+ },
+ {
+ field: "coding_agent.content_capture_mode",
+ getValue: (t) =>
+ (t as any).SpanAttributes?.["coding_agent.content_capture_mode"] ??
+ (t as any).ResourceAttributes?.["coding_agent.content_capture_mode"],
+ },
+ {
+ field: "coding_agent.user.classification",
+ getValue: (t) =>
+ (t as any).SpanAttributes?.["coding_agent.user.classification"] ??
+ (t as any).ResourceAttributes?.["coding_agent.user.classification"],
+ },
+ {
+ field: "coding_agent.session.outcome",
+ getValue: (t) =>
+ (t as any).SpanAttributes?.["coding_agent.session.outcome"] ??
+ (t as any).ResourceAttributes?.["coding_agent.session.outcome"],
+ },
+ {
+ field: "coding_agent.tool.name",
+ getValue: (t) => (t as any).SpanAttributes?.["coding_agent.tool.name"],
+ },
];
/**
diff --git a/src/client/src/lib/platform/governance/hierarchy.ts b/src/client/src/lib/platform/governance/hierarchy.ts
index eed4f235..872cedb4 100644
--- a/src/client/src/lib/platform/governance/hierarchy.ts
+++ b/src/client/src/lib/platform/governance/hierarchy.ts
@@ -13,6 +13,14 @@ const RULE_FIELD_NAMES = [
"gen_ai.usage.output_tokens",
"gen_ai.usage.total_cost",
"gen_ai.request.temperature",
+ "gen_ai.tool.name",
+ "gen_ai.tool.call.name",
+ "coding_agent.client",
+ "coding_agent.policy.permission_mode",
+ "coding_agent.content_capture_mode",
+ "coding_agent.user.classification",
+ "coding_agent.session.outcome",
+ "coding_agent.tool.name",
] as const;
function ruleFieldValue(row: TraceRow, field: string): string {
@@ -27,7 +35,37 @@ function ruleFieldValue(row: TraceRow, field: string): string {
"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"],
+ "gen_ai.tool.name": ["SpanAttributes", "gen_ai.tool.name"],
+ "gen_ai.tool.call.name": ["SpanAttributes", "gen_ai.tool.call.name"],
+ "coding_agent.client": ["SpanAttributes", "coding_agent.client"],
+ "coding_agent.policy.permission_mode": [
+ "SpanAttributes",
+ "coding_agent.policy.permission_mode",
+ ],
+ "coding_agent.content_capture_mode": [
+ "SpanAttributes",
+ "coding_agent.content_capture_mode",
+ ],
+ "coding_agent.user.classification": [
+ "SpanAttributes",
+ "coding_agent.user.classification",
+ ],
+ "coding_agent.session.outcome": [
+ "SpanAttributes",
+ "coding_agent.session.outcome",
+ ],
+ "coding_agent.tool.name": ["SpanAttributes", "coding_agent.tool.name"],
};
+ // Prefer SpanAttributes, then ResourceAttributes for coding-agent / capture mode.
+ if (
+ field.startsWith("coding_agent.") ||
+ field === "gen_ai.tool.name" ||
+ field === "gen_ai.tool.call.name"
+ ) {
+ return String(
+ row.SpanAttributes[field] ?? row.ResourceAttributes[field] ?? ""
+ );
+ }
if (field === "deployment.environment") {
return String(
row.ResourceAttributes["deployment.environment"] ??
diff --git a/src/client/src/lib/platform/governance/otter-findings.ts b/src/client/src/lib/platform/governance/otter-findings.ts
new file mode 100644
index 00000000..af57ca7e
--- /dev/null
+++ b/src/client/src/lib/platform/governance/otter-findings.ts
@@ -0,0 +1,111 @@
+import { getTraceAnalysisRuns } from "@/lib/platform/chat/improvement";
+import {
+ ensureTraceAnalysisDimensions,
+ type TraceAnalysisFinding,
+ type TraceAnalysisSeverity,
+} from "@/types/trace-analysis";
+import type {
+ GovernanceFinding,
+ GovernanceSeverity,
+} from "@/types/governance-report";
+import getMessage from "@/constants/messages";
+
+const OTTER_SECURITY_DIMENSIONS = [
+ "prompt_injection",
+ "tool_misuse",
+] as const;
+
+type OtterSecurityDimension = (typeof OTTER_SECURITY_DIMENSIONS)[number];
+
+function asGovernanceSeverity(
+ severity: TraceAnalysisSeverity | string | undefined
+): GovernanceSeverity {
+ switch (severity) {
+ case "critical":
+ case "major":
+ case "minor":
+ case "info":
+ return severity;
+ default:
+ return "minor";
+ }
+}
+
+function mapOtterFinding(
+ dimension: OtterSecurityDimension,
+ finding: TraceAnalysisFinding,
+ runId: string
+): GovernanceFinding {
+ const remediation =
+ finding.suggested_fix ||
+ (dimension === "prompt_injection"
+ ? getMessage().GOVERNANCE_REMEDIATION_PROMPT_INJECTION
+ : getMessage().GOVERNANCE_REMEDIATION_TOOL_MISUSE);
+
+ return {
+ id: finding.id || `${dimension}-${runId}`,
+ category: dimension,
+ severity: asGovernanceSeverity(finding.severity),
+ summary: finding.summary || dimension,
+ detail: finding.detail || "",
+ remediation,
+ span_refs: Array.isArray(finding.span_refs)
+ ? finding.span_refs.filter(Boolean)
+ : [],
+ evidence: {
+ source: "otter",
+ dimension,
+ run_id: runId,
+ ...(typeof finding.estimated_savings?.tokens === "number"
+ ? { estimated_savings_tokens: finding.estimated_savings.tokens }
+ : {}),
+ ...(typeof finding.estimated_savings?.usd === "number"
+ ? { estimated_savings_usd: finding.estimated_savings.usd }
+ : {}),
+ },
+ };
+}
+
+/**
+ * Fold existing Otter AI Analysis security dimensions into governance findings.
+ * Does not re-run the LLM — only reads the latest stored trace_analysis run.
+ */
+export async function loadOtterSecurityFindings(
+ rootSpanId: string,
+ databaseConfigId?: string
+): Promise<{ findings: GovernanceFinding[]; otter_run_id?: string }> {
+ const { data: runs, err } = await getTraceAnalysisRuns(
+ rootSpanId,
+ databaseConfigId,
+ "trace_analysis"
+ );
+ if (err || !runs?.length) {
+ return { findings: [] };
+ }
+
+ const latest = runs[runs.length - 1];
+ let parsed: unknown;
+ try {
+ parsed =
+ typeof latest.analysisJson === "string"
+ ? JSON.parse(latest.analysisJson)
+ : latest.analysisJson;
+ } catch {
+ return { findings: [] };
+ }
+
+ const dimensions = ensureTraceAnalysisDimensions(
+ parsed as Parameters<typeof ensureTraceAnalysisDimensions>[0]
+ );
+ const findings: GovernanceFinding[] = [];
+ for (const dimension of OTTER_SECURITY_DIMENSIONS) {
+ for (const finding of dimensions[dimension] || []) {
+ findings.push(mapOtterFinding(dimension, finding, latest.id));
+ }
+ }
+
+ return {
+ findings,
+ otter_run_id: findings.length ? latest.id : undefined,
+ };
+}
diff --git a/src/client/src/lib/platform/governance/passport.ts b/src/client/src/lib/platform/governance/passport.ts
new file mode 100644
index 00000000..67816f0e
--- /dev/null
+++ b/src/client/src/lib/platform/governance/passport.ts
@@ -0,0 +1,60 @@
+import { createHash } from "crypto";
+import type { TraceGovernanceReport } from "@/types/governance-report";
+
+export const GOVERNANCE_PASSPORT_SCHEMA_VERSION = "1.0.0";
+export const GOVERNANCE_REPORT_ID_ATTR = "openlit.governance.report_id";
+
+export type GovernancePassportEnvelope = {
+ schema_version: string;
+ exported_at: string;
+ report_id: string;
+ attribute_key: typeof GOVERNANCE_REPORT_ID_ATTR;
+ report: TraceGovernanceReport;
+};
+
+/** Deterministic passport id for a built report (stable across re-exports). */
+export function computeGovernanceReportId(
+ report: Pick<
+ TraceGovernanceReport,
+ | "trace_id"
+ | "root_span_id"
+ | "risk_level"
+ | "finding_count"
+ | "rule_match_count"
+ | "summary"
+ >
+): string {
+ const material = [
+ report.trace_id,
+ report.root_span_id,
+ report.risk_level,
+ String(report.finding_count),
+ String(report.rule_match_count),
+ report.summary,
+ ].join("|");
+ return createHash("sha256").update(material).digest("hex").slice(0, 24);
+}
+
+export function stampGovernanceReportId(
+ report: TraceGovernanceReport
+): TraceGovernanceReport {
+ if (report.report_id) return report;
+ return {
+ ...report,
+ report_id: computeGovernanceReportId(report),
+ };
+}
+
+export function buildGovernancePassport(
+ report: TraceGovernanceReport,
+ opts?: { exportedAt?: string }
+): GovernancePassportEnvelope {
+ const stamped = stampGovernanceReportId(report);
+ return {
+ schema_version: GOVERNANCE_PASSPORT_SCHEMA_VERSION,
+ exported_at: opts?.exportedAt || new Date().toISOString(),
+ report_id: stamped.report_id!,
+ attribute_key: GOVERNANCE_REPORT_ID_ATTR,
+ report: stamped,
+ };
+}
diff --git a/src/client/src/lib/platform/governance/policy-packs/eu-ai-act.ts b/src/client/src/lib/platform/governance/policy-packs/eu-ai-act.ts
new file mode 100644
index 00000000..6a7c490e
--- /dev/null
+++ b/src/client/src/lib/platform/governance/policy-packs/eu-ai-act.ts
@@ -0,0 +1,89 @@
+import { definePolicyPack } from "./types";
+
+/**
+ * EU AI Act — selected articles commonly implicated by runtime telemetry
+ * evidence (logging, robustness, oversight, deployer monitoring).
+ *
+ * This is evidence scaffolding for auditors, not a legal determination.
+ * Extend controls here when you need denser Article coverage.
+ */
+export const euAiActPack = definePolicyPack({
+ id: "eu-ai-act",
+ framework: "eu_ai_act",
+ version: "1.1.0",
+ controls: [
+ {
+ control_id: "Art.9",
+ title: "Risk management system",
+ finding_categories: [
+ "prompt_injection",
+ "tool_misuse",
+ "agent_loop",
+ "span_error",
+ "policy",
+ ],
+ },
+ {
+ control_id: "Art.10",
+ title: "Data and data governance",
+ finding_categories: ["policy", "coding_agent", "evaluation"],
+ rationale:
+ "Content-capture and classification findings speak to how training/ops data is handled at runtime.",
+ },
+ {
+ control_id: "Art.12",
+ title: "Record-keeping / logging",
+ finding_categories: ["coding_agent", "harness", "policy"],
+ },
+ {
+ control_id: "Art.13",
+ title: "Transparency and provision of information",
+ finding_categories: ["coding_agent", "policy", "generation_health"],
+ },
+ {
+ control_id: "Art.14",
+ title: "Human oversight",
+ finding_categories: [
+ "tool_misuse",
+ "agent_loop",
+ "policy",
+ "coding_agent",
+ ],
+ rationale:
+ "Autonomous tool loops and elevated permission modes implicate oversight effectiveness.",
+ },
+ {
+ control_id: "Art.15",
+ title: "Accuracy, robustness and cybersecurity",
+ finding_categories: [
+ "prompt_injection",
+ "tool_misuse",
+ "generation_health",
+ "evaluation",
+ "span_error",
+ ],
+ },
+ {
+ control_id: "Art.26",
+ title: "Obligations of deployers of high-risk AI systems",
+ finding_categories: [
+ "coding_agent",
+ "harness",
+ "policy",
+ "evaluation",
+ "generation_health",
+ ],
+ min_severity: "minor",
+ },
+ {
+ control_id: "Art.72",
+ title: "Post-market monitoring by providers",
+ finding_categories: [
+ "generation_health",
+ "evaluation",
+ "agent_loop",
+ "span_error",
+ ],
+ },
+ ],
+});
diff --git a/src/client/src/lib/platform/governance/policy-packs/index.ts b/src/client/src/lib/platform/governance/policy-packs/index.ts
new file mode 100644
index 00000000..9231f63b
--- /dev/null
+++ b/src/client/src/lib/platform/governance/policy-packs/index.ts
@@ -0,0 +1,126 @@
+import type {
+ GovernanceFinding,
+ GovernancePolicyControl,
+ GovernanceSeverity,
+} from "@/types/governance-report";
+import { euAiActPack } from "./eu-ai-act";
+import { nistAiRmfPack } from "./nist-ai-rmf";
+import { owaspAsiPack } from "./owasp-asi";
+import {
+ flattenPolicyPack,
+ SEVERITY_RANK,
+ type PolicyPack,
+ type PolicyPackEntry,
+} from "./types";
+
+export type { PolicyPack, PolicyPackControl, PolicyPackEntry } from "./types";
+export { definePolicyPack, flattenPolicyPack, SEVERITY_RANK } from "./types";
+export { nistAiRmfPack } from "./nist-ai-rmf";
+export { euAiActPack } from "./eu-ai-act";
+export { owaspAsiPack } from "./owasp-asi";
+
+/**
+ * Registry of active governance policy packs.
+ *
+ * ## Adding coverage
+ *
+ * 1. Create `policy-packs/<your-pack>.ts` that calls `definePolicyPack({...})`
+ * (or append controls to an existing framework file).
+ * 2. Import the pack here and push it onto `POLICY_PACKS`.
+ * 3. If you introduce a new framework id, extend `GovernancePolicyFramework`
+ * in `@/types/governance-report` and any UI that labels frameworks.
+ *
+ * Packs are evaluated in registry order; duplicate `framework`+`control_id`
+ * pairs from later packs are skipped so overlays can refine without double
+ * counting.
+ */
+export const POLICY_PACKS: PolicyPack[] = [
+ nistAiRmfPack,
+ euAiActPack,
+ owaspAsiPack,
+];
+
+/** Flat control list used by the matcher (derived from `POLICY_PACKS`). */
+export const GOVERNANCE_POLICY_PACK: PolicyPackEntry[] = POLICY_PACKS.flatMap(
+ flattenPolicyPack
+);
+
+function maxSeverityForCategories(
+ findings: GovernanceFinding[],
+ categories: Set<string>
+): GovernanceSeverity | null {
+ let max: GovernanceSeverity | null = null;
+ for (const finding of findings) {
+ if (!categories.has(finding.category)) continue;
+ if (
+ max == null ||
+ SEVERITY_RANK[finding.severity] > SEVERITY_RANK[max]
+ ) {
+ max = finding.severity;
+ }
+ }
+ return max;
+}
+
+/**
+ * Map report findings to implicated policy controls across all registered
+ * packs. Returns only controls that have at least one matching category
+ * (and that satisfy optional `min_severity`).
+ */
+export function policyControlsForFindings(
+ findings: GovernanceFinding[]
+): GovernancePolicyControl[] {
+ const present = new Set(findings.map((f) => f.category));
+ const matched: GovernancePolicyControl[] = [];
+ const seen = new Set<string>();
+
+ for (const entry of GOVERNANCE_POLICY_PACK) {
+ const hitCategories = entry.finding_categories.filter((c) =>
+ present.has(c)
+ );
+ if (!hitCategories.length) continue;
+
+ if (entry.min_severity) {
+ const peak = maxSeverityForCategories(
+ findings,
+ new Set(hitCategories)
+ );
+ if (
+ peak == null ||
+ SEVERITY_RANK[peak] < SEVERITY_RANK[entry.min_severity]
+ ) {
+ continue;
+ }
+ }
+
+ const dedupeKey = `${entry.framework}:${entry.control_id}`;
+ if (seen.has(dedupeKey)) continue;
+ seen.add(dedupeKey);
+
+ matched.push({
+ framework: entry.framework,
+ control_id: entry.control_id,
+ title: entry.title,
+ finding_categories: hitCategories,
+ ...(entry.rationale ? { rationale: entry.rationale } : {}),
+ pack_id: entry.pack_id,
+ });
+ }
+
+ return matched;
+}
+
+/** List registered packs (for docs / diagnostics). */
+export function listPolicyPacks(): Array<{
+ id: string;
+ framework: PolicyPack["framework"];
+ version: string;
+ control_count: number;
+}> {
+ return POLICY_PACKS.map((pack) => ({
+ id: pack.id,
+ framework: pack.framework,
+ version: pack.version,
+ control_count: pack.controls.length,
+ }));
+}
diff --git a/src/client/src/lib/platform/governance/policy-packs/nist-ai-rmf.ts b/src/client/src/lib/platform/governance/policy-packs/nist-ai-rmf.ts
new file mode 100644
index 00000000..82c0f021
--- /dev/null
+++ b/src/client/src/lib/platform/governance/policy-packs/nist-ai-rmf.ts
@@ -0,0 +1,138 @@
+import { definePolicyPack } from "./types";
+
+/**
+ * NIST AI Risk Management Framework (AI RMF 1.0) — selected Govern / Map /
+ * Measure / Manage functions mapped to OpenLIT finding categories.
+ *
+ * Extend this file to deepen NIST coverage; keep `control_id` stable so
+ * exported passports remain comparable over time.
+ */
+export const nistAiRmfPack = definePolicyPack({
+ id: "nist-ai-rmf",
+ framework: "nist_ai_rmf",
+ version: "1.1.0",
+ controls: [
+ {
+ control_id: "GOVERN-1.1",
+ title: "Legal and regulatory requirements are understood",
+ finding_categories: ["policy", "coding_agent"],
+ rationale:
+ "Capture-mode and permission findings show whether deployment policies are enforced in telemetry.",
+ },
+ {
+ control_id: "GOVERN-1.2",
+ title: "Accountability and governance roles",
+ finding_categories: ["policy", "coding_agent"],
+ },
+ {
+ control_id: "GOVERN-1.3",
+ title: "Processes for AI risk management are in place",
+ finding_categories: ["policy", "evaluation", "harness"],
+ },
+ {
+ control_id: "GOVERN-1.5",
+ title: "Ongoing monitoring and review of AI risks",
+ finding_categories: [
+ "generation_health",
+ "evaluation",
+ "agent_loop",
+ "span_error",
+ ],
+ },
+ {
+ control_id: "MAP-1.1",
+ title: "Context of AI system use is understood",
+ finding_categories: ["coding_agent", "policy", "harness"],
+ },
+ {
+ control_id: "MAP-2.1",
+ title: "Risks related to third-party components are understood",
+ finding_categories: ["tool_misuse", "harness", "coding_agent"],
+ },
+ {
+ control_id: "MAP-2.3",
+ title: "AI system impacts and harms are assessed",
+ finding_categories: [
+ "prompt_injection",
+ "tool_misuse",
+ "generation_health",
+ "policy",
+ ],
+ min_severity: "minor",
+ },
+ {
+ control_id: "MAP-5.1",
+ title: "AI system operational environment is documented",
+ finding_categories: ["coding_agent", "harness", "policy"],
+ },
+ {
+ control_id: "MEASURE-1.1",
+ title: "Approaches for measuring AI risks are identified",
+ finding_categories: ["evaluation", "generation_health", "harness"],
+ },
+ {
+ control_id: "MEASURE-2.3",
+ title: "AI system performance is evaluated",
+ finding_categories: ["evaluation", "generation_health"],
+ },
+ {
+ control_id: "MEASURE-2.6",
+ title: "AI system security and resilience are evaluated",
+ finding_categories: [
+ "prompt_injection",
+ "tool_misuse",
+ "span_error",
+ "agent_loop",
+ ],
+ },
+ {
+ control_id: "MEASURE-2.7",
+ title: "AI system privacy risks are evaluated",
+ finding_categories: ["policy", "coding_agent"],
+ rationale:
+ "Full content capture and secret-adjacent policy findings indicate privacy measurement gaps.",
+ },
+ {
+ control_id: "MEASURE-2.11",
+ title: "Risk tracking measures are applied",
+ finding_categories: ["evaluation", "generation_health", "agent_loop"],
+ },
+ {
+ control_id: "MANAGE-1.1",
+ title: "AI risks are prioritized and responded to",
+ finding_categories: [
+ "prompt_injection",
+ "tool_misuse",
+ "span_error",
+ "agent_loop",
+ "policy",
+ ],
+ min_severity: "major",
+ },
+ {
+ control_id: "MANAGE-2.2",
+ title: "Mechanisms for AI incident response are established",
+ finding_categories: ["span_error", "agent_loop", "prompt_injection"],
+ },
+ {
+ control_id: "MANAGE-2.4",
+ title: "Risk response for AI incidents",
+ finding_categories: [
+ "span_error",
+ "agent_loop",
+ "prompt_injection",
+ "tool_misuse",
+ ],
+ },
+ {
+ control_id: "MANAGE-4.1",
+ title: "Post-deployment monitoring plans are implemented",
+ finding_categories: [
+ "generation_health",
+ "evaluation",
+ "harness",
+ "coding_agent",
+ ],
+ },
+ ],
+});
diff --git a/src/client/src/lib/platform/governance/policy-packs/owasp-asi.ts b/src/client/src/lib/platform/governance/policy-packs/owasp-asi.ts
new file mode 100644
index 00000000..702a4701
--- /dev/null
+++ b/src/client/src/lib/platform/governance/policy-packs/owasp-asi.ts
@@ -0,0 +1,89 @@
+import { definePolicyPack } from "./types";
+
+/**
+ * OWASP Top 10 for Agentic Applications (ASI) — mapped to OpenLIT
+ * security / coding-agent finding categories.
+ *
+ * Add new ASI controls (or refine categories) in this file only; the
+ * registry in `index.ts` already loads this pack.
+ */
+export const owaspAsiPack = definePolicyPack({
+ id: "owasp-asi",
+ framework: "owasp_asi",
+ version: "1.1.0",
+ controls: [
+ {
+ control_id: "ASI01",
+ title: "Agent goal hijack / prompt injection",
+ finding_categories: ["prompt_injection"],
+ },
+ {
+ control_id: "ASI02",
+ title: "Tool misuse and excessive agency",
+ finding_categories: ["tool_misuse", "agent_loop", "harness"],
+ },
+ {
+ control_id: "ASI03",
+ title: "Identity and privilege abuse",
+ finding_categories: ["policy", "coding_agent", "tool_misuse"],
+ rationale:
+ "Elevated permission modes and policy bypass signals map to privilege abuse.",
+ },
+ {
+ control_id: "ASI04",
+ title: "Supply chain and untrusted tools",
+ finding_categories: ["tool_misuse", "harness", "coding_agent"],
+ },
+ {
+ control_id: "ASI05",
+ title: "Unexpected code execution / secrets exposure",
+ finding_categories: ["coding_agent", "policy", "tool_misuse"],
+ },
+ {
+ control_id: "ASI06",
+ title: "Memory and context poisoning",
+ finding_categories: [
+ "prompt_injection",
+ "generation_health",
+ "evaluation",
+ ],
+ },
+ {
+ control_id: "ASI07",
+ title: "Insecure inter-agent communication",
+ finding_categories: ["agent_loop", "harness", "tool_misuse"],
+ },
+ {
+ control_id: "ASI08",
+ title: "Cascading failures and unbounded agency",
+ finding_categories: [
+ "agent_loop",
+ "span_error",
+ "harness",
+ "tool_misuse",
+ ],
+ min_severity: "minor",
+ },
+ {
+ control_id: "ASI09",
+ title: "Human-agent trust exploitation",
+ finding_categories: [
+ "generation_health",
+ "evaluation",
+ "prompt_injection",
+ "policy",
+ ],
+ },
+ {
+ control_id: "ASI10",
+ title: "Rogue agents and lack of oversight",
+ finding_categories: [
+ "agent_loop",
+ "tool_misuse",
+ "coding_agent",
+ "policy",
+ ],
+ min_severity: "major",
+ },
+ ],
+});
diff --git a/src/client/src/lib/platform/governance/policy-packs/types.ts b/src/client/src/lib/platform/governance/policy-packs/types.ts
new file mode 100644
index 00000000..a52a3eab
--- /dev/null
+++ b/src/client/src/lib/platform/governance/policy-packs/types.ts
@@ -0,0 +1,59 @@
+import type {
+ GovernanceFindingCategory,
+ GovernancePolicyFramework,
+ GovernanceSeverity,
+} from "@/types/governance-report";
+
+/**
+ * One control mapping inside a policy pack.
+ *
+ * Add new rows to the pack file for your framework (e.g. `nist-ai-rmf.ts`).
+ * The aggregator in `index.ts` loads every registered pack — no other
+ * wiring is required beyond appending the pack to `POLICY_PACKS`.
+ */
+export type PolicyPackControl = {
+ control_id: string;
+ title: string;
+ /** Finding categories that implicate this control when present. */
+ finding_categories: GovernanceFindingCategory[];
+ /**
+ * Optional floor: only match when at least one implicated finding
+ * is at this severity or higher (`info` < `minor` < `major` < `critical`).
+ */
+ min_severity?: GovernanceSeverity;
+ /** Short auditor-facing note (optional; surfaced on the control when set). */
+ rationale?: string;
+};
+
+export type PolicyPack = {
+ /** Stable pack id (filesystem / docs), e.g. `nist-ai-rmf`. */
+ id: string;
+ framework: GovernancePolicyFramework;
+ version: string;
+ controls: PolicyPackControl[];
+};
+
+/** Flattened entry used by the matcher (pack metadata + one control). */
+export type PolicyPackEntry = PolicyPackControl & {
+ framework: GovernancePolicyFramework;
+ pack_id: string;
+};
+
+export const SEVERITY_RANK: Record<GovernanceSeverity, number> = {
+ info: 0,
+ minor: 1,
+ major: 2,
+ critical: 3,
+};
+
+export function definePolicyPack(pack: PolicyPack): PolicyPack {
+ return pack;
+}
+
+export function flattenPolicyPack(pack: PolicyPack): PolicyPackEntry[] {
+ return pack.controls.map((control) => ({
+ ...control,
+ framework: pack.framework,
+ pack_id: pack.id,
+ }));
+}
diff --git a/src/client/src/lib/platform/governance/trace-report.ts b/src/client/src/lib/platform/governance/trace-report.ts
index ecb214cb..a17e537d 100644
--- a/src/client/src/lib/platform/governance/trace-report.ts
+++ b/src/client/src/lib/platform/governance/trace-report.ts
@@ -23,6 +23,9 @@ import {
buildSecurityFindings,
summarizeGovernanceReport,
} from "./security-checks";
+import { loadOtterSecurityFindings } from "./otter-findings";
+import { policyControlsForFindings } from "./policy-packs";
+import { stampGovernanceReportId } from "./passport";
import { createHash } from "crypto";
export const GOVERNANCE_MAX_SPANS_RULE_EVAL = 100;
@@ -253,9 +256,14 @@ export async function buildTraceGovernanceReport(
spanIdsForEval,
opts?.databaseConfigId
);
+ const otter = await loadOtterSecurityFindings(
+ root.SpanId,
+ opts?.databaseConfigId
+ );
const security = [
...buildSecurityFindings(spans),
...evaluationFindings(evaluations),
+ ...otter.findings,
];
const harness = buildHarnessMetrics(root, spans);
const { risk_level, summary } = summarizeGovernanceReport(
@@ -263,9 +271,10 @@ export async function buildTraceGovernanceReport(
ruleMatches.length,
evaluations.length
);
+ const policy_controls = policyControlsForFindings(security);
return {
- report: {
+ report: stampGovernanceReportId({
trace_id: root.TraceId || opts?.traceId || spanId,
root_span_id: root.SpanId,
risk_level,
@@ -277,6 +286,8 @@ export async function buildTraceGovernanceReport(
finding_count: security.length,
rule_match_count: ruleMatches.length,
analysis_limited: analysisLimited || undefined,
- },
+ otter_run_id: otter.otter_run_id,
+ policy_controls: policy_controls.length ? policy_controls : undefined,
+ }),
};
}
diff --git a/src/client/src/lib/platform/manage-dashboard/widget.ts b/src/client/src/lib/platform/manage-dashboard/widget.ts
index 1c4360c1..126c1c99 100644
--- a/src/client/src/lib/platform/manage-dashboard/widget.ts
+++ b/src/client/src/lib/platform/manage-dashboard/widget.ts
@@ -56,8 +56,76 @@ function getFilterPathValue(filter: unknown, path: string): unknown {
return current;
}
+/** Truthiness for Mustache-style `{{#filter.*}}` / `{{^filter.*}}` sections. */
+function isFilterSectionTruthy(value: unknown): boolean {
+ if (value == null) return false;
+ if (typeof value === "boolean") return value;
+ if (typeof value === "number") return value !== 0 && !Number.isNaN(value);
+ if (typeof value === "string") return value.length > 0;
+ if (Array.isArray(value)) return value.length > 0;
+ if (typeof value === "object") {
+ return Object.keys(value as Record<string, unknown>).length > 0;
+ }
+ return Boolean(value);
+}
+
+/**
+ * Expand only `{{#filter.path}}…{{/filter.path}}` and
+ * `{{^filter.path}}…{{/filter.path}}` sections.
+ *
+ * Coding Agents (and other) seeded widgets rely on these to optionally inject
+ * vendor/user predicates. We deliberately do **not** hand the query to a
+ * template engine — only allow-listed `filter.<path>` section tags are
+ * recognized, so arbitrary Mustache (`{{#evil}}`, lambdas, partials) stays
+ * inert (CodeQL js/code-injection).
+ *
+ * Implemented as a left-to-right scan (no `[\s\S]*?` + backref replace) to
+ * avoid polynomial ReDoS on hostile templates (CodeQL js/polynomial-redos).
+ */
+function renderFilterSections(template: string, filter: MetricParams): string {
+ const openTag = /\{\{([#^])\s*filter\.([a-zA-Z0-9_.]+)\s*\}\}/g;
+ let out = "";
+ let cursor = 0;
+
+ while (cursor < template.length) {
+ openTag.lastIndex = cursor;
+ const open = openTag.exec(template);
+ if (!open) {
+ out += template.slice(cursor);
+ break;
+ }
+
+ const openStart = open.index;
+ const openEnd = openTag.lastIndex;
+ const kind = open[1] as "#" | "^";
+ const path = open[2];
+ out += template.slice(cursor, openStart);
+
+ const closeNeedle = `{{/filter.${path}}}`;
+ const closeIndex = template.indexOf(closeNeedle, openEnd);
+ if (closeIndex === -1) {
+ // Unclosed section: keep the open tag literal and continue.
+ out += open[0];
+ cursor = openEnd;
+ continue;
+ }
+
+ const body = template.slice(openEnd, closeIndex);
+ const truthy = isFilterSectionTruthy(getFilterPathValue(filter, path));
+ if (kind === "#") {
+ out += truthy ? body : "";
+ } else {
+ out += truthy ? "" : body;
+ }
+ cursor = closeIndex + closeNeedle.length;
+ }
+
+ return out;
+}
+
/**
- * Substitute only `{{filter.*}}` / `{{{filter.*}}}` placeholders.
+ * Substitute only `{{filter.*}}` / `{{{filter.*}}}` placeholders, after
+ * expanding `filter.*` section tags.
*
* Intentionally does **not** use Mustache (or any template engine): the
* query string is user-controlled on the widget preview path, and treating
@@ -70,7 +138,8 @@ function renderFilterPlaceholders(
template: string,
filter: MetricParams
): string {
- return template.replace(
+ const withSections = renderFilterSections(template, filter);
+ return withSections.replace(
/\{\{\{\s*filter\.([a-zA-Z0-9_.]+)\s*\}\}\}|\{\{\s*filter\.([a-zA-Z0-9_.]+)\s*\}\}/g,
(
_match,
diff --git a/src/client/src/lib/platform/rule-engine/telemetry.ts b/src/client/src/lib/platform/rule-engine/telemetry.ts
index 4e064616..884904fd 100644
--- a/src/client/src/lib/platform/rule-engine/telemetry.ts
+++ b/src/client/src/lib/platform/rule-engine/telemetry.ts
@@ -45,6 +45,26 @@ export function getRuleTraceFieldValue(
"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"],
+ "gen_ai.tool.name": ["SpanAttributes", "gen_ai.tool.name"],
+ "gen_ai.tool.call.name": ["SpanAttributes", "gen_ai.tool.call.name"],
+ "coding_agent.client": ["SpanAttributes", "coding_agent.client"],
+ "coding_agent.policy.permission_mode": [
+ "SpanAttributes",
+ "coding_agent.policy.permission_mode",
+ ],
+ "coding_agent.content_capture_mode": [
+ "SpanAttributes",
+ "coding_agent.content_capture_mode",
+ ],
+ "coding_agent.user.classification": [
+ "SpanAttributes",
+ "coding_agent.user.classification",
+ ],
+ "coding_agent.session.outcome": [
+ "SpanAttributes",
+ "coding_agent.session.outcome",
+ ],
+ "coding_agent.tool.name": ["SpanAttributes", "coding_agent.tool.name"],
};
if (field === "deployment.environment") {
return String(
@@ -54,6 +74,17 @@ export function getRuleTraceFieldValue(
""
);
}
+ if (
+ field.startsWith("coding_agent.") ||
+ field === "gen_ai.tool.name" ||
+ field === "gen_ai.tool.call.name"
+ ) {
+ return String(
+ trace.SpanAttributes?.[field] ??
+ trace.ResourceAttributes?.[field] ??
+ ""
+ );
+ }
const attribute = attributeFields[field];
if (attribute) {
const [scope, key] = attribute;
diff --git a/src/client/src/lib/platform/traces/read.ts b/src/client/src/lib/platform/traces/read.ts
index 3c9ca4f7..e48017f8 100644
--- a/src/client/src/lib/platform/traces/read.ts
+++ b/src/client/src/lib/platform/traces/read.ts
@@ -679,7 +679,8 @@ const BUCKET_INTERVAL: Record<string, string> = {
/** Friendly filter-bar groupBy keys -> the attribute/field an adapter groups on. */
const GROUP_BY_FIELD: Record<string, string> = {
model: "gen_ai.request.model",
- provider: "gen_ai.system",
+ // Prefer provider.name; ClickHouse adapter coalesces legacy gen_ai.system.
+ provider: "gen_ai.provider.name",
spanName: "SpanName",
applicationName: "service.name",
};
@@ -737,7 +738,12 @@ export async function getTraceFilterConfig(params: MetricParams) {
);
const { spans } = await fetchSpansForAggregation(adapter, query);
const models = distinctFromSpans(spans, "gen_ai.request.model");
- const providers = distinctFromSpans(spans, "gen_ai.system");
+ const providers = Array.from(
+ new Set([
+ ...distinctFromSpans(spans, "gen_ai.provider.name"),
+ ...distinctFromSpans(spans, "gen_ai.system"),
+ ])
+ ).filter(Boolean);
// Prefer adapter-native enums (Jaeger /api/services/{svc}/operations) when
// available so Span Names match the Jaeger Search UI instead of a sample.
let spanNames: string[] = [];
diff --git a/src/client/src/types/governance-report.ts b/src/client/src/types/governance-report.ts
index e0c2172f..c8f30ba2 100644
--- a/src/client/src/types/governance-report.ts
+++ b/src/client/src/types/governance-report.ts
@@ -7,7 +7,25 @@ export type GovernanceFindingCategory =
| "evaluation"
| "coding_agent"
| "harness"
- | "policy";
+ | "policy"
+ | "prompt_injection"
+ | "tool_misuse";
+
+export type GovernancePolicyFramework =
+ | "nist_ai_rmf"
+ | "eu_ai_act"
+ | "owasp_asi";
+
+export type GovernancePolicyControl = {
+ framework: GovernancePolicyFramework;
+ control_id: string;
+ title: string;
+ finding_categories: GovernanceFindingCategory[];
+ /** Optional auditor-facing note from the pack entry. */
+ rationale?: string;
+ /** Source pack id (e.g. `nist-ai-rmf`) when emitted from the registry. */
+ pack_id?: string;
+};
export type GovernanceRuleEntityType =
| "context"
@@ -82,6 +100,8 @@ export type GovernanceHarnessReport = {
export type TraceGovernanceReport = {
trace_id: string;
root_span_id: string;
+ /** Stable id for CI / evidence correlation (`openlit.governance.report_id`). */
+ report_id?: string;
risk_level: GovernanceSeverity | "none";
summary: string;
harness: GovernanceHarnessReport;
@@ -91,4 +111,8 @@ export type TraceGovernanceReport = {
finding_count: number;
rule_match_count: number;
analysis_limited?: boolean;
+ /** Latest Otter trace_analysis run id when security dims were merged. */
+ otter_run_id?: string;
+ /** Policy pack controls implicated by findings on this trace. */
+ policy_controls?: GovernancePolicyControl[];
};