Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(agents,web): WS-D1 — alert "Explain" endpoint + side drawer

Beenu Arorae7ead8f46a95
diff --git a/apps/web/src/components/alerts/AlertDetailView.tsx b/apps/web/src/components/alerts/AlertDetailView.tsx
index 878ad5deb..4ddfe8174 100644
--- a/apps/web/src/components/alerts/AlertDetailView.tsx
+++ b/apps/web/src/components/alerts/AlertDetailView.tsx
@@ -19,6 +19,7 @@ import {
import { format } from 'date-fns';
import { clsx } from 'clsx';
import { ContextualActions } from '@/components/copilot/ContextualActions';
+import { ExplainDrawer } from '@/components/alerts/ExplainDrawer';
// ─── Helpers ──────────────────────────────────────────────────────────────────
@@ -823,6 +824,10 @@ function AnalystOverridePanel({
export function AlertDetailView({ alertId }: { alertId: string }) {
const [activeTab, setActiveTab] = useState<'overview' | 'timeline' | 'raw'>('overview');
const [status, setStatus] = useState<Alert['status']>('new');
+ // Side drawer for the "Explain this alert" structured walkthrough
+ // (`POST /api/v1/explain`). Kept local to the detail view because it
+ // only makes sense while a single alert is on screen.
+ const [explainOpen, setExplainOpen] = useState(false);
const { data: alert, isLoading, mutate } = useSWR(
['alert', alertId],
@@ -892,6 +897,34 @@ export function AlertDetailView({ alertId }: { alertId: string }) {
<option key={key} value={key}>{cfg.label}</option>
))}
</select>
+ {/*
+ Primary L1/L2 affordance: open the structured "What happened
+ and what should I do?" drawer. Placed in the header so it's
+ the first thing a triaging analyst sees, ahead of the heavier
+ Create Case action.
+ */}
+ <button
+ type="button"
+ onClick={() => setExplainOpen(true)}
+ className="bg-purple-600/90 hover:bg-purple-500 text-white text-sm font-medium px-4 py-1.5 rounded-lg transition-colors inline-flex items-center gap-1.5"
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden="true"
+ >
+ <path d="M12 2a7 7 0 0 0-4 12.74V17a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2v-2.26A7 7 0 0 0 12 2z" />
+ <line x1="9" y1="22" x2="15" y2="22" />
+ </svg>
+ Explain
+ </button>
<button className="bg-blue-600 hover:bg-blue-500 text-white text-sm font-medium px-4 py-1.5 rounded-lg transition-colors">
Create Case
</button>
@@ -1053,6 +1086,21 @@ export function AlertDetailView({ alertId }: { alertId: string }) {
</pre>
</Section>
)}
+
+ {/*
+ Explain drawer is mounted at the root of the detail view so it
+ can overlay tabs without unmounting on tab switch. It only fires
+ a network call when `open` flips true (see useEffect inside).
+ */}
+ <ExplainDrawer
+ open={explainOpen}
+ onClose={() => setExplainOpen(false)}
+ alert={alert}
+ onRunPlaybook={(pid) => {
+ toast.success(`Queued playbook ${pid}`);
+ setExplainOpen(false);
+ }}
+ />
</div>
);
}
diff --git a/apps/web/src/components/alerts/ExplainDrawer.tsx b/apps/web/src/components/alerts/ExplainDrawer.tsx
new file mode 100644
index 000000000..38a039038
--- /dev/null
+++ b/apps/web/src/components/alerts/ExplainDrawer.tsx
@@ -0,0 +1,576 @@
+'use client';
+
+/**
+ * ExplainDrawer
+ * =============
+ *
+ * Right-edge slide-over that streams an OCSF + MITRE-grounded explanation
+ * of a single alert. Backed by `services/agents` ` POST /api/v1/explain`
+ * (NDJSON stream).
+ *
+ * Why a drawer instead of inline?
+ * -------------------------------
+ * The alert detail page is already dense. A drawer keeps the alert grid
+ * intact while the analyst is still in the middle of reading the row, and
+ * gives us room for ATT&CK technique cards (which want their own width).
+ *
+ * Streaming model
+ * ---------------
+ * Each line of the response body is one {@link ExplainStreamFrame}. The
+ * drawer routes by `kind`:
+ *
+ * - `section` opens a new section (summary / ocsf / mitre / evidence /
+ * next) so the renderer can show a heading even before any content
+ * has arrived. This avoids the "blank drawer for 800ms" flash.
+ * - `delta` (only for the summary) appends a token. Buffered into one
+ * state field so React doesn't re-render per word.
+ * - `ocsf`, `mitre`, `evidence`, `next_step` are typed records.
+ * - `done` closes the stream cleanly.
+ * - `error` aborts and shows the message.
+ *
+ * Cancellation
+ * ------------
+ * We use an `AbortController` that fires on close + on unmount. This
+ * guarantees that closing the drawer also aborts an in-flight LLM call,
+ * which is important when the user clicks Explain on the wrong alert and
+ * immediately closes it.
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ agentsApi,
+ type Alert,
+ type ExplainEvidenceFrame,
+ type ExplainMitreFrame,
+ type ExplainNextStepFrame,
+ type ExplainOcsfFrame,
+ type ExplainStreamFrame,
+} from '@/lib/api';
+import { clsx } from 'clsx';
+
+// ─── Props ───────────────────────────────────────────────────────────────────
+
+export interface ExplainDrawerProps {
+ /** Whether the drawer is currently visible. */
+ open: boolean;
+ /** Called when the user requests to close (overlay click, ESC, X). */
+ onClose: () => void;
+ /** Source alert. We pass the full record to the backend. */
+ alert: Alert;
+ /**
+ * Optional callback when the user clicks "Run playbook" inside a
+ * recommended next-step card. The parent owns the actual run logic so
+ * the drawer stays presentational.
+ */
+ onRunPlaybook?: (playbookId: string) => void;
+}
+
+// ─── Internal state shape ────────────────────────────────────────────────────
+//
+// We keep everything keyed by section so frames can arrive in any order
+// without breaking the render. (The backend sends them in canonical order
+// today, but treating order as a hint not a contract makes this resilient
+// when we layer caching or replay later.)
+
+interface DrawerState {
+ status: 'idle' | 'loading' | 'streaming' | 'done' | 'error';
+ error?: string;
+ summary: string;
+ ocsf?: ExplainOcsfFrame;
+ mitre: ExplainMitreFrame[];
+ evidence: ExplainEvidenceFrame[];
+ nextSteps: ExplainNextStepFrame[];
+}
+
+const INITIAL: DrawerState = {
+ status: 'idle',
+ summary: '',
+ mitre: [],
+ evidence: [],
+ nextSteps: [],
+};
+
+// ─── Component ───────────────────────────────────────────────────────────────
+
+export function ExplainDrawer({
+ open,
+ onClose,
+ alert,
+ onRunPlaybook,
+}: ExplainDrawerProps) {
+ const [state, setState] = useState<DrawerState>(INITIAL);
+ const abortRef = useRef<AbortController | null>(null);
+
+ // The alert object we send to the backend. We strip large fields the
+ // server doesn't need so the request stays lean.
+ const alertPayload = useMemo(() => {
+ const { rawEvent: _rawEvent, ...rest } = alert as Alert & {
+ rawEvent?: unknown;
+ };
+ return rest as unknown as Record<string, unknown>;
+ }, [alert]);
+
+ const startStream = useCallback(async () => {
+ abortRef.current?.abort();
+ const ctrl = new AbortController();
+ abortRef.current = ctrl;
+
+ setState({ ...INITIAL, status: 'loading' });
+
+ try {
+ const response = await agentsApi.explainStream(
+ { alert: alertPayload, alertId: alert.id },
+ ctrl.signal,
+ );
+
+ if (!response.ok || !response.body) {
+ throw new Error(`Explain endpoint returned HTTP ${response.status}`);
+ }
+
+ setState((s) => ({ ...s, status: 'streaming' }));
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+
+ // NDJSON parse loop. Same pattern as ContextualActions.tsx — read
+ // chunks, split on newlines, JSON.parse each line, ignore empty
+ // lines. Buffering across chunks keeps us safe when a frame is
+ // split mid-line by the network layer.
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+
+ let nl = buffer.indexOf('\n');
+ while (nl !== -1) {
+ const line = buffer.slice(0, nl).trim();
+ buffer = buffer.slice(nl + 1);
+ nl = buffer.indexOf('\n');
+ if (!line) continue;
+
+ let frame: ExplainStreamFrame;
+ try {
+ frame = JSON.parse(line) as ExplainStreamFrame;
+ } catch {
+ continue;
+ }
+
+ setState((s) => applyFrame(s, frame));
+ if (frame.kind === 'error' || frame.kind === 'done') return;
+ }
+ }
+ } catch (err) {
+ if ((err as { name?: string })?.name === 'AbortError') return;
+ setState((s) => ({
+ ...s,
+ status: 'error',
+ error:
+ err instanceof Error
+ ? err.message
+ : 'Failed to load explanation.',
+ }));
+ }
+ }, [alert.id, alertPayload]);
+
+ // Open / close lifecycle. Restarts the stream on every open so the
+ // drawer is always fresh — alert state changes between opens.
+ useEffect(() => {
+ if (!open) {
+ abortRef.current?.abort();
+ return;
+ }
+ void startStream();
+ return () => {
+ abortRef.current?.abort();
+ };
+ }, [open, startStream]);
+
+ // ESC to close.
+ useEffect(() => {
+ if (!open) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') onClose();
+ };
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ }, [open, onClose]);
+
+ if (!open) return null;
+
+ return (
+ <div className="fixed inset-0 z-50 flex">
+ {/* Click-to-close overlay. */}
+ <button
+ type="button"
+ aria-label="Close"
+ onClick={onClose}
+ className="flex-1 bg-black/60 backdrop-blur-sm cursor-default"
+ />
+
+ {/* Drawer panel. */}
+ <aside
+ role="dialog"
+ aria-modal="true"
+ aria-label="Explain alert"
+ className="w-full max-w-2xl h-full bg-gray-950 border-l border-gray-800 shadow-2xl flex flex-col"
+ >
+ <DrawerHeader
+ alert={alert}
+ status={state.status}
+ onClose={onClose}
+ onRetry={state.status === 'error' ? startStream : undefined}
+ />
+
+ <div className="flex-1 overflow-y-auto px-6 py-4 space-y-6">
+ {state.status === 'error' && (
+ <ErrorBanner message={state.error || 'Unknown error'} />
+ )}
+
+ <SummarySection text={state.summary} status={state.status} />
+
+ {state.ocsf && <OcsfSection frame={state.ocsf} />}
+
+ {state.mitre.length > 0 && (
+ <MitreSection cards={state.mitre} />
+ )}
+
+ {state.evidence.length > 0 && (
+ <EvidenceSection items={state.evidence} />
+ )}
+
+ {state.nextSteps.length > 0 && (
+ <NextStepsSection
+ steps={state.nextSteps}
+ onRunPlaybook={onRunPlaybook}
+ />
+ )}
+
+ {state.status === 'done' && (
+ <div className="text-xs text-gray-500 text-center pt-2">
+ Generated by AiSOC. Always verify before taking action.
+ </div>
+ )}
+ </div>
+ </aside>
+ </div>
+ );
+}
+
+// ─── Frame reducer ───────────────────────────────────────────────────────────
+
+function applyFrame(state: DrawerState, frame: ExplainStreamFrame): DrawerState {
+ switch (frame.kind) {
+ case 'section':
+ // Sections themselves carry no content — we render the heading
+ // implicitly when their array becomes non-empty. Nothing to merge.
+ return state;
+ case 'delta':
+ return { ...state, summary: state.summary + frame.text };
+ case 'ocsf':
+ return { ...state, ocsf: frame };
+ case 'mitre':
+ // Dedupe by ID so a re-emitted card doesn't double-render.
+ if (state.mitre.some((m) => m.id === frame.id)) return state;
+ return { ...state, mitre: [...state.mitre, frame] };
+ case 'evidence':
+ return { ...state, evidence: [...state.evidence, frame] };
+ case 'next_step':
+ return { ...state, nextSteps: [...state.nextSteps, frame] };
+ case 'done':
+ return { ...state, status: 'done' };
+ case 'error':
+ return { ...state, status: 'error', error: frame.error };
+ default:
+ return state;
+ }
+}
+
+// ─── Subcomponents ───────────────────────────────────────────────────────────
+
+function DrawerHeader({
+ alert,
+ status,
+ onClose,
+ onRetry,
+}: {
+ alert: Alert;
+ status: DrawerState['status'];
+ onClose: () => void;
+ onRetry?: () => void;
+}) {
+ return (
+ <div className="flex items-start justify-between border-b border-gray-800 px-6 py-4 bg-gradient-to-r from-blue-500/10 to-purple-500/10">
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1">
+ <span className="text-xs font-semibold uppercase tracking-wider text-blue-400">
+ Explain
+ </span>
+ <StatusBadge status={status} />
+ </div>
+ <h2 className="text-lg font-semibold text-gray-100 truncate">
+ {alert.title}
+ </h2>
+ <p className="text-xs text-gray-400 mt-0.5">
+ {alert.source} · {alert.severity} · {alert.id}
+ </p>
+ </div>
+
+ <div className="flex items-center gap-2 ml-4">
+ {onRetry && (
+ <button
+ type="button"
+ onClick={onRetry}
+ className="text-xs px-3 py-1.5 rounded-md bg-gray-800 text-gray-200 hover:bg-gray-700 transition"
+ >
+ Retry
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close"
+ className="text-gray-400 hover:text-gray-100 transition p-1"
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <line x1="18" y1="6" x2="6" y2="18" />
+ <line x1="6" y1="6" x2="18" y2="18" />
+ </svg>
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function StatusBadge({ status }: { status: DrawerState['status'] }) {
+ const map: Record<DrawerState['status'], { label: string; cls: string }> = {
+ idle: { label: 'Idle', cls: 'bg-gray-500/10 text-gray-400 ring-gray-500/20' },
+ loading: {
+ label: 'Loading…',
+ cls: 'bg-blue-500/10 text-blue-300 ring-blue-500/20',
+ },
+ streaming: {
+ label: 'Streaming',
+ cls: 'bg-blue-500/10 text-blue-300 ring-blue-500/20',
+ },
+ done: {
+ label: 'Done',
+ cls: 'bg-emerald-500/10 text-emerald-400 ring-emerald-500/20',
+ },
+ error: { label: 'Error', cls: 'bg-red-500/10 text-red-400 ring-red-500/20' },
+ };
+ const { label, cls } = map[status];
+ return (
+ <span
+ className={clsx(
+ 'text-[10px] font-mono px-2 py-0.5 rounded ring-1 ring-inset',
+ cls,
+ )}
+ >
+ {label}
+ </span>
+ );
+}
+
+function ErrorBanner({ message }: { message: string }) {
+ return (
+ <div className="rounded-md border border-red-500/30 bg-red-500/5 px-4 py-3 text-sm text-red-300">
+ {message}
+ </div>
+ );
+}
+
+function SectionHeading({ children }: { children: React.ReactNode }) {
+ return (
+ <h3 className="text-xs font-semibold uppercase tracking-wider text-gray-400 mb-2">
+ {children}
+ </h3>
+ );
+}
+
+function SummarySection({
+ text,
+ status,
+}: {
+ text: string;
+ status: DrawerState['status'];
+}) {
+ const showCursor = status === 'loading' || status === 'streaming';
+ return (
+ <section>
+ <SectionHeading>What happened</SectionHeading>
+ <p className="text-sm text-gray-200 leading-relaxed whitespace-pre-wrap">
+ {text || (status === 'loading' ? 'Generating explanation…' : '—')}
+ {showCursor && text && (
+ <span className="inline-block w-1.5 h-4 ml-0.5 bg-blue-400 animate-pulse align-middle" />
+ )}
+ </p>
+ </section>
+ );
+}
+
+function OcsfSection({ frame }: { frame: ExplainOcsfFrame }) {
+ const hasFields = Object.keys(frame.fields || {}).length > 0;
+ return (
+ <section>
+ <SectionHeading>OCSF mapping</SectionHeading>
+ <div className="rounded-md border border-gray-800 bg-gray-900/60 p-4 space-y-2">
+ <div className="flex flex-wrap gap-3 text-xs">
+ <Tag label="Category" value={`${frame.category} (${frame.category_uid})`} />
+ <Tag label="Class" value={`${frame.class} (${frame.class_uid})`} />
+ <Tag label="Activity" value={frame.activity} />
+ </div>
+ {hasFields && (
+ <dl className="grid grid-cols-[max-content,1fr] gap-x-3 gap-y-1 text-xs pt-2 border-t border-gray-800/80">
+ {Object.entries(frame.fields).map(([k, v]) => (
+ <FieldRow key={k} label={k} value={String(v)} />
+ ))}
+ </dl>
+ )}
+ </div>
+ </section>
+ );
+}
+
+function MitreSection({ cards }: { cards: ExplainMitreFrame[] }) {
+ return (
+ <section>
+ <SectionHeading>MITRE ATT&CK</SectionHeading>
+ <div className="space-y-2">
+ {cards.map((c) => (
+ <a
+ key={c.id}
+ href={c.url}
+ target="_blank"
+ rel="noreferrer noopener"
+ className="block rounded-md border border-purple-500/20 bg-purple-500/5 p-3 hover:bg-purple-500/10 transition"
+ >
+ <div className="flex items-center gap-2 mb-1">
+ <span className="text-xs font-mono text-purple-300 bg-purple-500/15 px-2 py-0.5 rounded">
+ {c.id}
+ </span>
+ <span className="text-sm font-medium text-gray-100">{c.name}</span>
+ {!c.found && (
+ <span className="text-[10px] text-amber-400 ml-auto">
+ corpus unavailable
+ </span>
+ )}
+ </div>
+ {c.tactic_names.length > 0 && (
+ <div className="text-xs text-gray-400 mb-1">
+ Tactics: {c.tactic_names.join(', ')}
+ </div>
+ )}
+ {c.description && (
+ <p className="text-xs text-gray-300 leading-relaxed">
+ {c.description}
+ </p>
+ )}
+ </a>
+ ))}
+ </div>
+ </section>
+ );
+}
+
+function EvidenceSection({ items }: { items: ExplainEvidenceFrame[] }) {
+ return (
+ <section>
+ <SectionHeading>Key evidence</SectionHeading>
+ <ul className="space-y-1.5">
+ {items.map((e, i) => (
+ <li
+ key={`${e.label}-${i}`}
+ className="flex items-baseline gap-3 text-sm"
+ >
+ <span className="text-xs text-gray-500 min-w-[100px]">
+ {e.label}
+ </span>
+ <span className="font-mono text-gray-100 break-all">
+ {e.value}
+ </span>
+ {e.annotation && (
+ <span className="text-xs text-gray-400 ml-auto">
+ {e.annotation}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ </section>
+ );
+}
+
+function NextStepsSection({
+ steps,
+ onRunPlaybook,
+}: {
+ steps: ExplainNextStepFrame[];
+ onRunPlaybook?: (playbookId: string) => void;
+}) {
+ return (
+ <section>
+ <SectionHeading>Next steps</SectionHeading>
+ <div className="space-y-2">
+ {steps.map((s, i) => (
+ <div
+ key={`${s.title}-${i}`}
+ className="rounded-md border border-gray-800 bg-gray-900/60 p-3"
+ >
+ <div className="flex items-start justify-between gap-2 mb-1">
+ <h4 className="text-sm font-medium text-gray-100">{s.title}</h4>
+ {s.playbook_id && onRunPlaybook && (
+ <button
+ type="button"
+ onClick={() => onRunPlaybook(s.playbook_id!)}
+ className="text-xs px-2.5 py-1 rounded bg-blue-500/15 text-blue-300 hover:bg-blue-500/25 ring-1 ring-inset ring-blue-500/30 transition"
+ >
+ Run playbook
+ </button>
+ )}
+ </div>
+ <p className="text-xs text-gray-300 leading-relaxed">
+ {s.rationale}
+ </p>
+ {s.playbook_id && (
+ <div className="text-[10px] font-mono text-gray-500 mt-1">
+ {s.playbook_id}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </section>
+ );
+}
+
+// ─── Tiny presentational atoms ───────────────────────────────────────────────
+
+function Tag({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="flex items-baseline gap-1.5">
+ <span className="text-gray-500">{label}</span>
+ <span className="text-gray-200 font-medium">{value}</span>
+ </div>
+ );
+}
+
+function FieldRow({ label, value }: { label: string; value: string }) {
+ return (
+ <>
+ <dt className="text-gray-500 font-mono">{label}</dt>
+ <dd className="text-gray-200 font-mono break-all">{value}</dd>
+ </>
+ );
+}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 75a147616..3b8973ea0 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1753,8 +1753,105 @@ export const agentsApi = {
body: JSON.stringify({ alertId }),
signal,
}),
+
+ /**
+ * Stream a structured "Explain this alert" walkthrough as NDJSON.
+ *
+ * Each line in `response.body` is one {@link ExplainStreamFrame}.
+ * Returns the raw `Response` because the drawer renders frames as
+ * they arrive — see `ExplainDrawer.tsx` for the consumer.
+ */
+ explainStream: (
+ payload: { alert: Record<string, unknown>; alertId?: string },
+ signal?: AbortSignal,
+ ) =>
+ fetch(`${AGENTS_BASE}/api/v1/explain`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Tenant-Id': TENANT_ID,
+ },
+ body: JSON.stringify({
+ alert: payload.alert,
+ alert_id: payload.alertId,
+ tenant_id: TENANT_ID,
+ }),
+ signal,
+ }),
};
+// ─── Explain endpoint frames ─────────────────────────────────────────────────
+//
+// One frame per NDJSON line. The drawer routes each frame by `kind` and
+// appends to the matching section, so order matters: `section` opens a
+// section, subsequent typed frames fill it, and `done` closes the stream.
+
+export interface ExplainSectionFrame {
+ kind: 'section';
+ id: 'summary' | 'ocsf' | 'mitre' | 'evidence' | 'next';
+ title: string;
+}
+
+export interface ExplainDeltaFrame {
+ kind: 'delta';
+ section: 'summary';
+ text: string;
+}
+
+export interface ExplainOcsfFrame {
+ kind: 'ocsf';
+ category: string;
+ category_uid: number;
+ class: string;
+ class_uid: number;
+ activity: string;
+ fields: Record<string, unknown>;
+}
+
+export interface ExplainMitreFrame {
+ kind: 'mitre';
+ id: string;
+ name: string;
+ tactic_names: string[];
+ description: string;
+ url: string;
+ found: boolean;
+}
+
+export interface ExplainEvidenceFrame {
+ kind: 'evidence';
+ label: string;
+ value: string;
+ annotation: string;
+}
+
+export interface ExplainNextStepFrame {
+ kind: 'next_step';
+ title: string;
+ rationale: string;
+ playbook_id: string | null;
+}
+
+export interface ExplainDoneFrame {
+ kind: 'done';
+ alert_id: string;
+}
+
+export interface ExplainErrorFrame {
+ kind: 'error';
+ error: string;
+}
+
+export type ExplainStreamFrame =
+ | ExplainSectionFrame
+ | ExplainDeltaFrame
+ | ExplainOcsfFrame
+ | ExplainMitreFrame
+ | ExplainEvidenceFrame
+ | ExplainNextStepFrame
+ | ExplainDoneFrame
+ | ExplainErrorFrame;
+
// ─── Hunt / Search ───────────────────────────────────────────────────────────
export interface HuntQuery {
diff --git a/services/agents/app/api/explain.py b/services/agents/app/api/explain.py
new file mode 100644
index 000000000..3243c8271
--- /dev/null
+++ b/services/agents/app/api/explain.py
@@ -0,0 +1,599 @@
+"""
+Explain endpoint — turns an alert into a grounded, human-readable answer to
+"why did this fire and what should I do?".
+
+Endpoint
+--------
+
+ POST /api/v1/explain — NDJSON stream
+
+Why this exists separately from ``copilot.py``
+----------------------------------------------
+
+Copilot is freeform chat. Explain is **structured grounding**: every
+emitted frame is one of a small set of typed sections (summary, OCSF
+mapping, MITRE technique cards pulled from the local corpus, evidence,
+next-step recommendations). The frontend renders each frame
+deterministically, so the analyst gets the same drawer shape whether the
+LLM is enabled, disabled, or running locally — and so the UI can link
+directly to attack.mitre.org without trusting the model not to
+hallucinate IDs.
+
+Air-gap behaviour
+-----------------
+
+- ``AISOC_AIRGAPPED=true`` → no outbound LLM call, ever
+- ``OPENAI_BASE_URL`` set to a non-OpenAI host (LiteLLM, Ollama, vLLM)
+ → allowed in air-gap mode
+- Otherwise → openai.com, gated on the
+ presence of ``OPENAI_API_KEY``
+
+When the LLM path is skipped, the deterministic synthesizer fills the
+``summary`` section from the alert payload itself, so the demo path
+never breaks.
+
+NDJSON frame shapes
+-------------------
+
+Each line is a single JSON object. Frames are emitted in this order::
+
+ {"kind": "section", "id": "summary", "title": "What happened"}
+ {"kind": "delta", "section": "summary", "text": "..."} (×N)
+ {"kind": "section", "id": "ocsf", "title": "OCSF mapping"}
+ {"kind": "ocsf", "category": "...", "category_uid": 3,
+ "class": "...", "class_uid": 3002,
+ "activity": "...", "fields": {...}}
+ {"kind": "section", "id": "mitre", "title": "MITRE ATT&CK"}
+ {"kind": "mitre", "id": "T1078", "name": "Valid Accounts",
+ "tactic_names": [...], "url": "...",
+ "description": "..."} (×N)
+ {"kind": "section", "id": "evidence", "title": "Key evidence"}
+ {"kind": "evidence","label": "...", "value": "...",
+ "annotation": "..."} (×N)
+ {"kind": "section", "id": "next", "title": "Next steps"}
+ {"kind": "next_step","title": "...", "rationale": "...",
+ "playbook_id": null} (×N)
+ {"kind": "done", "alert_id": "..."}
+
+The first ``error`` frame, if any, is fatal — the client should display
+it and stop reading.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import re
+from collections.abc import AsyncIterator
+from typing import Any
+
+import structlog
+from fastapi import APIRouter
+from fastapi.responses import StreamingResponse
+from pydantic import BaseModel, Field
+
+logger = structlog.get_logger()
+
+router = APIRouter(prefix="/api/v1", tags=["explain"])
+
+
+# ---------------------------------------------------------------------------
+# Request shape
+# ---------------------------------------------------------------------------
+
+
+class ExplainRequest(BaseModel):
+ """Body of POST /api/v1/explain.
+
+ The frontend already has the full alert object in hand from the
+ detail view, so we accept it verbatim rather than re-fetching by ID.
+ Falls back to ``alert_id`` lookup later if needed.
+ """
+
+ alert: dict[str, Any] = Field(default_factory=dict)
+ alert_id: str | None = None
+ tenant_id: str = "default"
+
+
+# ---------------------------------------------------------------------------
+# OCSF heuristic mapping
+# ---------------------------------------------------------------------------
+#
+# We do NOT re-implement the canonical OCSF normalizer here — that lives in
+# ``services/ocsf``. The Explain drawer's job is to *label* the right OCSF
+# class so an analyst knows where in the schema to look. Source-string
+# heuristics are good enough for that and degrade gracefully (we always
+# fall back to the generic Security Finding class).
+
+_OCSF_BY_SOURCE: dict[str, dict[str, Any]] = {
+ "okta": {
+ "category": "Identity & Access Management",
+ "category_uid": 3,
+ "class": "Authentication",
+ "class_uid": 3002,
+ "activity": "Logon",
+ },
+ "azure-ad": {
+ "category": "Identity & Access Management",
+ "category_uid": 3,
+ "class": "Authentication",
+ "class_uid": 3002,
+ "activity": "Logon",
+ },
+ "crowdstrike": {
+ "category": "System Activity",
+ "category_uid": 1,
+ "class": "Process Activity",
+ "class_uid": 1007,
+ "activity": "Launch",
+ },
+ "defender": {
+ "category": "System Activity",
+ "category_uid": 1,
+ "class": "Process Activity",
+ "class_uid": 1007,
+ "activity": "Launch",
+ },
+ "aws-guardduty": {
+ "category": "Findings",
+ "category_uid": 2,
+ "class": "Security Finding",
+ "class_uid": 2001,
+ "activity": "Create",
+ },
+ "aws-cloudtrail": {
+ "category": "Application Activity",
+ "category_uid": 6,
+ "class": "API Activity",
+ "class_uid": 6003,
+ "activity": "Create",
+ },
+ "github": {
+ "category": "Application Activity",
+ "category_uid": 6,
+ "class": "API Activity",
+ "class_uid": 6003,
+ "activity": "Read",
+ },
+ "splunk": {
+ "category": "Findings",
+ "category_uid": 2,
+ "class": "Security Finding",
+ "class_uid": 2001,
+ "activity": "Create",
+ },
+ "elastic": {
+ "category": "Findings",
+ "category_uid": 2,
+ "class": "Security Finding",
+ "class_uid": 2001,
+ "activity": "Create",
+ },
+}
+
+_OCSF_FALLBACK = {
+ "category": "Findings",
+ "category_uid": 2,
+ "class": "Security Finding",
+ "class_uid": 2001,
+ "activity": "Create",
+}
+
+
+def _map_to_ocsf(alert: dict[str, Any]) -> dict[str, Any]:
+ """Pick a sensible OCSF class label for the alert."""
+ src = (alert.get("source") or "").lower().strip()
+ for key, mapping in _OCSF_BY_SOURCE.items():
+ if key in src:
+ base = dict(mapping)
+ break
+ else:
+ base = dict(_OCSF_FALLBACK)
+
+ raw = alert.get("rawEvent") or alert.get("raw_event") or {}
+ fields: dict[str, Any] = {}
+ for key in ("user", "user_name", "username", "actor", "src_ip",
+ "source_ip", "dest_ip", "destination_ip", "host",
+ "hostname", "process", "process_name", "file_hash",
+ "domain", "url"):
+ if isinstance(raw, dict) and raw.get(key):
+ fields[key] = raw[key]
+
+ base["fields"] = fields
+ return base
+
+
+# ---------------------------------------------------------------------------
+# MITRE grounding — pull real technique cards from the loaded corpus
+# ---------------------------------------------------------------------------
+
+_MITRE_ID_RE = re.compile(r"\bT\d{4}(?:\.\d{3})?\b")
+
+
+def _extract_mitre_ids(alert: dict[str, Any]) -> list[str]:
+ """Return ATT&CK technique IDs referenced by the alert.
+
+ Looks at the structured ``mitreAttack`` field first (canonical),
+ then scans tags and free-text fields with the T-ID regex so older
+ detections still produce cards.
+ """
+ found: list[str] = []
+ seen: set[str] = set()
+
+ # Structured field — preferred
+ mitre = alert.get("mitreAttack") or alert.get("mitre_attack") or []
+ if isinstance(mitre, list):
+ for item in mitre:
+ tid = None
+ if isinstance(item, dict):
+ tid = item.get("techniqueId") or item.get("technique_id") or item.get("id")
+ elif isinstance(item, str):
+ tid = item
+ if tid and tid not in seen:
+ found.append(tid)
+ seen.add(tid)
+
+ # Regex sweep across tags + descriptive text
+ text_pool = " ".join(
+ str(v)
+ for v in (
+ alert.get("tags") or []
+ )
+ ) + " " + str(alert.get("description") or "") + " " + str(alert.get("title") or "")
+
+ for tid in _MITRE_ID_RE.findall(text_pool):
+ if tid not in seen:
+ found.append(tid)
+ seen.add(tid)
+
+ return found[:5] # cap so the drawer stays scannable
+
+
+def _resolve_technique(technique_id: str) -> dict[str, Any]:
+ """Return a MITRE card dict from the corpus, or a stub if unloaded.
+
+ ``mitre_full.get_technique`` returns ``found=False`` for unknown
+ IDs; we use that as the signal to emit a degraded card.
+ """
+ try:
+ from app.tools.mitre_full import get_technique
+ except Exception as exc:
+ logger.debug("explain.mitre_corpus_unavailable", error=str(exc))
+ return {
+ "id": technique_id,
+ "name": technique_id,
+ "tactic_names": [],
+ "description": "",
+ "url": f"https://attack.mitre.org/techniques/{technique_id.replace('.', '/')}/",
+ "found": False,
+ }
+
+ raw = get_technique(technique_id)
+ desc = (raw.get("description") or "").strip()
+ return {
+ "id": raw.get("id", technique_id),
+ "name": raw.get("name", technique_id),
+ "tactic_names": raw.get("tactic_names") or [],
+ "description": desc[:280] + ("…" if len(desc) > 280 else ""),
+ "url": raw.get("url") or f"https://attack.mitre.org/techniques/{technique_id.replace('.', '/')}/",
+ "found": bool(raw.get("found")),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Evidence + next steps
+# ---------------------------------------------------------------------------
+
+
+def _extract_evidence(alert: dict[str, Any]) -> list[dict[str, str]]:
+ """Pull a small, scannable list of observables from the alert."""
+ items: list[dict[str, str]] = []
+ raw = alert.get("rawEvent") or alert.get("raw_event") or {}
+
+ def add(label: str, value: Any, annotation: str = "") -> None:
+ if value in (None, "", [], {}):
+ return
+ items.append(
+ {
+ "label": label,
+ "value": str(value)[:160],
+ "annotation": annotation,
+ }
+ )
+
+ add("Severity", alert.get("severity"))
+ add("Risk score", alert.get("riskScore") or alert.get("risk_score"))
+ add("Source", alert.get("source"))
+
+ if isinstance(raw, dict):
+ for label, key in (
+ ("User", "user"),
+ ("User", "user_name"),
+ ("Source IP", "src_ip"),
+ ("Source IP", "source_ip"),
+ ("Destination IP", "dest_ip"),
+ ("Destination IP", "destination_ip"),
+ ("Host", "hostname"),
+ ("Host", "host"),
+ ("Process", "process_name"),
+ ("Process", "process"),
+ ("File hash", "file_hash"),
+ ("Domain", "domain"),
+ ("URL", "url"),
+ ):
+ if raw.get(key) and not any(it["label"] == label for it in items):
+ add(label, raw[key])
+
+ iocs = alert.get("iocs") or []
+ if isinstance(iocs, list):
+ for ioc in iocs[:3]:
+ if isinstance(ioc, dict) and ioc.get("value"):
+ add(f"IOC ({ioc.get('type', 'indicator')})", ioc["value"])
+
+ return items[:8]
+
+
+def _build_next_steps(
+ alert: dict[str, Any], mitre_ids: list[str]
+) -> list[dict[str, Any]]:
+ """Recommend concrete next moves grounded in alert tags / techniques.
+
+ These are intentionally generic and link to the playbook engine so
+ analysts can one-click run them. The list is curated, not generated,
+ so the LLM can never hallucinate a non-existent playbook ID.
+ """
+ tags = {str(t).lower() for t in (alert.get("tags") or [])}
+ severity = (alert.get("severity") or "").lower()
+ steps: list[dict[str, Any]] = []
+
+ if "account-takeover" in tags or "ato" in tags or "T1078" in mitre_ids:
+ steps.append(
+ {
+ "title": "Run ATO containment playbook",
+ "rationale": "Block sessions, force password reset, and require step-up MFA on the affected identity.",
+ "playbook_id": "ato-impossible-travel-block-v1",
+ }
+ )
+
+ if "ransomware" in tags or "T1486" in mitre_ids:
+ steps.append(
+ {
+ "title": "Isolate the host",
+ "rationale": "Suspected ransomware activity — quarantine the endpoint to stop encryption spread.",
+ "playbook_id": "ransomware-host-isolate-v1",
+ }
+ )
+
+ if "phishing" in tags or "bec" in tags:
+ steps.append(
+ {
+ "title": "Pull the message and similar deliveries",
+ "rationale": "Identify other recipients and remove the message from inboxes before clicks propagate.",
+ "playbook_id": "phishing-message-pull-v1",
+ }
+ )
+
+ if any(t.startswith("T1190") or t.startswith("T1133") for t in mitre_ids):
+ steps.append(
+ {
+ "title": "Tighten perimeter exposure",
+ "rationale": "Initial access vector points at an external-facing service — review WAF rules and patch level.",
+ "playbook_id": None,
+ }
+ )
+
+ # Always-applicable triage steps — only if we have nothing else.
+ if not steps:
+ steps.append(
+ {
+ "title": "Correlate with the last 24 h of alerts",
+ "rationale": "Look for the same user, host, or IOC in adjacent detections to spot a multi-stage attack.",
+ "playbook_id": None,
+ }
+ )
+
+ if severity in ("high", "critical"):
+ steps.append(
+ {
+ "title": "Open a case and notify on-call",
+ "rationale": f"Severity is {severity}; promote to a tracked incident before further investigation.",
+ "playbook_id": None,
+ }
+ )
+
+ return steps[:4]
+
+
+def _build_summary(alert: dict[str, Any], mitre_ids: list[str]) -> str:
+ """Deterministic 2–3 sentence summary used when the LLM is disabled."""
+ title = alert.get("title") or "Security alert"
+ severity = (alert.get("severity") or "unknown").lower()
+ source = alert.get("source") or "an unknown source"
+ desc = (alert.get("description") or "").strip()
+
+ technique_clause = ""
+ if mitre_ids:
+ technique_clause = (
+ f" The detection maps to {', '.join(mitre_ids[:3])}, "
+ "which the technique cards below describe in full."
+ )
+
+ base = (
+ f"{title} fired at {severity} severity from {source}."
+ f"{technique_clause}"
+ )
+ if desc:
+ # Trim to keep the drawer scannable.
+ snippet = desc if len(desc) <= 240 else desc[:237] + "…"
+ base += f" {snippet}"
+ return base
+
+
+# ---------------------------------------------------------------------------
+# LLM call (optional, best-effort)
+# ---------------------------------------------------------------------------
+
+
+def _llm_allowed() -> bool:
+ """Decide whether to attempt an outbound LLM call.
+
+ Honours ``AISOC_AIRGAPPED``: when true, only allow if
+ ``OPENAI_BASE_URL`` is set to something other than openai.com (i.e.
+ a local LiteLLM/Ollama proxy on a private host).
+ """
+ if not os.getenv("OPENAI_API_KEY"):
+ return False
+
+ airgapped = os.getenv("AISOC_AIRGAPPED", "").lower() in ("1", "true", "yes")
+ if not airgapped:
+ return True
+
+ base = (os.getenv("OPENAI_BASE_URL") or "").lower()
+ if not base:
+ return False # would hit api.openai.com — blocked
+ return "api.openai.com" not in base
+
+
+async def _llm_summary(
+ alert: dict[str, Any],
+ mitre_techs: list[dict[str, Any]],
+ fallback: str,
+) -> str:
+ """Ask the model for a tightly-scoped summary, with a hard fallback.
+
+ The prompt deliberately forbids inventing technique IDs — the
+ structured cards are emitted from the corpus, so the model only ever
+ explains, never enumerates.
+ """
+ if not _llm_allowed():
+ return fallback
+
+ try:
+ import httpx
+
+ base = (os.getenv("OPENAI_BASE_URL") or "https://api.openai.com").rstrip("/")
+ url = f"{base}/v1/chat/completions"
+ model = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
+
+ tech_lines = [
+ f"- {t['id']} {t['name']} ({', '.join(t.get('tactic_names') or []) or 'unknown tactic'})"
+ for t in mitre_techs
+ ]
+ prompt_alert = {
+ "title": alert.get("title"),
+ "severity": alert.get("severity"),
+ "source": alert.get("source"),
+ "description": alert.get("description"),
+ "tags": alert.get("tags") or [],
+ }
+
+ messages = [
+ {
+ "role": "system",
+ "content": (
+ "You are AiSOC's alert explainer. Given one security alert and a "
+ "list of MITRE ATT&CK techniques already pulled from the local "
+ "corpus, write a tight 2–4 sentence summary for an L1/L2 SOC "
+ "analyst. Be concrete about WHAT happened and WHY it matters. "
+ "Never invent technique IDs, vendor names, or IOCs that aren't "
+ "in the input. No bullet lists, no headings — just prose."
+ ),
+ },
+ {
+ "role": "user",
+ "content": json.dumps(
+ {
+ "alert": prompt_alert,
+ "mitre_techniques": tech_lines,
+ },
+ indent=2,
+ ),
+ },
+ ]
+
+ async with httpx.AsyncClient(timeout=20) as client:
+ resp = await client.post(
+ url,
+ headers={"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"},
+ json={"model": model, "messages": messages, "max_tokens": 320},
+ )
+ resp.raise_for_status()
+ return resp.json()["choices"][0]["message"]["content"].strip()
+
+ except Exception as exc:
+ logger.warning("explain.llm_error", error=str(exc))
+ return fallback
+
+
+# ---------------------------------------------------------------------------
+# Stream
+# ---------------------------------------------------------------------------
+
+
+def _frame(obj: dict[str, Any]) -> bytes:
+ return (json.dumps(obj) + "\n").encode()
+
+
+async def _stream_explanation(req: ExplainRequest) -> AsyncIterator[bytes]:
+ alert = req.alert or {}
+ alert_id = req.alert_id or alert.get("id") or "unknown"
+
+ try:
+ # ── 1. SUMMARY ────────────────────────────────────────────────────
+ mitre_ids = _extract_mitre_ids(alert)
+ mitre_cards = [_resolve_technique(t) for t in mitre_ids]
+
+ fallback_summary = _build_summary(alert, mitre_ids)
+ # Run the LLM call concurrently with the deterministic emissions
+ # so the drawer paints fast even on a cold network.
+ summary_task = asyncio.create_task(
+ _llm_summary(alert, mitre_cards, fallback_summary)
+ )
+
+ yield _frame({"kind": "section", "id": "summary", "title": "What happened"})
+ # Stream the summary word-by-word once it resolves.
+ summary_text = await summary_task
+ for word in summary_text.split(" "):
+ yield _frame({"kind": "delta", "section": "summary", "text": word + " "})
+ await asyncio.sleep(0.005)
+
+ # ── 2. OCSF MAPPING ───────────────────────────────────────────────
+ yield _frame({"kind": "section", "id": "ocsf", "title": "OCSF mapping"})
+ ocsf = _map_to_ocsf(alert)
+ yield _frame({"kind": "ocsf", **ocsf})
+
+ # ── 3. MITRE CARDS ────────────────────────────────────────────────
+ if mitre_cards:
+ yield _frame({"kind": "section", "id": "mitre", "title": "MITRE ATT&CK"})
+ for card in mitre_cards:
+ yield _frame({"kind": "mitre", **card})
+
+ # ── 4. EVIDENCE ───────────────────────────────────────────────────
+ evidence = _extract_evidence(alert)
+ if evidence:
+ yield _frame({"kind": "section", "id": "evidence", "title": "Key evidence"})
+ for item in evidence:
+ yield _frame({"kind": "evidence", **item})
+
+ # ── 5. NEXT STEPS ─────────────────────────────────────────────────
+ next_steps = _build_next_steps(alert, mitre_ids)
+ yield _frame({"kind": "section", "id": "next", "title": "Next steps"})
+ for step in next_steps:
+ yield _frame({"kind": "next_step", **step})
+
+ # ── DONE ──────────────────────────────────────────────────────────
+ yield _frame({"kind": "done", "alert_id": alert_id})
+
+ except Exception as exc: # noqa: BLE001 — frontend gets a structured error
+ logger.exception("explain.stream_failed", error=str(exc))
+ yield _frame({"kind": "error", "error": str(exc)})
+
+
[email protected]("/explain")
+async def explain(req: ExplainRequest) -> StreamingResponse:
+ """Stream an OCSF + MITRE-grounded explanation of an alert as NDJSON."""
+ return StreamingResponse(
+ _stream_explanation(req),
+ media_type="application/x-ndjson",
+ )
diff --git a/services/agents/app/main.py b/services/agents/app/main.py
index a402fc251..620a94afc 100644
--- a/services/agents/app/main.py
+++ b/services/agents/app/main.py
@@ -8,6 +8,7 @@ from fastapi.middleware.cors import CORSMiddleware
from app.api.contextual import router as contextual_router
from app.api.copilot import router as copilot_router
+from app.api.explain import router as explain_router
from app.api.hunt_search import router as hunt_search_router
from app.api.hunts import router as hunts_router
from app.api.investigate import router as investigate_router
@@ -125,6 +126,7 @@ app.include_router(contextual_router) # prefix: /api/v1/contextual
app.include_router(hunts_router) # prefix: /api/v1/hunts
app.include_router(hunt_search_router) # prefix: /api/v1/hunt (search + saved)
app.include_router(copilot_router) # prefix: /api/v1/copilot
+app.include_router(explain_router) # prefix: /api/v1 (POST /explain — NDJSON stream)
@app.get("/health")
diff --git a/services/agents/tests/smoke_explain.py b/services/agents/tests/smoke_explain.py
new file mode 100644
index 000000000..50176627d
--- /dev/null
+++ b/services/agents/tests/smoke_explain.py
@@ -0,0 +1,180 @@
+"""Smoke test for the /api/v1/explain NDJSON streaming endpoint.
+
+Runs the actual `_stream_explanation` async generator against a realistic
+alert payload (impossible-travel ATO with MITRE T1078) and validates every
+emitted frame:
+
+ * Order: section → (delta|ocsf|mitre|evidence|next_step) → done
+ * No malformed JSON, no missing required keys per `kind`
+ * MITRE technique cards resolve from the local corpus when available
+ (we tolerate `found=False` because the corpus loader is async and
+ fires on FastAPI startup, not from a bare smoke)
+ * `done` frame echoes the incoming alert id
+
+Run with::
+
+ cd services/agents
+ PYTHONPATH=. .venv/bin/python tests/smoke_explain.py
+
+Exits non-zero on any structural failure so CI can pick it up later.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import sys
+from typing import Any
+
+# Force LLM off so the smoke is deterministic and offline.
+import os
+os.environ.pop("OPENAI_API_KEY", None)
+os.environ["AISOC_AIRGAPPED"] = "true"
+
+from app.api.explain import ExplainRequest, _stream_explanation # noqa: E402
+
+
+SAMPLE_ALERT: dict[str, Any] = {
+ "id": "ALERT-SMOKE-0001",
+ "title": "Impossible travel — login from Frankfurt then Tokyo within 8 minutes",
+ "severity": "high",
+ "source": "okta",
+ "description": (
+ "User authenticated successfully from two geographically impossible "
+ "locations within an 8-minute window. Likely account takeover."
+ ),
+ "tags": ["account-takeover", "ato", "identity"],
+ "mitreAttack": [{"techniqueId": "T1078"}],
+ "iocs": [
+ {"type": "ip", "value": "203.0.113.42"},
+ {"type": "ip", "value": "198.51.100.7"},
+ ],
+ "rawEvent": {
+ "user_name": "alice.tan",
+ "src_ip": "203.0.113.42",
+ "hostname": "okta-prod",
+ },
+}
+
+
+REQUIRED_KEYS = {
+ "section": {"kind", "id", "title"},
+ "delta": {"kind", "section", "text"},
+ "ocsf": {"kind", "category", "category_uid", "class", "class_uid", "activity", "fields"},
+ "mitre": {"kind", "id", "name", "tactic_names", "description", "url", "found"},
+ "evidence": {"kind", "label", "value", "annotation"},
+ "next_step": {"kind", "title", "rationale", "playbook_id"},
+ "done": {"kind", "alert_id"},
+ "error": {"kind", "error"},
+}
+
+
+async def _run() -> int:
+ req = ExplainRequest(alert=SAMPLE_ALERT, alert_id=SAMPLE_ALERT["id"])
+
+ frames: list[dict[str, Any]] = []
+ async for chunk in _stream_explanation(req):
+ line = chunk.decode().strip()
+ if not line:
+ continue
+ try:
+ frame = json.loads(line)
+ except json.JSONDecodeError as exc:
+ print(f"FAIL: malformed JSON line: {line!r} ({exc})")
+ return 1
+ frames.append(frame)
+ # One-line preview so we can eyeball the actual content.
+ preview = json.dumps(frame)
+ print(preview[:160] + ("…" if len(preview) > 160 else ""))
+
+ # ── Structural assertions ────────────────────────────────────────────
+ if not frames:
+ print("FAIL: no frames emitted")
+ return 1
+
+ # 1. Last frame is `done` (no error).
+ last = frames[-1]
+ if last.get("kind") == "error":
+ print(f"FAIL: stream errored: {last.get('error')}")
+ return 1
+ if last.get("kind") != "done":
+ print(f"FAIL: last frame is {last.get('kind')!r}, expected 'done'")
+ return 1
+ if last.get("alert_id") != SAMPLE_ALERT["id"]:
+ print(f"FAIL: done frame alert_id mismatch: {last.get('alert_id')!r}")
+ return 1
+
+ # 2. Every frame has the required keys for its kind.
+ for i, frame in enumerate(frames):
+ kind = frame.get("kind")
+ if kind not in REQUIRED_KEYS:
+ print(f"FAIL: frame {i} has unknown kind {kind!r}")
+ return 1
+ missing = REQUIRED_KEYS[kind] - frame.keys()
+ if missing:
+ print(f"FAIL: frame {i} ({kind}) missing keys {missing}")
+ return 1
+
+ # 3. Each canonical section opens with a `section` frame.
+ section_ids = [f["id"] for f in frames if f["kind"] == "section"]
+ expected_sections = ["summary", "ocsf", "mitre", "evidence", "next"]
+ if section_ids != expected_sections:
+ print(
+ f"FAIL: section order is {section_ids!r}, expected {expected_sections!r}"
+ )
+ return 1
+
+ # 4. We got a real OCSF mapping for an Okta-sourced alert.
+ ocsf_frame = next((f for f in frames if f["kind"] == "ocsf"), None)
+ if ocsf_frame is None:
+ print("FAIL: no ocsf frame")
+ return 1
+ if ocsf_frame["class_uid"] != 3002:
+ print(
+ f"FAIL: Okta alert should map to OCSF class_uid=3002 (Authentication), "
+ f"got {ocsf_frame['class_uid']}"
+ )
+ return 1
+
+ # 5. T1078 came through. The corpus may or may not be loaded in this
+ # bare-process smoke — we accept `found=False` but the ID and a
+ # valid attack.mitre.org URL must be present.
+ mitre_frames = [f for f in frames if f["kind"] == "mitre"]
+ if not any(f["id"] == "T1078" for f in mitre_frames):
+ print(f"FAIL: expected MITRE T1078 card, got {[f['id'] for f in mitre_frames]}")
+ return 1
+ for m in mitre_frames:
+ if not m["url"].startswith("https://attack.mitre.org/techniques/"):
+ print(f"FAIL: MITRE frame {m['id']} has bad url {m['url']!r}")
+ return 1
+
+ # 6. ATO tags should produce the ATO containment playbook recommendation.
+ next_frames = [f for f in frames if f["kind"] == "next_step"]
+ if not any(
+ f["playbook_id"] == "ato-impossible-travel-block-v1" for f in next_frames
+ ):
+ print(
+ "FAIL: ATO-tagged alert should recommend "
+ "'ato-impossible-travel-block-v1' playbook; got "
+ f"{[f['playbook_id'] for f in next_frames]}"
+ )
+ return 1
+
+ # 7. Evidence must contain the user from rawEvent.
+ evidence = [f for f in frames if f["kind"] == "evidence"]
+ if not any("alice.tan" in f["value"] for f in evidence):
+ print(
+ "FAIL: evidence missing the user from rawEvent: "
+ f"{[(f['label'], f['value']) for f in evidence]}"
+ )
+ return 1
+
+ print()
+ print(f"PASS: {len(frames)} frames, sections={section_ids}, "
+ f"mitre={[m['id'] for m in mitre_frames]}, "
+ f"playbooks={[n['playbook_id'] for n in next_frames]}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(asyncio.run(_run()))