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(alerts,fusion): InvestigationRail on /alerts + correlation narrative (PR-4 / v1.5 W6) (#106)

Beenu Aroraca66869f9bb9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b2c3975e6..475be41fa 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -138,6 +138,16 @@ jobs:
# `python scripts/sync_vendored_nl_query.py` locally to fix.
- name: Verify vendored nl_query is in sync
run: python scripts/sync_vendored_nl_query.py --check
+ # Same story for the correlation-narrative builder. It lives canonically
+ # in `services/fusion/app/services/narrative.py` (called at fusion time
+ # to populate `FusedAlert.narrative`) and is mirrored into
+ # `services/api/app/_vendor/narrative.py` so the API can lazily compute
+ # the narrative on first read of an alert whose `narrative` column is
+ # still NULL — without depending on `services/fusion` being inside the
+ # Docker build context. Re-run `python scripts/sync_vendored_narrative.py`
+ # locally if this check fails.
+ - name: Verify vendored narrative builder is in sync
+ run: python scripts/sync_vendored_narrative.py --check
python-test:
name: Python — Tests
diff --git a/apps/docs/docs/console/investigation-rail.md b/apps/docs/docs/console/investigation-rail.md
new file mode 100644
index 000000000..457869ce4
--- /dev/null
+++ b/apps/docs/docs/console/investigation-rail.md
@@ -0,0 +1,175 @@
+---
+sidebar_position: 2
+title: Investigation Rail on /alerts
+description: How AiSOC turns the legacy alert detail drawer into a structured triage rail — narrative, related entities, mini-timeline, and recommended actions — served by GET /api/v1/alerts/{id} and rendered to the right of the queue.
+---
+
+# Investigation Rail on `/alerts`
+
+Tier-1 analysts spend most of their day on the alert queue. The thing they reach for first is not a chart; it is *context*. v1.5 reshapes `/alerts` into a two-pane workbench: the queue on the left, an **Investigation Rail** on the right. Selecting a row hydrates the rail in place — no drawer, no page hop — and the same row's "Deep Explain" button still opens the existing LLM walkthrough on demand.
+
+This page documents the rail, the four sections it renders, and the API envelope it consumes.
+
+## Where the rail sits
+
+```
+┌────────────────────────────────────────────┬──────────────────────────────┐
+│ Alerts queue │ Investigation Rail │
+│ ───────────────────────────────────────── │ ─────────────────────────── │
+│ ● ALERT-7341 Impossible travel │ Impossible travel — Okta │
+│ ● ALERT-7340 Suspicious OAuth grant →│ Severity: high · Risk 87 │
+│ ● ALERT-7339 AWS S3 mass-download │ │
+│ ● ALERT-7338 Defender — credential dump │ Narrative │
+│ ● ALERT-7337 GitHub PAT exfil │ Related entities │
+│ │ Mini-timeline │
+│ │ Recommended actions │
+└────────────────────────────────────────────┴──────────────────────────────┘
+```
+
+The queue is unchanged for analysts who already memorised v1.4 muscle memory: column order, filters, saved views, and the bulk-acknowledge bar still behave the way they always did. The right pane appears the first time you click a row and stays in place until you press **Close investigation rail** or unmount the page.
+
+## The four rail sections
+
+### 1. Narrative — *why* this alert was promoted
+
+Every alert that comes through fusion now carries a short, deterministic narrative explaining the correlation that promoted it. The narrative is generated once at fusion time, cached on the alert row, and rendered verbatim in the rail. There is no LLM call on the read path — the same text is identical for every analyst who opens the alert.
+
+For alerts created before v1.5, the API lazily back-fills the narrative on the first read: `GET /api/v1/alerts/{id}` projects the row into `NarrativeInputs`, generates the text via the shared narrative builder, and persists the result so subsequent reads are cheap. Analysts never see a blank panel.
+
+The narrative is the *first* thing the analyst reads. It answers four questions a Tier-1 needs in under five seconds:
+
+- *Which detection or detections fired?*
+- *What did fusion match on?* (principal, host, indicator, MITRE technique)
+- *How much weight did each factor carry?*
+- *What does fusion say the next move is?*
+
+### 2. Related entities — pivots, not paragraphs
+
+The rail groups related entities into four buckets so the analyst can scan them at a glance:
+
+| Group | Examples |
+|---|---|
+| Principal | user accounts, service principals, IAM roles |
+| Network | source IPs, destination IPs, hostnames, ASNs |
+| Workflow | case ID, playbook run ID, ticket key |
+| Tenant | tenant slug, business unit, environment tag |
+
+Each entry has a `kind`, a `value`, an optional `displayLabel` (for example `[email protected] (Okta)`), and — most importantly — an optional `pivotPath`. When present, the rail renders the row as a `next/link`: clicking it sends the analyst straight to `AttackGraphView` or the corresponding workbench, with the entity prefocused. The whole point of this section is to make the queue a launchpad: every entity is a *verb*, not a label.
+
+The grouping is computed server-side in `services/api/app/services/alert_rail.py` so the frontend never has to re-sort the list, and so two analysts looking at the same alert see exactly the same buckets in the same order.
+
+### 3. Mini-timeline — the last six things that happened
+
+The rail surfaces the six most recent events for the alert's case, drawn from two sources that already exist in the platform:
+
+- **`CaseTimeline`** — analyst comments, status transitions, playbook checkpoints, attached evidence.
+- **`AuditLog`** — auth events, RBAC changes, and system actions that touched the alert or its case.
+
+The two streams are merged, deduplicated, ordered newest-first, and capped at six. Each event renders with a kind badge (`comment`, `status`, `evidence`, `auth`, `playbook`, `system`), a title, an actor if one is recorded, and a relative timestamp. Malformed timestamps fall through gracefully — the badge still renders so the analyst sees the event count is right even if a single event lost its clock.
+
+The point of the mini-timeline is to answer "what did someone else already do here?" without forcing the analyst to open the full case page. If something interesting happened in the last hour, it shows up on the rail.
+
+### 4. Recommended actions — the responder's structured guidance
+
+ResponderAgent already emits structured `recommended_actions` for v1.4 cases. The rail surfaces them verbatim:
+
+```json
+{
+ "priority": "critical",
+ "action": "Isolate the host via EDR",
+ "rationale": "Defender flagged credential-dump tooling and the same host appears in a GitHub PAT exfil alert from 11 minutes ago.",
+ "risk": "Isolation will sever active RDP sessions on this host."
+}
+```
+
+The rail normalises both modern (`{priority, action, rationale, risk}`) and legacy (list-of-strings) payloads so older alerts still render uniformly. Each card carries a priority chip (`critical | high | medium | low | info`), the action title, the rationale, and the risk callout. If a payload omits `priority`, the rail falls back to `medium` so the chip is always rendered — there is no empty state inside a populated card.
+
+The rail does *not* execute actions. The "Run this action" affordance lives on the case page; the rail's job is to make sure the analyst sees the recommendation *before* they spend ten minutes investigating a dead end.
+
+## The API envelope
+
+The rail is served by a single endpoint:
+
+```
+GET /api/v1/alerts/{alert_id}
+```
+
+The response is the `AlertDetailResponse` Pydantic contract:
+
+```jsonc
+{
+ // ─── existing AlertResponse fields ──────────────────────────────
+ "id": "ALERT-7341",
+ "title": "Impossible travel — Okta",
+ "severity": "high",
+ "status": "new",
+ "risk_score": 87,
+ "source": "okta",
+ "ai_confidence": 0.82,
+ "ai_recommendations": [ /* ... */ ],
+
+ // ─── rail envelope (added in v1.5) ─────────────────────────────
+ "narrative": "Fusion linked an Okta impossible-travel signal …",
+ "related_entities": [
+ { "kind": "principal", "value": "[email protected]",
+ "display_label": "[email protected] (Okta)",
+ "pivot_path": "/graph?focus=user:analyst%40aisoc.dev" },
+ { "kind": "network", "value": "203.0.113.42",
+ "pivot_path": "/graph?focus=ip:203.0.113.42" }
+ ],
+ "mini_timeline": [
+ { "id": "evt-1", "kind": "comment", "title": "Initial triage",
+ "actor": "[email protected]", "occurred_at": "2026-05-13T08:31:00Z" }
+ ],
+ "recommended_actions": [
+ { "priority": "critical",
+ "action": "Isolate the host via EDR",
+ "rationale": "Credential-dump tooling on the same host.",
+ "risk": "Active RDP sessions will be severed." }
+ ]
+}
+```
+
+Older clients (the v1.4 detail drawer, third-party MCP integrations) keep working because every rail field is optional. If the rail receives an envelope without a `narrative` or with an empty `related_entities`, the corresponding section is omitted from the panel entirely — the rail never shows an empty "Mini-timeline" header above zero events.
+
+### Lazy back-fill
+
+For pre-v1.5 alerts, `narrative` is `null` on disk. The endpoint:
+
+1. Projects the alert into `NarrativeInputs` (`services/api/app/services/narrative_projection.py`).
+2. Calls the vendored narrative builder (`services/api/app/_vendor/narrative.py`).
+3. Persists the resulting text on the alert row.
+4. Returns the populated `AlertDetailResponse`.
+
+This back-fill is best-effort and idempotent. If projection fails (for example, the alert was written by a connector that does not populate `correlated_indicators`), the response simply omits `narrative` and the rail hides the section. The endpoint never raises a 5xx because the narrative could not be generated.
+
+## Permissions and tenancy
+
+The endpoint is gated by the existing `alerts:read` permission and runs under a tenant-scoped DB session, so the rail respects every RLS policy that already applies to the queue. Analysts only ever see related entities, timeline events, and recommended actions for alerts they are authorised to read in the first place.
+
+## Deep Explain is still one click away
+
+The rail is deterministic and cheap by design — there is no LLM call on the read path. For the rich, LLM-driven walkthrough analysts already know from v1.4, every rail header carries a **Deep Explain** button. It opens the same `ExplainDrawer` the queue used to open inline, with the same prompt and the same model contract. The rail does not replace Deep Explain; it makes it opt-in.
+
+## What this replaces
+
+| Before (v1.4) | After (v1.5) |
+|---|---|
+| Click a row → drawer slides over the queue, hides the next ten alerts | Click a row → rail hydrates beside the queue, queue stays visible |
+| Drawer shows free-form LLM narrative as the *primary* affordance | Rail shows deterministic narrative + structured entities; LLM is one click away |
+| Mini-timeline lived in a separate `/cases/{id}` page | Last six events render inline on the rail |
+| Recommended actions were a `<ul>` of strings on the drawer footer | Cards with priority chip, action, rationale, and risk callout |
+| `GET /api/v1/alerts/{id}` returned `AlertResponse` | `GET /api/v1/alerts/{id}` returns `AlertDetailResponse` (superset; fully backwards-compatible) |
+
+## Source layout
+
+- **Frontend rail** — `apps/web/src/components/alerts/InvestigationRail.tsx`
+- **Two-pane queue** — `apps/web/src/components/alerts/AlertsView.tsx`
+- **API envelope** — `services/api/app/api/v1/endpoints/alerts.py`
+- **Rail builder** — `services/api/app/services/alert_rail.py`
+- **Narrative projection** — `services/api/app/services/narrative_projection.py`
+- **Vendored narrative** — `services/api/app/_vendor/narrative.py`
+
+## Author
+
+Beenu Arora · `[email protected]`
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index e2d5c20a0..9bb27b516 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -30,7 +30,12 @@ const sidebars: SidebarsConfig = {
{
type: "category",
label: "Console",
- items: ["console/funnel-kpis", "console/queue", "console/rule-tuning"],
+ items: [
+ "console/funnel-kpis",
+ "console/queue",
+ "console/rule-tuning",
+ "console/investigation-rail",
+ ],
},
{
type: "category",
diff --git a/apps/web/src/components/alerts/AlertsView.tsx b/apps/web/src/components/alerts/AlertsView.tsx
index 9c9e1f481..fe2f90b81 100644
--- a/apps/web/src/components/alerts/AlertsView.tsx
+++ b/apps/web/src/components/alerts/AlertsView.tsx
@@ -7,7 +7,7 @@ import { alertsApi, type Alert, type AlertFilters, type ConfidenceLabel } from '
import { clsx } from 'clsx';
import { formatDistanceToNow } from 'date-fns';
import { EntityRiskQueue } from './EntityRiskQueue';
-import { ExplainDrawer } from './ExplainDrawer';
+import { InvestigationRail } from './InvestigationRail';
import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
import { ErrorState } from '@/components/ui/ErrorState';
import { SavedViewsBar } from '@/components/saved-views/SavedViewsBar';
@@ -17,6 +17,14 @@ import { SavedViewsBar } from '@/components/saved-views/SavedViewsBar';
// points to the entities they touch, and the queue surfaces those entities
// (not the raw alerts) to the analyst. The "alerts" tab keeps the legacy
// alert-centric grid for tenants that prefer it or have RBA disabled.
+//
+// v1.5 W6 — The alerts tab is now a two-pane layout: the dense grid on the
+// left, an Investigation Rail on the right. Selecting a row populates the
+// rail with the deterministic narrative + related entities + recent events +
+// recommended actions envelope from `GET /alerts/{id}`. The legacy
+// `ExplainDrawer` is no longer mounted from this view directly; it has been
+// demoted to a "Deep Explain" button inside the rail itself, so analysts
+// only burn an LLM call when they explicitly ask for it.
type ViewMode = 'entities' | 'alerts';
// ─── Config ───────────────────────────────────────────────────────────────────
@@ -177,14 +185,39 @@ function FiltersBar({
);
}
-// WS-D1 — AlertRow accepts an onExplain callback so the Explain button can open
-// the SSE-streaming side drawer without navigating away. The button uses
-// e.preventDefault() + e.stopPropagation() to suppress the parent <Link>.
-function AlertRow({ alert, onExplain }: { alert: Alert; onExplain: (a: Alert) => void }) {
+// v1.5 W6 — AlertRow is now a *selection* affordance. Plain click selects the
+// row (which populates the Investigation Rail to the right); modifier-clicks
+// or middle-clicks still navigate to the full detail page so we don't break
+// "open in new tab" muscle memory. The row gets a left-border highlight
+// when selected so the analyst can see at a glance which alert the rail is
+// describing.
+function AlertRow({
+ alert,
+ selected,
+ onSelect,
+}: {
+ alert: Alert;
+ selected: boolean;
+ onSelect: (id: string) => void;
+}) {
return (
<Link
href={`/alerts/${alert.id}`}
- className="flex items-center gap-4 px-4 py-3 hover:bg-gray-800/20 transition-colors border-b border-gray-800/40 last:border-0"
+ onClick={(e) => {
+ // Modifier or middle-click → keep the native Link behaviour so
+ // analysts can open the alert in a new tab/window. Only a plain
+ // left-click is hijacked for in-pane selection.
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button === 1) return;
+ e.preventDefault();
+ onSelect(alert.id);
+ }}
+ aria-current={selected ? 'true' : undefined}
+ className={clsx(
+ 'flex items-center gap-4 px-4 py-3 transition-colors border-b border-gray-800/40 last:border-0 border-l-2',
+ selected
+ ? 'border-l-blue-500 bg-blue-500/5 hover:bg-blue-500/10'
+ : 'border-l-transparent hover:bg-gray-800/20',
+ )}
>
<SeverityDot severity={alert.severity} />
@@ -209,20 +242,6 @@ function AlertRow({ alert, onExplain }: { alert: Alert; onExplain: (a: Alert) =>
</div>
<div className="flex items-center gap-2 shrink-0">
- {/* WS-D1: Explain button — opens SSE-streaming side drawer */}
- <button
- type="button"
- aria-label="AI explain this alert"
- title="AI Explain"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onExplain(alert);
- }}
- className="text-[10px] font-medium px-2 py-0.5 rounded border border-violet-500/30 bg-violet-500/10 text-violet-400 hover:bg-violet-500/20 hover:border-violet-500/50 transition-colors shrink-0"
- >
- ✦ Explain
- </button>
{alert.confidenceLabel && <ConfidencePill label={alert.confidenceLabel} />}
<SeverityBadge severity={alert.severity} />
<StatusBadge status={alert.status} />
@@ -242,8 +261,6 @@ export function AlertsView() {
// RBA work. Analysts can flip back to the raw alert grid for legacy
// workflows or when triaging a specific alert ID.
const [viewMode, setViewMode] = useState<ViewMode>('entities');
- // WS-D1 — controls the SSE-streaming Explain side drawer.
- const [explainAlert, setExplainAlert] = useState<Alert | null>(null);
const { data, error, isLoading } = useSWR(
['alerts', filters],
@@ -345,18 +362,6 @@ export function AlertsView() {
isLoading={isLoading}
error={error}
onFilterChange={handleFilterChange}
- onExplain={setExplainAlert}
- />
- )}
-
- {/* WS-D1 — SSE-streaming AI explain side drawer.
- We always mount the drawer (open controls CSS visibility) so the
- closing animation can finish before the alert ref is cleared. */}
- {explainAlert && (
- <ExplainDrawer
- open={true}
- alert={explainAlert}
- onClose={() => setExplainAlert(null)}
/>
)}
</div>
@@ -375,7 +380,6 @@ function AlertsTable({
isLoading,
error,
onFilterChange,
- onExplain,
}: {
alerts: Alert[];
total: number;
@@ -386,11 +390,16 @@ function AlertsTable({
isLoading: boolean;
error: unknown;
onFilterChange: (f: AlertFilters) => void;
- onExplain: (a: Alert) => void;
}) {
+ // v1.5 W6 — Selection lives at the AlertsTable level (not AlertsView)
+ // because the rail is only rendered inside the "alerts" view mode.
+ // Switching to the entities tab unmounts this state cleanly, which is
+ // what we want — the rail is alert-scoped, not entity-scoped.
+ const [selectedAlertId, setSelectedAlertId] = useState<string | null>(null);
+
return (
<div className="space-y-4">
- {/* Stats strip */}
+ {/* Stats strip (full width) */}
<div className="grid grid-cols-4 gap-3">
{[
{ label: 'Total', value: total, color: 'text-gray-200' },
@@ -425,85 +434,159 @@ function AlertsTable({
<FiltersBar filters={filters} onChange={onFilterChange} total={total} />
- {/* Table */}
- <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl overflow-hidden">
- <div className="flex items-center px-4 py-2 border-b border-gray-800/60 bg-gray-900/80">
- <span className="text-xs text-gray-500 flex-1">ALERT</span>
- <span className="text-xs text-gray-500 w-20">SEVERITY</span>
- <span className="text-xs text-gray-500 w-24">STATUS</span>
- <span className="text-xs text-gray-500 w-24 text-right">TIME</span>
+ {/*
+ v1.5 W6 — two-pane layout. On wide screens the queue takes the left
+ seven cols and the Investigation Rail takes the right five; on narrow
+ screens they stack so the rail sits beneath the queue rather than
+ squeezing the columns into illegibility. The rail is `sticky` so it
+ stays in view while the analyst scrolls the queue.
+ */}
+ <div className="grid grid-cols-1 xl:grid-cols-12 gap-4">
+ <div className="xl:col-span-7 space-y-4">
+ <AlertsTableGrid
+ alerts={alerts}
+ isLoading={isLoading}
+ error={error}
+ filters={filters}
+ selectedAlertId={selectedAlertId}
+ onSelect={setSelectedAlertId}
+ onFilterChange={onFilterChange}
+ />
+ <AlertsPagination
+ alerts={alerts}
+ total={total}
+ filters={filters}
+ onFilterChange={onFilterChange}
+ />
</div>
-
- {isLoading ? (
- <div className="flex items-center justify-center h-32">
- <div className="w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
- </div>
- ) : error ? (
- <div className="p-4">
- <ErrorState
- title="Couldn't load alerts"
- description="The alerts feed didn't respond. Check the API service or try again."
- error={error}
+ <div className="xl:col-span-5">
+ <div className="xl:sticky xl:top-4 xl:max-h-[calc(100vh-7rem)] xl:overflow-hidden xl:flex xl:flex-col">
+ <InvestigationRail
+ alertId={selectedAlertId}
+ onClose={() => setSelectedAlertId(null)}
/>
</div>
- ) : alerts.length === 0 ? (
- <div className="p-4">
- {/*
- WS-F5 — distinguish "no data at all" from "filtered out". The
- filter-aware copy is the difference between an analyst thinking
- "the system is broken" and "I should clear my filters".
- */}
- {filters.severity || filters.status ? (
- <EmptyState
- icon={EmptyStateIcons.search}
- title="No alerts match these filters"
- description="Try clearing the severity or status filter to widen the search."
- action={
- <button
- onClick={() => onFilterChange({ page: 1, pageSize: filters.pageSize ?? 25 })}
- className="text-xs px-3 py-1.5 rounded-md border border-blue-500/40 bg-blue-500/10 text-blue-300 hover:bg-blue-500/20 transition-colors"
- >
- Clear filters
- </button>
- }
- />
- ) : (
- <EmptyState
- icon={EmptyStateIcons.alert}
- title="No alerts yet"
- description="Once a connector ingests events that trip a detection, alerts will appear here. Connect a data source from Settings → Connectors to start streaming."
- />
- )}
- </div>
- ) : (
- <div>
- {alerts.map((alert) => (
- <AlertRow key={alert.id} alert={alert} onExplain={onExplain} />
- ))}
- </div>
- )}
+ </div>
</div>
+ </div>
+ );
+}
- {/* Pagination */}
- <div className="flex items-center justify-between text-xs text-gray-500">
- <span>Showing {alerts.length} of {total} alerts</span>
- <div className="flex items-center gap-1">
- <button
- onClick={() => onFilterChange({ ...filters, page: Math.max(1, (filters.page || 1) - 1) })}
- disabled={(filters.page || 1) <= 1}
- className="px-2 py-1 rounded bg-gray-800 hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed"
- >
- Prev
- </button>
- <span className="px-2">Page {filters.page || 1}</span>
- <button
- onClick={() => onFilterChange({ ...filters, page: (filters.page || 1) + 1 })}
- disabled={alerts.length < (filters.pageSize || 25)}
- className="px-2 py-1 rounded bg-gray-800 hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed"
- >
- Next
- </button>
+// ─── Queue grid (split out from AlertsTable so the two-pane shell stays lean) ─
+
+function AlertsTableGrid({
+ alerts,
+ isLoading,
+ error,
+ filters,
+ selectedAlertId,
+ onSelect,
+ onFilterChange,
+}: {
+ alerts: Alert[];
+ isLoading: boolean;
+ error: unknown;
+ filters: AlertFilters;
+ selectedAlertId: string | null;
+ onSelect: (id: string) => void;
+ onFilterChange: (f: AlertFilters) => void;
+}) {
+ return (
+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl overflow-hidden">
+ <div className="flex items-center px-4 py-2 border-b border-gray-800/60 bg-gray-900/80">
+ <span className="text-xs text-gray-500 flex-1 pl-2">ALERT</span>
+ <span className="text-xs text-gray-500 w-20">SEVERITY</span>
+ <span className="text-xs text-gray-500 w-24">STATUS</span>
+ <span className="text-xs text-gray-500 w-24 text-right">TIME</span>
+ </div>
+
+ {isLoading ? (
+ <div className="flex items-center justify-center h-32">
+ <div className="w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
+ </div>
+ ) : error ? (
+ <div className="p-4">
+ <ErrorState
+ title="Couldn't load alerts"
+ description="The alerts feed didn't respond. Check the API service or try again."
+ error={error}
+ />
+ </div>
+ ) : alerts.length === 0 ? (
+ <div className="p-4">
+ {/*
+ WS-F5 — distinguish "no data at all" from "filtered out". The
+ filter-aware copy is the difference between an analyst thinking
+ "the system is broken" and "I should clear my filters".
+ */}
+ {filters.severity || filters.status ? (
+ <EmptyState
+ icon={EmptyStateIcons.search}
+ title="No alerts match these filters"
+ description="Try clearing the severity or status filter to widen the search."
+ action={
+ <button
+ onClick={() => onFilterChange({ page: 1, pageSize: filters.pageSize ?? 25 })}
+ className="text-xs px-3 py-1.5 rounded-md border border-blue-500/40 bg-blue-500/10 text-blue-300 hover:bg-blue-500/20 transition-colors"
+ >
+ Clear filters
+ </button>
+ }
+ />
+ ) : (
+ <EmptyState
+ icon={EmptyStateIcons.alert}
+ title="No alerts yet"
+ description="Once a connector ingests events that trip a detection, alerts will appear here. Connect a data source from Settings → Connectors to start streaming."
+ />
+ )}
</div>
+ ) : (
+ <div>
+ {alerts.map((alert) => (
+ <AlertRow
+ key={alert.id}
+ alert={alert}
+ selected={selectedAlertId === alert.id}
+ onSelect={onSelect}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function AlertsPagination({
+ alerts,
+ total,
+ filters,
+ onFilterChange,
+}: {
+ alerts: Alert[];
+ total: number;
+ filters: AlertFilters;
+ onFilterChange: (f: AlertFilters) => void;
+}) {
+ return (
+ <div className="flex items-center justify-between text-xs text-gray-500">
+ <span>Showing {alerts.length} of {total} alerts</span>
+ <div className="flex items-center gap-1">
+ <button
+ onClick={() => onFilterChange({ ...filters, page: Math.max(1, (filters.page || 1) - 1) })}
+ disabled={(filters.page || 1) <= 1}
+ className="px-2 py-1 rounded bg-gray-800 hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ Prev
+ </button>
+ <span className="px-2">Page {filters.page || 1}</span>
+ <button
+ onClick={() => onFilterChange({ ...filters, page: (filters.page || 1) + 1 })}
+ disabled={alerts.length < (filters.pageSize || 25)}
+ className="px-2 py-1 rounded bg-gray-800 hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ Next
+ </button>
</div>
</div>
);
diff --git a/apps/web/src/components/alerts/InvestigationRail.test.tsx b/apps/web/src/components/alerts/InvestigationRail.test.tsx
new file mode 100644
index 000000000..a615e71ef
--- /dev/null
+++ b/apps/web/src/components/alerts/InvestigationRail.test.tsx
@@ -0,0 +1,711 @@
+// W6 — pin the InvestigationRail contract for the v1.5 SOC console parity.
+//
+// The rail is the structured triage panel that lives to the right of the
+// `/alerts` grid. It is a thin presentation layer on top of the envelope
+// returned by `GET /api/v1/alerts/{id}` and it owns five behaviors the
+// analyst experience depends on:
+//
+// 1. Empty state — when no row is selected, render the placeholder with
+// a hint instead of a blank panel or a skeleton.
+// 2. Loading state — show a skeleton while SWR resolves the envelope so
+// the rail doesn't flash empty.
+// 3. Error state — surface a readable message when the API call fails,
+// without crashing the queue on the left.
+// 4. Section gating — render `Narrative`, `Related entities`, `Recent
+// events`, and `Recommended actions` only when their data is present,
+// and group related entities in the canonical order even if the API
+// hands them back out of order.
+// 5. Deep Explain handoff — the `✦ Deep Explain` button is the *only*
+// affordance that opens the ExplainDrawer; mounting the drawer from
+// inside the rail (rather than from `AlertsView`) gives us one
+// well-known entry point and lets the drawer close cleanly when the
+// analyst dismisses it.
+//
+// SWR is mocked at the module boundary so each test can pin the loading /
+// error / data state without touching the network. The `ExplainDrawer` is
+// also mocked so we can assert the rail opens / closes it without dragging
+// in the LLM streaming machinery — that surface has its own deep tests in
+// `ExplainDrawer.test.tsx`.
+//
+// Author: Beenu Arora <[email protected]>
+
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+// ─── Mocks ───────────────────────────────────────────────────────────────────
+
+// SWR — we control `data` / `error` / `isLoading` per-test by mutating the
+// hoisted state. Mirrors the pattern used in `FunnelKpiBar.test.tsx`.
+const swrState = vi.hoisted(() => ({
+ data: undefined as unknown,
+ error: undefined as unknown,
+ isLoading: false,
+}));
+
+vi.mock('swr', () => ({
+ __esModule: true,
+ default: () => ({
+ data: swrState.data,
+ error: swrState.error,
+ isLoading: swrState.isLoading,
+ }),
+}));
+
+// next/link — render as an anchor so we can assert `href` without pulling
+// the App Router into jsdom.
+vi.mock('next/link', () => ({
+ __esModule: true,
+ default: ({
+ href,
+ children,
+ ...rest
+ }: {
+ href: string;
+ children: React.ReactNode;
+ } & React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
+ <a href={typeof href === 'string' ? href : '#'} {...rest}>
+ {children}
+ </a>
+ ),
+}));
+
+// ExplainDrawer — the rail is the only thing under test here; we use a
+// minimal mock so we can prove the rail opens the drawer with the right
+// alert and closes it via the `onClose` callback. The real drawer is
+// covered exhaustively in `ExplainDrawer.test.tsx`.
+const explainDrawerProps = vi.hoisted(() => ({
+ lastProps: null as null | {
+ open: boolean;
+ alertId: string;
+ onClose: () => void;
+ },
+}));
+
+vi.mock('./ExplainDrawer', () => ({
+ __esModule: true,
+ ExplainDrawer: (props: {
+ open: boolean;
+ alert: { id: string };
+ onClose: () => void;
+ }) => {
+ explainDrawerProps.lastProps = {
+ open: props.open,
+ alertId: props.alert.id,
+ onClose: props.onClose,
+ };
+ return (
+ <div data-testid="explain-drawer-mock">
+ <span data-testid="explain-drawer-alert-id">{props.alert.id}</span>
+ <button
+ type="button"
+ onClick={props.onClose}
+ data-testid="explain-drawer-close"
+ >
+ mock-close
+ </button>
+ </div>
+ );
+ },
+}));
+
+// Import AFTER the mocks so the component picks up the stubs.
+import { InvestigationRail } from './InvestigationRail';
+import type {
+ Alert,
+ RelatedEntity,
+ MiniTimelineEvent,
+ RecommendedAction,
+} from '@/lib/api';
+
+// ─── Fixtures ────────────────────────────────────────────────────────────────
+
+const RELATED_ENTITIES: RelatedEntity[] = [
+ {
+ kind: 'principal',
+ type: 'user',
+ value: '[email protected]',
+ label: 'Alice (Finance)',
+ pivotPath: '/graph/user/alice%40example.com',
+ },
+ {
+ kind: 'principal',
+ type: 'host',
+ value: 'fin-laptop-12',
+ },
+ {
+ kind: 'network',
+ type: 'ip',
+ value: '10.0.0.7',
+ pivotPath: '/graph/ip/10.0.0.7',
+ },
+ {
+ kind: 'workflow',
+ type: 'rule',
+ value: 'impossible-travel',
+ label: 'Impossible Travel',
+ },
+ {
+ kind: 'tenant',
+ type: 'tenant',
+ value: 'acme-corp',
+ },
+];
+
+const MINI_TIMELINE: MiniTimelineEvent[] = [
+ {
+ id: 'evt-1',
+ timestamp: '2026-05-13T09:55:00Z',
+ type: 'alert_promoted',
+ title: 'Alert promoted by fusion',
+ description: 'Correlation score crossed threshold',
+ actor: 'fusion-engine',
+ source: 'case_timeline',
+ },
+ {
+ id: 'evt-2',
+ timestamp: '2026-05-13T09:50:00Z',
+ type: 'case_assigned',
+ title: 'Case assigned to analyst',
+ actor: '[email protected]',
+ source: 'audit_log',
+ },
+];
+
+// Priorities chosen so they never collide with the severity text in the
+// header — severity is 'high', so we exercise {critical, low, info}. The
+// component still walks the full PRIORITY_TONE table, so coverage is the
+// same as testing {critical, high, medium}.
+const RECOMMENDED_ACTIONS: RecommendedAction[] = [
+ {
+ priority: 'critical',
+ action: 'Disable the account immediately',
+ rationale: 'Impossible travel confirmed across two regions',
+ risk: 'Locking the account temporarily disrupts the user',
+ },
+ {
+ priority: 'low',
+ action: 'Reset password and revoke active sessions',
+ },
+ {
+ priority: 'info',
+ action: 'Open a P2 ticket with the IAM team',
+ rationale: 'Track follow-up SSO config review',
+ },
+];
+
+// Build a full Alert that satisfies the type. The rail only reads a subset
+// of the fields, but the type signature requires more, so we set sensible
+// defaults and let callers override.
+function buildAlert(overrides: Partial<Alert> = {}): Alert {
+ const base: Alert = {
+ id: 'ALERT-W6-0001',
+ title: 'Impossible travel — Frankfurt then Tokyo',
+ description: 'Account takeover suspected based on geo signals.',
+ severity: 'high',
+ status: 'new',
+ source: 'okta',
+ tenantId: 'tenant-acme',
+ riskScore: 87,
+ mitreAttack: [],
+ iocs: [],
+ tags: ['account-takeover'],
+ createdAt: '2026-05-13T09:00:00Z',
+ updatedAt: '2026-05-13T09:00:00Z',
+ narrative:
+ 'Fusion promoted this alert because two sign-ins from non-adjacent regions\nlanded within 12 minutes of each other.',
+ relatedEntities: RELATED_ENTITIES,
+ miniTimeline: MINI_TIMELINE,
+ recommendedActions: RECOMMENDED_ACTIONS,
+ };
+ return { ...base, ...overrides };
+}
+
+// ─── Reset hoisted state between tests ───────────────────────────────────────
+
+beforeEach(() => {
+ swrState.data = undefined;
+ swrState.error = undefined;
+ swrState.isLoading = false;
+ explainDrawerProps.lastProps = null;
+});
+
+// ─── Empty state ─────────────────────────────────────────────────────────────
+
+describe('InvestigationRail — empty state', () => {
+ it('renders the placeholder when no alert is selected', () => {
+ render(<InvestigationRail alertId={null} onClose={vi.fn()} />);
+ expect(
+ screen.getByLabelText('Investigation rail (no alert selected)'),
+ ).toBeInTheDocument();
+ expect(screen.getByText(/select an alert to investigate/i)).toBeVisible();
+ // The shell-with-Close button only renders when an alert is selected; the
+ // placeholder is deliberately non-dismissible.
+ expect(screen.queryByLabelText('Close investigation rail')).toBeNull();
+ });
+
+ it('does not call onClose from the placeholder', () => {
+ const onClose = vi.fn();
+ render(<InvestigationRail alertId={null} onClose={onClose} />);
+ // No close button exists in the placeholder — but make sure nothing
+ // implicitly fires onClose on mount either.
+ expect(onClose).not.toHaveBeenCalled();
+ });
+});
+
+// ─── Loading state ───────────────────────────────────────────────────────────
+
+describe('InvestigationRail — loading state', () => {
+ it('renders the skeleton while SWR is loading', () => {
+ swrState.isLoading = true;
+ render(<InvestigationRail alertId="ALERT-1" onClose={vi.fn()} />);
+ // The loading shell uses the "Loading…" title.
+ expect(screen.getByLabelText('Investigation rail')).toBeInTheDocument();
+ expect(screen.getByText('Loading…')).toBeInTheDocument();
+ });
+
+ it('still renders the skeleton when alert is undefined but no error', () => {
+ // SWR's initial state for some adapters: not loading, no data, no error.
+ // The component treats this as "still resolving" to avoid flashing the
+ // error panel.
+ swrState.isLoading = false;
+ swrState.data = undefined;
+ swrState.error = undefined;
+ render(<InvestigationRail alertId="ALERT-1" onClose={vi.fn()} />);
+ expect(screen.getByText('Loading…')).toBeInTheDocument();
+ });
+
+ it('close button in the loading shell calls onClose', async () => {
+ const user = userEvent.setup();
+ swrState.isLoading = true;
+ const onClose = vi.fn();
+ render(<InvestigationRail alertId="ALERT-1" onClose={onClose} />);
+ await user.click(screen.getByLabelText('Close investigation rail'));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+});
+
+// ─── Error state ─────────────────────────────────────────────────────────────
+
+describe('InvestigationRail — error state', () => {
+ it('renders a readable error message on API failure', () => {
+ swrState.error = new Error('boom');
+ render(<InvestigationRail alertId="ALERT-1" onClose={vi.fn()} />);
+ expect(
+ screen.getByText(/couldn't load the alert envelope/i),
+ ).toBeInTheDocument();
+ // The fallback shell still exposes the Close affordance — otherwise the
+ // analyst gets stuck looking at the error.
+ expect(
+ screen.getByLabelText('Close investigation rail'),
+ ).toBeInTheDocument();
+ });
+
+ it('error fallback close button is wired to onClose', async () => {
+ const user = userEvent.setup();
+ swrState.error = new Error('boom');
+ const onClose = vi.fn();
+ render(<InvestigationRail alertId="ALERT-1" onClose={onClose} />);
+ await user.click(screen.getByLabelText('Close investigation rail'));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+});
+
+// ─── Loaded rail — header ────────────────────────────────────────────────────
+
+describe('InvestigationRail — header', () => {
+ it('renders the alert title, severity, source, and risk', () => {
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+
+ expect(
+ screen.getByRole('heading', {
+ name: /impossible travel — frankfurt then tokyo/i,
+ }),
+ ).toBeInTheDocument();
+ // Severity 'high' is unique — the fixture priorities are {critical, low,
+ // info}, so 'high' appears exactly once (in the severity span).
+ expect(screen.getByText('high')).toBeInTheDocument();
+ expect(screen.getByText('okta')).toBeInTheDocument();
+ // Risk score is rounded — 87 stays 87, but the prefix is the contract.
+ expect(screen.getByText(/^risk 87$/)).toBeInTheDocument();
+ });
+
+ it('omits the risk chip when riskScore is missing', () => {
+ swrState.data = buildAlert({
+ // Cast to undefined deliberately — the Alert type says number, but the
+ // backend can omit it on legacy rows and the rail must not crash.
+ riskScore: undefined as unknown as number,
+ });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ // The lowercase 'risk ' (with trailing space) prefix only appears on the
+ // header chip; the "Risk:" line in recommended actions is capitalised and
+ // followed by a colon, so it can't collide with this matcher.
+ expect(screen.queryByText(/^risk /)).toBeNull();
+ });
+
+ it('renders the "Open full detail" link with the alert id', () => {
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ const link = screen.getByRole('link', { name: /open full detail/i });
+ expect(link).toHaveAttribute('href', '/alerts/ALERT-W6-0001');
+ });
+
+ it('renders the underscore-stripped status text', () => {
+ // 'false_positive' is the only multi-word AlertStatus literal — it
+ // exercises the `status.replace('_', ' ')` codepath.
+ swrState.data = buildAlert({ status: 'false_positive' });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ expect(screen.getByText('false positive')).toBeInTheDocument();
+ });
+});
+
+// ─── Loaded rail — narrative ─────────────────────────────────────────────────
+
+describe('InvestigationRail — narrative section', () => {
+ it('renders the narrative when present', () => {
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ expect(screen.getByText('Narrative')).toBeInTheDocument();
+ expect(
+ screen.getByText(/fusion promoted this alert because two sign-ins/i),
+ ).toBeInTheDocument();
+ });
+
+ it('omits the narrative section when narrative is null', () => {
+ swrState.data = buildAlert({ narrative: null });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ expect(screen.queryByText('Narrative')).toBeNull();
+ });
+
+ it('omits the narrative section when narrative is only whitespace', () => {
+ swrState.data = buildAlert({ narrative: ' \n ' });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ expect(screen.queryByText('Narrative')).toBeNull();
+ });
+});
+
+// ─── Loaded rail — related entities ──────────────────────────────────────────
+
+describe('InvestigationRail — related entities section', () => {
+ it('renders related entities grouped by kind with a count', () => {
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+
+ expect(screen.getByText(/related entities/i)).toBeInTheDocument();
+ // 5 entities total in the fixture.
+ expect(screen.getByText('(5)')).toBeInTheDocument();
+
+ // Each kind that has at least one entity renders its label exactly once.
+ expect(screen.getByText('Principals')).toBeInTheDocument();
+ expect(screen.getByText('Network')).toBeInTheDocument();
+ expect(screen.getByText('Workflow')).toBeInTheDocument();
+ expect(screen.getByText('Tenant')).toBeInTheDocument();
+ });
+
+ it('renders the principal chips with their display labels', () => {
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ // Display label wins over raw value when present.
+ expect(screen.getByText('Alice (Finance)')).toBeInTheDocument();
+ // No label → fall back to raw value.
+ expect(screen.getByText('fin-laptop-12')).toBeInTheDocument();
+ });
+
+ it('wraps entities with pivotPath in a link and leaves the rest as plain chips', () => {
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+
+ // The pivotable principal renders an anchor.
+ const aliceLink = screen.getByText('Alice (Finance)').closest('a');
+ expect(aliceLink).not.toBeNull();
+ expect(aliceLink).toHaveAttribute(
+ 'href',
+ '/graph/user/alice%40example.com',
+ );
+
+ // The non-pivotable host does NOT render an anchor — `closest('a')` should
+ // skip past the chip's outer span and find nothing.
+ const hostChip = screen.getByText('fin-laptop-12');
+ expect(hostChip.closest('a')).toBeNull();
+
+ // The network IP chip renders an anchor too.
+ const ipLink = screen.getByText('10.0.0.7').closest('a');
+ expect(ipLink).toHaveAttribute('href', '/graph/ip/10.0.0.7');
+ });
+
+ it('omits the section entirely when no related entities are returned', () => {
+ swrState.data = buildAlert({ relatedEntities: [] });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ expect(screen.queryByText(/related entities/i)).toBeNull();
+ });
+
+ it('re-groups entities defensively when the API returns them out of order', () => {
+ const shuffled: RelatedEntity[] = [
+ { kind: 'tenant', type: 'tenant', value: 'acme' },
+ { kind: 'principal', type: 'user', value: 'alice' },
+ { kind: 'network', type: 'ip', value: '10.0.0.1' },
+ { kind: 'principal', type: 'host', value: 'box-1' },
+ ];
+ swrState.data = buildAlert({ relatedEntities: shuffled });
+ const { container } = render(
+ <InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />,
+ );
+
+ // The three group headers present in the fixture appear; the workflow
+ // group is skipped because there are no workflow entities.
+ expect(screen.getByText('Principals')).toBeInTheDocument();
+ expect(screen.getByText('Network')).toBeInTheDocument();
+ expect(screen.getByText('Tenant')).toBeInTheDocument();
+ expect(screen.queryByText('Workflow')).toBeNull();
+
+ // Render order: Principals comes before Network comes before Tenant,
+ // independent of the input order.
+ const html = container.innerHTML;
+ const principalsIdx = html.indexOf('Principals');
+ const networkIdx = html.indexOf('Network');
+ const tenantIdx = html.indexOf('Tenant');
+ expect(principalsIdx).toBeGreaterThan(-1);
+ expect(networkIdx).toBeGreaterThan(principalsIdx);
+ expect(tenantIdx).toBeGreaterThan(networkIdx);
+ });
+});
+
+// ─── Loaded rail — mini timeline ─────────────────────────────────────────────
+
+describe('InvestigationRail — mini-timeline section', () => {
+ it('renders the mini-timeline rows with badges, titles, and actors', () => {
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+
+ expect(screen.getByText(/recent events/i)).toBeInTheDocument();
+ expect(screen.getByText('(2)')).toBeInTheDocument();
+
+ // Titles render.
+ expect(screen.getByText('Alert promoted by fusion')).toBeInTheDocument();
+ expect(screen.getByText('Case assigned to analyst')).toBeInTheDocument();
+
+ // Source badges — `case_timeline` collapses to "case", `audit_log` to "audit".
+ expect(screen.getByText('case')).toBeInTheDocument();
+ expect(screen.getByText('audit')).toBeInTheDocument();
+
+ // Actor lines render with the "by " prefix.
+ expect(screen.getByText('by fusion-engine')).toBeInTheDocument();
+ expect(screen.getByText('by [email protected]')).toBeInTheDocument();
+ });
+
+ it('renders the row without crashing when the timestamp is malformed', () => {
+ swrState.data = buildAlert({
+ miniTimeline: [
+ {
+ id: 'evt-bad',
+ timestamp: 'not-a-real-timestamp',
+ type: 'note_added',
+ title: 'Analyst added a note',
+ source: 'audit_log',
+ },
+ ],
+ });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ // The title still surfaces so the row isn't lost.
+ expect(screen.getByText('Analyst added a note')).toBeInTheDocument();
+ });
+
+ it('omits the section when there are no timeline events', () => {
+ swrState.data = buildAlert({ miniTimeline: [] });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ expect(screen.queryByText(/recent events/i)).toBeNull();
+ });
+});
+
+// ─── Loaded rail — recommended actions ───────────────────────────────────────
+
+describe('InvestigationRail — recommended actions section', () => {
+ it('renders recommended actions with priority chips, rationale, and risk', () => {
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+
+ expect(screen.getByText(/recommended actions/i)).toBeInTheDocument();
+ expect(screen.getByText('(3)')).toBeInTheDocument();
+
+ // Priorities render as their literal lowercase tag. With severity='high'
+ // and priorities {critical, low, info}, every priority text is unique in
+ // the document.
+ expect(screen.getByText('critical')).toBeInTheDocument();
+ expect(screen.getByText('low')).toBeInTheDocument();
+ expect(screen.getByText('info')).toBeInTheDocument();
+
+ // Action text renders.
+ expect(
+ screen.getByText('Disable the account immediately'),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText('Reset password and revoke active sessions'),
+ ).toBeInTheDocument();
+
+ // Rationale + risk only render when present.
+ expect(
+ screen.getByText(/impossible travel confirmed across two regions/i),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ /risk: locking the account temporarily disrupts the user/i,
+ ),
+ ).toBeInTheDocument();
+
+ // Action 1 (low) has no rationale; we should NOT see a stray "Risk:" line
+ // for it — only action 0 (critical) carries a risk field.
+ const risks = screen.queryAllByText(/^Risk:/);
+ expect(risks).toHaveLength(1);
+ });
+
+ it('falls back to the medium tone when priority is unrecognised', () => {
+ swrState.data = buildAlert({
+ recommendedActions: [
+ {
+ // Cast through unknown to simulate a stale backend handing us
+ // a priority outside the documented enum.
+ priority: 'urgent' as unknown as RecommendedAction['priority'],
+ action: 'Investigate quickly',
+ },
+ ],
+ });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ // The chip still renders with the raw priority text — the fallback is
+ // about the tone class, not about hiding the row.
+ expect(screen.getByText('urgent')).toBeInTheDocument();
+ expect(screen.getByText('Investigate quickly')).toBeInTheDocument();
+ });
+
+ it('omits the section when there are no recommended actions', () => {
+ swrState.data = buildAlert({ recommendedActions: [] });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ expect(screen.queryByText(/recommended actions/i)).toBeNull();
+ });
+});
+
+// ─── Deep Explain handoff ────────────────────────────────────────────────────
+
+describe('InvestigationRail — Deep Explain drawer', () => {
+ it('does not mount the drawer on initial render', () => {
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ expect(screen.queryByTestId('explain-drawer-mock')).toBeNull();
+ expect(explainDrawerProps.lastProps).toBeNull();
+ });
+
+ it('mounts the drawer with the loaded alert when Deep Explain is clicked', async () => {
+ const user = userEvent.setup();
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+
+ await user.click(screen.getByRole('button', { name: /deep explain/i }));
+
+ expect(screen.getByTestId('explain-drawer-mock')).toBeInTheDocument();
+ expect(explainDrawerProps.lastProps?.alertId).toBe('ALERT-W6-0001');
+ expect(explainDrawerProps.lastProps?.open).toBe(true);
+ });
+
+ it('closes the drawer when the drawer fires onClose', async () => {
+ const user = userEvent.setup();
+ swrState.data = buildAlert();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+
+ await user.click(screen.getByRole('button', { name: /deep explain/i }));
+ expect(screen.getByTestId('explain-drawer-mock')).toBeInTheDocument();
+
+ await user.click(screen.getByTestId('explain-drawer-close'));
+ expect(screen.queryByTestId('explain-drawer-mock')).toBeNull();
+ });
+
+ it('does NOT call the rail-level onClose when the drawer is closed', async () => {
+ // The rail's onClose is the queue-level "dismiss the rail" affordance.
+ // Closing the drawer must not bubble up into that.
+ const user = userEvent.setup();
+ swrState.data = buildAlert();
+ const onClose = vi.fn();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={onClose} />);
+
+ await user.click(screen.getByRole('button', { name: /deep explain/i }));
+ await user.click(screen.getByTestId('explain-drawer-close'));
+
+ expect(onClose).not.toHaveBeenCalled();
+ });
+});
+
+// ─── Rail-level Close button ─────────────────────────────────────────────────
+
+describe('InvestigationRail — rail close button', () => {
+ it('calls onClose when the analyst clicks Close on a loaded rail', async () => {
+ const user = userEvent.setup();
+ swrState.data = buildAlert();
+ const onClose = vi.fn();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={onClose} />);
+
+ // The shell exposes one Close affordance — the loaded rail uses the same
+ // aria-label as the loading shell, so we can target it the same way.
+ const closeBtn = screen.getByLabelText('Close investigation rail');
+ await user.click(closeBtn);
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the alert content visible until the parent unmounts the rail', () => {
+ // The rail itself doesn't toggle visibility on Close — it just fires
+ // onClose. The parent (AlertsView) controls mount/unmount. This test
+ // pins that contract so refactors don't accidentally short-circuit it.
+ swrState.data = buildAlert();
+ const onClose = vi.fn();
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={onClose} />);
+
+ expect(
+ screen.getByRole('heading', { name: /impossible travel/i }),
+ ).toBeInTheDocument();
+ });
+});
+
+// ─── Empty envelopes (legacy backend) ────────────────────────────────────────
+
+describe('InvestigationRail — degrades gracefully on legacy envelopes', () => {
+ it('renders the header but no section bodies when the rail fields are missing', () => {
+ // Pre-v1.5 backends won't carry any of the new rail fields. The
+ // component must still render — just with the header alone — rather
+ // than crashing or showing four empty sections.
+ swrState.data = buildAlert({
+ narrative: null,
+ relatedEntities: [],
+ miniTimeline: [],
+ recommendedActions: [],
+ });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+
+ // Header still renders.
+ expect(
+ screen.getByRole('heading', { name: /impossible travel/i }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', { name: /deep explain/i }),
+ ).toBeInTheDocument();
+
+ // None of the four section labels appear.
+ expect(screen.queryByText('Narrative')).toBeNull();
+ expect(screen.queryByText(/related entities/i)).toBeNull();
+ expect(screen.queryByText(/recent events/i)).toBeNull();
+ expect(screen.queryByText(/recommended actions/i)).toBeNull();
+ });
+
+ it('treats omitted rail fields the same as empty arrays', () => {
+ // Same as above but the fields are `undefined` instead of `[]` — the
+ // rail uses `??` so this is the explicit contract test.
+ swrState.data = buildAlert({
+ narrative: undefined,
+ relatedEntities: undefined,
+ miniTimeline: undefined,
+ recommendedActions: undefined,
+ });
+ render(<InvestigationRail alertId="ALERT-W6-0001" onClose={vi.fn()} />);
+ expect(screen.queryByText('Narrative')).toBeNull();
+ expect(screen.queryByText(/related entities/i)).toBeNull();
+ expect(screen.queryByText(/recent events/i)).toBeNull();
+ expect(screen.queryByText(/recommended actions/i)).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/alerts/InvestigationRail.tsx b/apps/web/src/components/alerts/InvestigationRail.tsx
new file mode 100644
index 000000000..d7ca168ff
--- /dev/null
+++ b/apps/web/src/components/alerts/InvestigationRail.tsx
@@ -0,0 +1,451 @@
+'use client';
+
+/**
+ * Investigation Rail (v1.5 W6 — SOC console parity).
+ *
+ * Structured triage panel rendered to the right of the `/alerts` grid
+ * whenever an analyst selects a row. The rail consumes the envelope
+ * served by `GET /api/v1/alerts/{id}` — which carries four sections
+ * the analyst needs at first glance:
+ *
+ * 1. Narrative — deterministic, Markdown-light explanation of *why*
+ * fusion promoted this alert. Cached on the row at fusion time and
+ * lazily back-filled by the API for legacy alerts so we never
+ * surface a blank panel.
+ * 2. Related entities — principal / network / workflow / tenant
+ * groupings. Entries with a `pivotPath` link straight into the
+ * AttackGraphView so analysts can hop from "10.0.0.7" to its
+ * neighbourhood in two clicks instead of switching pages.
+ * 3. Mini-timeline — the six most recent case-timeline + audit-log
+ * events for this alert's case, surfaced inline so the analyst
+ * doesn't have to leave the queue just to see what happened last.
+ * 4. Recommended actions — ResponderAgent's structured guidance,
+ * normalised server-side so legacy list-of-strings payloads and
+ * the modern `{priority, action, rationale, risk}` shape render
+ * uniformly.
+ *
+ * A single "Deep Explain" button at the top of the rail still opens the
+ * existing {@link ExplainDrawer} for the rich LLM-driven walkthrough —
+ * the rail itself is deterministic and cheap so we don't burn an LLM
+ * call every time the analyst clicks a row.
+ *
+ * Author: Beenu Arora <[email protected]>
+ */
+
+import Link from 'next/link';
+import { useState } from 'react';
+import useSWR from 'swr';
+import { clsx } from 'clsx';
+import { format, formatDistanceToNow } from 'date-fns';
+import {
+ alertsApi,
+ type Alert,
+ type MiniTimelineEvent,
+ type RecommendedAction,
+ type RelatedEntity,
+} from '@/lib/api';
+import { ExplainDrawer } from './ExplainDrawer';
+import { Skeleton } from '@/components/ui/Skeleton';
+
+// ─── Visual config ───────────────────────────────────────────────────────────
+
+/**
+ * Grouping config for {@link RelatedEntity.kind}.
+ *
+ * The order of these keys determines the render order inside the rail.
+ * "principal" goes first because that's the entity an analyst usually
+ * pivots on (who did it / who was hit). "tenant" is last because it's
+ * the broadest-context grouping.
+ */
+const ENTITY_KIND_CONFIG: Record<
+ RelatedEntity['kind'],
+ { label: string; tone: string }
+> = {
+ principal: { label: 'Principals', tone: 'text-blue-300' },
+ network: { label: 'Network', tone: 'text-cyan-300' },
+ workflow: { label: 'Workflow', tone: 'text-purple-300' },
+ tenant: { label: 'Tenant', tone: 'text-gray-300' },
+};
+
+/** Tone map for the priority chip on a recommended action. */
+const PRIORITY_TONE: Record<RecommendedAction['priority'], string> = {
+ critical: 'border-red-500/40 bg-red-500/10 text-red-300',
+ high: 'border-orange-500/40 bg-orange-500/10 text-orange-300',
+ medium: 'border-yellow-500/40 bg-yellow-500/10 text-yellow-300',
+ low: 'border-blue-500/40 bg-blue-500/10 text-blue-300',
+ info: 'border-gray-500/40 bg-gray-500/10 text-gray-300',
+};
+
+// ─── Props ───────────────────────────────────────────────────────────────────
+
+export interface InvestigationRailProps {
+ /** Selected alert id. When `null` the rail renders an empty-state hint. */
+ alertId: string | null;
+ /** Called when the analyst dismisses the rail (close button). */
+ onClose: () => void;
+}
+
+// ─── Main component ──────────────────────────────────────────────────────────
+
+export function InvestigationRail({ alertId, onClose }: InvestigationRailProps) {
+ // The drawer is mounted on demand and closed by default; we don't
+ // burn the LLM call until the analyst explicitly asks for it.
+ const [deepExplainOpen, setDeepExplainOpen] = useState(false);
+
+ const { data: alert, error, isLoading } = useSWR(
+ alertId ? (['alerts', alertId, 'rail'] as const) : null,
+ () => alertsApi.get(alertId as string),
+ {
+ // The rail is supposed to feel like a *snapshot* — the analyst
+ // explicitly opens it. We don't want noisy revalidates on tab
+ // focus throwing off their reading flow.
+ revalidateOnFocus: false,
+ shouldRetryOnError: false,
+ },
+ );
+
+ if (!alertId) {
+ return <RailPlaceholder />;
+ }
+
+ if (isLoading || (!alert && !error)) {
+ return <RailLoading onClose={onClose} />;
+ }
+
+ if (error || !alert) {
+ return (
+ <RailShell title="Investigation rail" onClose={onClose}>
+ <div className="px-4 py-6 text-sm text-red-300">
+ <p className="font-medium">Couldn&apos;t load the alert envelope.</p>
+ <p className="mt-1 text-xs text-gray-500">
+ The alert API didn&apos;t respond. Try selecting the alert again or
+ open the full detail view.
+ </p>
+ </div>
+ </RailShell>
+ );
+ }
+
+ return (
+ <>
+ <RailShell title={alert.title} onClose={onClose}>
+ <RailHeader alert={alert} onDeepExplain={() => setDeepExplainOpen(true)} />
+ <NarrativeSection narrative={alert.narrative ?? null} />
+ <RelatedEntitiesSection entities={alert.relatedEntities ?? []} />
+ <MiniTimelineSection events={alert.miniTimeline ?? []} />
+ <RecommendedActionsSection actions={alert.recommendedActions ?? []} />
+ </RailShell>
+ {/*
+ * Deep Explain is mounted only when requested — keeping it inside the
+ * rail (rather than at AlertsView level) means the rail owns the
+ * "deep" affordance and we don't end up with two ways to open the
+ * same drawer from different places.
+ */}
+ {deepExplainOpen && (
+ <ExplainDrawer
+ open={true}
+ alert={alert}
+ onClose={() => setDeepExplainOpen(false)}
+ />
+ )}
+ </>
+ );
+}
+
+// ─── Layout primitives ───────────────────────────────────────────────────────
+
+function RailShell({
+ title,
+ onClose,
+ children,
+}: {
+ title: string;
+ onClose: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <aside
+ className="flex flex-col bg-gray-900/60 border border-gray-800/60 rounded-xl overflow-hidden h-full"
+ aria-label="Investigation rail"
+ >
+ <div className="flex items-center justify-between px-4 py-3 border-b border-gray-800/60 bg-gray-900/80">
+ <h2 className="text-sm font-semibold text-gray-100 truncate" title={title}>
+ {title}
+ </h2>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close investigation rail"
+ className="text-xs text-gray-500 hover:text-gray-300 px-2 py-0.5 rounded hover:bg-gray-800/60 transition-colors"
+ >
+ Close
+ </button>
+ </div>
+ <div className="flex-1 overflow-y-auto">{children}</div>
+ </aside>
+ );
+}
+
+function RailPlaceholder() {
+ return (
+ <aside
+ className="flex flex-col items-center justify-center bg-gray-900/30 border border-dashed border-gray-800/60 rounded-xl text-gray-500 text-sm h-full p-6 text-center"
+ aria-label="Investigation rail (no alert selected)"
+ >
+ <p className="font-medium text-gray-400">Select an alert to investigate</p>
+ <p className="mt-1 text-xs text-gray-600">
+ Click a row in the queue on the left. The rail will show the fusion
+ narrative, related entities, recent events, and recommended actions.
+ </p>
+ </aside>
+ );
+}
+
+function RailLoading({ onClose }: { onClose: () => void }) {
+ return (
+ <RailShell title="Loading…" onClose={onClose}>
+ <div className="p-4 space-y-4">
+ <Skeleton className="h-4 w-2/3" />
+ <Skeleton className="h-3 w-full" />
+ <Skeleton className="h-3 w-5/6" />
+ <Skeleton className="h-3 w-4/6" />
+ <div className="pt-3 space-y-2">
+ <Skeleton className="h-3 w-1/4" />
+ <Skeleton className="h-3 w-3/4" />
+ <Skeleton className="h-3 w-2/4" />
+ </div>
+ </div>
+ </RailShell>
+ );
+}
+
+// ─── Header (severity, status, deep explain) ─────────────────────────────────
+
+function RailHeader({
+ alert,
+ onDeepExplain,
+}: {
+ alert: Alert;
+ onDeepExplain: () => void;
+}) {
+ return (
+ <div className="px-4 py-3 border-b border-gray-800/60 bg-gray-900/40">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-gray-500">
+ <span className="capitalize text-gray-300">{alert.severity}</span>
+ <span>·</span>
+ <span className="capitalize">{alert.status.replace('_', ' ')}</span>
+ <span>·</span>
+ <span>{alert.source}</span>
+ <span>·</span>
+ <span suppressHydrationWarning>
+ {formatDistanceToNow(new Date(alert.createdAt), { addSuffix: true })}
+ </span>
+ {typeof alert.riskScore === 'number' && (
+ <>
+ <span>·</span>
+ <span className="font-mono text-gray-400">
+ risk {Math.round(alert.riskScore)}
+ </span>
+ </>
+ )}
+ </div>
+ <div className="mt-3 flex items-center gap-3">
+ <button
+ type="button"
+ onClick={onDeepExplain}
+ aria-label="Open AI deep explain drawer"
+ title="Run the LLM deep-explain for this alert"
+ className="text-xs font-medium px-2.5 py-1 rounded border border-violet-500/40 bg-violet-500/10 text-violet-300 hover:bg-violet-500/20 hover:border-violet-500/60 transition-colors"
+ >
+ ✦ Deep Explain
+ </button>
+ <Link
+ href={`/alerts/${alert.id}`}
+ className="text-xs text-blue-300 hover:text-blue-200 transition-colors"
+ >
+ Open full detail →
+ </Link>
+ </div>
+ </div>
+ );
+}
+
+// ─── Sections ────────────────────────────────────────────────────────────────
+
+function SectionHeader({ title, count }: { title: string; count?: number }) {
+ return (
+ <h3 className="text-[11px] uppercase tracking-wider text-gray-500 mb-2 font-medium">
+ {title}
+ {typeof count === 'number' && (
+ <span className="ml-1.5 text-gray-600">({count})</span>
+ )}
+ </h3>
+ );
+}
+
+function NarrativeSection({ narrative }: { narrative: string | null }) {
+ if (!narrative || !narrative.trim()) return null;
+ // Markdown-light: we preserve newlines so the deterministic
+ // paragraph + bullet structure produced by `narrative.build_narrative`
+ // renders without us pulling in a full Markdown engine.
+ return (
+ <section className="px-4 py-4 border-b border-gray-800/40">
+ <SectionHeader title="Narrative" />
+ <p className="text-sm text-gray-300 whitespace-pre-wrap leading-relaxed">
+ {narrative}
+ </p>
+ </section>
+ );
+}
+
+function RelatedEntitiesSection({ entities }: { entities: RelatedEntity[] }) {
+ if (entities.length === 0) return null;
+ // Server already groups by kind in the canonical order, but defensively
+ // re-group on the client so an out-of-order payload (older API) still
+ // renders cleanly grouped.
+ const grouped = entities.reduce<Record<RelatedEntity['kind'], RelatedEntity[]>>(
+ (acc, e) => {
+ (acc[e.kind] ||= []).push(e);
+ return acc;
+ },
+ { principal: [], network: [], workflow: [], tenant: [] },
+ );
+ return (
+ <section className="px-4 py-4 border-b border-gray-800/40">
+ <SectionHeader title="Related entities" count={entities.length} />
+ <div className="space-y-3">
+ {(Object.keys(ENTITY_KIND_CONFIG) as Array<keyof typeof ENTITY_KIND_CONFIG>).map(
+ (kind) => {
+ const items = grouped[kind];
+ if (!items || items.length === 0) return null;
+ const cfg = ENTITY_KIND_CONFIG[kind];
+ return (
+ <div key={kind}>
+ <p className={clsx('text-xs font-medium', cfg.tone)}>{cfg.label}</p>
+ <ul className="mt-1.5 flex flex-wrap gap-1.5">
+ {items.map((e) => (
+ <EntityChip key={`${e.type}:${e.value}`} entity={e} />
+ ))}
+ </ul>
+ </div>
+ );
+ },
+ )}
+ </div>
+ </section>
+ );
+}
+
+function EntityChip({ entity }: { entity: RelatedEntity }) {
+ const display = entity.label || entity.value;
+ const inner = (
+ <span
+ className={clsx(
+ 'inline-flex items-center gap-1.5 text-xs px-2 py-0.5 rounded border border-gray-700/60 bg-gray-800/60 text-gray-200',
+ entity.pivotPath &&
+ 'hover:bg-gray-700/60 hover:border-gray-600/60 cursor-pointer transition-colors',
+ )}
+ title={`${entity.type}: ${entity.value}`}
+ >
+ <span className="text-gray-500 font-mono text-[10px]">{entity.type}</span>
+ <span className="font-mono">{display}</span>
+ </span>
+ );
+ return (
+ <li>
+ {entity.pivotPath ? (
+ <Link href={entity.pivotPath} className="inline-block">
+ {inner}
+ </Link>
+ ) : (
+ inner
+ )}
+ </li>
+ );
+}
+
+function MiniTimelineSection({ events }: { events: MiniTimelineEvent[] }) {
+ if (events.length === 0) return null;
+ return (
+ <section className="px-4 py-4 border-b border-gray-800/40">
+ <SectionHeader title="Recent events" count={events.length} />
+ <ol className="space-y-2.5">
+ {events.map((e) => (
+ <TimelineRow key={e.id} event={e} />
+ ))}
+ </ol>
+ </section>
+ );
+}
+
+function TimelineRow({ event }: { event: MiniTimelineEvent }) {
+ let ts: string;
+ try {
+ ts = format(new Date(event.timestamp), 'MMM d HH:mm');
+ } catch {
+ // Defensive: if the server hands back a malformed timestamp we still
+ // render the row rather than crashing the rail.
+ ts = event.timestamp;
+ }
+ return (
+ <li className="text-xs text-gray-300 border-l-2 border-gray-700/60 pl-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-mono text-gray-500 text-[10px]" suppressHydrationWarning>
+ {ts}
+ </span>
+ <span className="px-1.5 py-0 text-[10px] font-mono rounded border border-gray-700/60 bg-gray-800/40 text-gray-400 uppercase">
+ {event.source === 'case_timeline' ? 'case' : 'audit'}
+ </span>
+ <span className="text-[10px] uppercase text-gray-500 tracking-wide">
+ {event.type}
+ </span>
+ </div>
+ <p className="mt-0.5 text-gray-200">{event.title}</p>
+ {event.description && (
+ <p className="mt-0.5 text-gray-500 line-clamp-2">{event.description}</p>
+ )}
+ {event.actor && (
+ <p className="mt-0.5 text-[10px] text-gray-600">by {event.actor}</p>
+ )}
+ </li>
+ );
+}
+
+function RecommendedActionsSection({ actions }: { actions: RecommendedAction[] }) {
+ if (actions.length === 0) return null;
+ return (
+ <section className="px-4 py-4">
+ <SectionHeader title="Recommended actions" count={actions.length} />
+ <ul className="space-y-2">
+ {actions.map((a, idx) => (
+ <li
+ key={`${a.action}-${idx}`}
+ className="border border-gray-800/60 bg-gray-900/40 rounded-lg p-2.5"
+ >
+ <div className="flex items-start gap-2">
+ <span
+ className={clsx(
+ 'text-[10px] font-mono uppercase px-1.5 py-0.5 rounded border shrink-0 mt-0.5',
+ PRIORITY_TONE[a.priority] ?? PRIORITY_TONE.medium,
+ )}
+ >
+ {a.priority}
+ </span>
+ <p className="text-sm text-gray-200 flex-1">{a.action}</p>
+ </div>
+ {a.rationale && (
+ <p className="mt-1 text-xs text-gray-500 ml-[3.25rem]">
+ {a.rationale}
+ </p>
+ )}
+ {a.risk && (
+ <p className="mt-1 text-xs text-amber-400/80 ml-[3.25rem]">
+ Risk: {a.risk}
+ </p>
+ )}
+ </li>
+ ))}
+ </ul>
+ </section>
+ );
+}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index de989a210..f763ee345 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -429,6 +429,57 @@ export interface ConfidenceFactor {
weight: number;
}
+/**
+ * One pivotable entity from the Investigation Rail (W6).
+ *
+ * The API groups these by ``kind`` — *principal* (user, host, asset),
+ * *network* (ip, domain, fqdn), *workflow* (case_id, run_id, ledger),
+ * *tenant* (tenant_id) — so the rail can render each group with its
+ * own affordances. ``value`` is always renderable as text; ``label``
+ * is an optional human-friendly override. ``pivotPath`` is an
+ * internal href (e.g. ``/graph?node=ip:10.0.0.1``) when the entity
+ * can be opened in the AttackGraphView.
+ */
+export interface RelatedEntity {
+ kind: 'principal' | 'network' | 'workflow' | 'tenant';
+ type: string;
+ value: string;
+ label?: string | null;
+ pivotPath?: string | null;
+}
+
+/**
+ * One row in the Investigation Rail's mini-timeline (W6).
+ *
+ * Reuses the shape of ``InvestigationLedger`` so the existing
+ * renderer can be lifted. Sourced from the case timeline and audit
+ * log; capped at the six most recent events on the server.
+ */
+export interface MiniTimelineEvent {
+ id: string;
+ timestamp: string;
+ type: string;
+ title: string;
+ description?: string | null;
+ actor?: string | null;
+ /** ``case_timeline`` or ``audit_log`` — surfaced as a small badge. */
+ source: 'case_timeline' | 'audit_log';
+}
+
+/**
+ * One row in the rail's "Recommended actions" list (W6).
+ *
+ * Generated by the ResponderAgent and normalised server-side so the
+ * UI can render legacy list-of-strings payloads and the structured
+ * shape uniformly.
+ */
+export interface RecommendedAction {
+ priority: 'critical' | 'high' | 'medium' | 'low' | 'info';
+ action: string;
+ rationale?: string | null;
+ risk?: string | null;
+}
+
export interface Alert {
id: string;
title: string;
@@ -454,6 +505,201 @@ export interface Alert {
ledgerRunId?: string;
/** Analyst-corrected verdict (Tier 1.5 override loop). */
disposition?: 'true_positive' | 'false_positive' | 'benign' | 'escalate' | null;
+ // ─── Investigation Rail envelope (W6) ─────────────────────────────────────
+ //
+ // The list endpoint never populates these — they're only present
+ // on ``GET /api/v1/alerts/{id}``. The rail component checks for
+ // their presence before rendering each section, so it degrades
+ // gracefully when the backend predates v1.5.
+ narrative?: string | null;
+ relatedEntities?: RelatedEntity[];
+ miniTimeline?: MiniTimelineEvent[];
+ recommendedActions?: RecommendedAction[];
+}
+
+/**
+ * Normalize an alert payload coming back from the API.
+ *
+ * The Postgres-backed API speaks ``snake_case`` (``tenant_id``,
+ * ``risk_score``, ``confidence_label``, …) while the web console's
+ * ``Alert`` type uses ``camelCase``. We map the keys explicitly so
+ * the UI can rely on the documented shape and the new Investigation
+ * Rail fields (W6 — ``narrative``, ``related_entities``,
+ * ``mini_timeline``, ``recommended_actions``) flow through one
+ * predictable boundary.
+ *
+ * Unknown / missing keys are tolerated — older API builds simply
+ * don't carry the new fields and the rail renders empty sections.
+ */
+function normalizeAlert(raw: unknown): Alert {
+ const r = (raw ?? {}) as Record<string, unknown>;
+
+ const pickStr = (snake: string, camel: string): string | undefined => {
+ const v = r[snake] ?? r[camel];
+ return typeof v === 'string' ? v : undefined;
+ };
+ const pickNum = (snake: string, camel: string): number | undefined => {
+ const v = r[snake] ?? r[camel];
+ return typeof v === 'number' ? v : undefined;
+ };
+ const pickArr = <T = unknown>(snake: string, camel: string): T[] | undefined => {
+ const v = r[snake] ?? r[camel];
+ return Array.isArray(v) ? (v as T[]) : undefined;
+ };
+
+ // Tags arrive either as a bare array (legacy) or as the JSONB
+ // ``{labels: [...]}`` shape the cases endpoint uses. Normalise to
+ // a plain string[] so the rail and grid can map without a guard.
+ const tagsRaw = r.tags;
+ let tags: string[] | undefined;
+ if (Array.isArray(tagsRaw)) {
+ tags = tagsRaw.map((t) => String(t));
+ } else if (
+ tagsRaw &&
+ typeof tagsRaw === 'object' &&
+ Array.isArray((tagsRaw as Record<string, unknown>).labels)
+ ) {
+ tags = ((tagsRaw as Record<string, unknown>).labels as unknown[]).map((t) =>
+ String(t),
+ );
+ }
+
+ // MITRE: the API can return either ``mitre_attack`` (already
+ // structured) or the split ``mitre_tactics`` / ``mitre_techniques``
+ // arrays. Prefer structured; otherwise zip the two parallel lists.
+ let mitreAttack: MitreAttack[] | undefined;
+ const mitreStructured = r.mitre_attack ?? r.mitreAttack;
+ if (Array.isArray(mitreStructured)) {
+ mitreAttack = (mitreStructured as Array<Record<string, unknown>>).map((m) => ({
+ tactic: String(m.tactic ?? ''),
+ technique: String(m.technique ?? ''),
+ techniqueId: String(m.technique_id ?? m.techniqueId ?? ''),
+ }));
+ } else {
+ const techniques = pickArr<string>('mitre_techniques', 'mitreTechniques');
+ const tactics = pickArr<string>('mitre_tactics', 'mitreTactics');
+ if (techniques && techniques.length > 0) {
+ mitreAttack = techniques.map((t, i) => ({
+ tactic: tactics?.[i] ? String(tactics[i]) : '',
+ technique: String(t),
+ techniqueId: String(t),
+ }));
+ }
+ }
+
+ const rationaleRaw = r.confidence_rationale ?? r.confidenceRationale;
+ const confidenceRationale = Array.isArray(rationaleRaw)
+ ? (rationaleRaw as Array<Record<string, unknown>>).map((f) => ({
+ factor: String(f.factor ?? ''),
+ label: String(f.label ?? ''),
+ value: Number(f.value ?? 0),
+ contribution: Number(f.contribution ?? 0),
+ weight: Number(f.weight ?? 0),
+ }))
+ : undefined;
+
+ // ── Investigation Rail envelope (W6) ────────────────────────────────────
+ const relatedRaw = r.related_entities ?? r.relatedEntities;
+ const relatedEntities = Array.isArray(relatedRaw)
+ ? (relatedRaw as Array<Record<string, unknown>>).map((e) => ({
+ kind: (e.kind ?? 'principal') as RelatedEntity['kind'],
+ type: String(e.type ?? ''),
+ value: String(e.value ?? ''),
+ label: (e.label as string | null | undefined) ?? null,
+ pivotPath:
+ (e.pivot_path as string | null | undefined) ??
+ (e.pivotPath as string | null | undefined) ??
+ null,
+ }))
+ : undefined;
+
+ const timelineRaw = r.mini_timeline ?? r.miniTimeline;
+ const miniTimeline = Array.isArray(timelineRaw)
+ ? (timelineRaw as Array<Record<string, unknown>>).map((e) => ({
+ id: String(e.id ?? ''),
+ timestamp: String(e.timestamp ?? ''),
+ type: String(e.type ?? ''),
+ title: String(e.title ?? ''),
+ description: (e.description as string | null | undefined) ?? null,
+ actor: (e.actor as string | null | undefined) ?? null,
+ source: (e.source ?? 'audit_log') as MiniTimelineEvent['source'],
+ }))
+ : undefined;
+
+ const recommendedRaw =
+ r.recommended_actions ??
+ r.recommendedActions ??
+ r.ai_recommendations ??
+ r.aiRecommendations;
+ let recommendedActions: RecommendedAction[] | undefined;
+ if (Array.isArray(recommendedRaw)) {
+ recommendedActions = (recommendedRaw as unknown[]).map((item) => {
+ if (typeof item === 'string') {
+ return { priority: 'medium', action: item };
+ }
+ const o = (item ?? {}) as Record<string, unknown>;
+ return {
+ priority: (o.priority ?? 'medium') as RecommendedAction['priority'],
+ action: String(o.action ?? ''),
+ rationale: (o.rationale as string | null | undefined) ?? null,
+ risk: (o.risk as string | null | undefined) ?? null,
+ };
+ });
+ }
+
+ // ``risk_score`` legacy fallback: fusion sometimes only ships
+ // ``confidence`` (0-100) and not the older ``risk_score``. Prefer
+ // the explicit field, fall back to confidence as a soft signal.
+ const riskScore =
+ pickNum('risk_score', 'riskScore') ??
+ pickNum('ai_score', 'aiScore') ??
+ pickNum('confidence', 'confidence') ??
+ 0;
+
+ return {
+ id: String(r.id ?? ''),
+ title: String(r.title ?? ''),
+ description: String(r.description ?? ''),
+ severity: ((r.severity as string) ?? 'medium') as AlertSeverity,
+ status: ((r.status as string) ?? 'new') as AlertStatus,
+ source:
+ pickStr('source', 'source') ??
+ pickStr('connector_type', 'connectorType') ??
+ 'unknown',
+ sourceRef: pickStr('source_ref', 'sourceRef'),
+ tenantId: pickStr('tenant_id', 'tenantId') ?? '',
+ riskScore,
+ mitreAttack,
+ iocs: pickArr<AlertIOC>('iocs', 'iocs'),
+ rawEvent:
+ (r.raw_event as Record<string, unknown> | undefined) ??
+ (r.rawEvent as Record<string, unknown> | undefined),
+ assignee: pickStr('assignee', 'assignee'),
+ caseId: pickStr('case_id', 'caseId'),
+ tags,
+ createdAt:
+ pickStr('created_at', 'createdAt') ??
+ pickStr('first_seen', 'firstSeen') ??
+ new Date().toISOString(),
+ updatedAt:
+ pickStr('updated_at', 'updatedAt') ??
+ pickStr('last_seen', 'lastSeen') ??
+ new Date().toISOString(),
+ resolvedAt: pickStr('resolved_at', 'resolvedAt'),
+ confidenceLabel: (r.confidence_label ?? r.confidenceLabel) as
+ | ConfidenceLabel
+ | undefined,
+ confidenceScore:
+ pickNum('confidence_score', 'confidenceScore') ??
+ pickNum('confidence', 'confidence'),
+ confidenceRationale,
+ ledgerRunId: pickStr('ledger_run_id', 'ledgerRunId'),
+ disposition: (r.disposition ?? null) as Alert['disposition'],
+ narrative: (r.narrative as string | null | undefined) ?? null,
+ relatedEntities,
+ miniTimeline,
+ recommendedActions,
+ };
}
export interface AlertsResponse {
@@ -477,18 +723,41 @@ export interface AlertFilters {
}
export const alertsApi = {
- list: (filters: AlertFilters = {}) =>
- request<AlertsResponse>('/api/v1/alerts', {
+ list: async (filters: AlertFilters = {}) => {
+ const raw = await request<{
+ alerts?: unknown[];
+ total?: number;
+ page?: number;
+ page_size?: number;
+ pageSize?: number;
+ }>('/api/v1/alerts', {
params: filters as Record<string, string>,
- }),
+ });
+ return {
+ alerts: Array.isArray(raw.alerts) ? raw.alerts.map(normalizeAlert) : [],
+ total: typeof raw.total === 'number' ? raw.total : 0,
+ page: typeof raw.page === 'number' ? raw.page : 1,
+ pageSize:
+ typeof raw.pageSize === 'number'
+ ? raw.pageSize
+ : typeof raw.page_size === 'number'
+ ? raw.page_size
+ : 50,
+ } satisfies AlertsResponse;
+ },
- get: (id: string) => request<Alert>(`/api/v1/alerts/${id}`),
+ get: async (id: string) => {
+ const raw = await request<unknown>(`/api/v1/alerts/${id}`);
+ return normalizeAlert(raw);
+ },
- update: (id: string, data: Partial<Alert>) =>
- request<Alert>(`/api/v1/alerts/${id}`, {
+ update: async (id: string, data: Partial<Alert>) => {
+ const raw = await request<unknown>(`/api/v1/alerts/${id}`, {
method: 'PATCH',
body: JSON.stringify(data),
- }),
+ });
+ return normalizeAlert(raw);
+ },
bulkAction: (
ids: string[],
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 972429d84..e79698fbc 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -464,7 +464,14 @@ paths:
tags:
- alerts
summary: Get Alert
- description: Get a single alert by ID.
+ description: "Get a single alert by ID, enriched with Investigation Rail data.\n\
+ \nThe endpoint returns the standard alert fields plus everything the\nrail\
+ \ needs to render in one shot:\n\n* a deterministic ``narrative`` (lazily\
+ \ filled and persisted if the\n row was created before fusion started emitting\
+ \ it),\n* ``related_entities`` grouped for pivot,\n* a compact ``mini_timeline``,\n\
+ * normalised ``recommended_actions``.\n\nThe lazy-fill is best-effort: if\
+ \ the narrative builder ever raises\nwe log and return the alert with ``narrative=None``\
+ \ so the page\nkeeps rendering. The frontend already handles the null case."
operationId: get_alert_api_v1_alerts__alert_id__get
security:
- HTTPBearer: []
@@ -482,7 +489,7 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/AlertResponse'
+ $ref: '#/components/schemas/AlertDetailResponse'
'422':
description: Validation Error
content:
@@ -12387,6 +12394,202 @@ components:
- threat_intel_age_hours
- checks
title: AirgapStatus
+ AlertDetailResponse:
+ properties:
+ id:
+ type: string
+ format: uuid
+ title: Id
+ tenant_id:
+ type: string
+ format: uuid
+ title: Tenant Id
+ title:
+ type: string
+ title: Title
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ severity:
+ type: string
+ title: Severity
+ status:
+ type: string
+ title: Status
+ priority:
+ type: integer
+ title: Priority
+ category:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Category
+ mitre_tactics:
+ items: {}
+ type: array
+ title: Mitre Tactics
+ mitre_techniques:
+ items: {}
+ type: array
+ title: Mitre Techniques
+ connector_type:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Connector Type
+ ai_score:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Ai Score
+ ai_summary:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Ai Summary
+ ai_recommendations:
+ items: {}
+ type: array
+ title: Ai Recommendations
+ confidence:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Confidence
+ confidence_label:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Confidence Label
+ confidence_rationale:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Confidence Rationale
+ disposition:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Disposition
+ affected_ips:
+ items: {}
+ type: array
+ title: Affected Ips
+ affected_hosts:
+ items: {}
+ type: array
+ title: Affected Hosts
+ affected_users:
+ items: {}
+ type: array
+ title: Affected Users
+ case_id:
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
+ title: Case Id
+ tags:
+ items: {}
+ type: array
+ title: Tags
+ event_time:
+ type: string
+ format: date-time
+ title: Event Time
+ first_seen:
+ type: string
+ format: date-time
+ title: First Seen
+ last_seen:
+ type: string
+ format: date-time
+ title: Last Seen
+ snoozed_until:
+ anyOf:
+ - type: string
+ format: date-time
+ - type: 'null'
+ title: Snoozed Until
+ snoozed_by_id:
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
+ title: Snoozed By Id
+ created_at:
+ type: string
+ format: date-time
+ title: Created At
+ updated_at:
+ type: string
+ format: date-time
+ title: Updated At
+ narrative:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Narrative
+ related_entities:
+ items:
+ $ref: '#/components/schemas/RelatedEntity'
+ type: array
+ title: Related Entities
+ default: []
+ mini_timeline:
+ items:
+ $ref: '#/components/schemas/MiniTimelineEvent'
+ type: array
+ title: Mini Timeline
+ default: []
+ recommended_actions:
+ items:
+ $ref: '#/components/schemas/RecommendedAction'
+ type: array
+ title: Recommended Actions
+ default: []
+ type: object
+ required:
+ - id
+ - tenant_id
+ - title
+ - description
+ - severity
+ - status
+ - priority
+ - category
+ - mitre_tactics
+ - mitre_techniques
+ - connector_type
+ - ai_score
+ - ai_summary
+ - ai_recommendations
+ - affected_ips
+ - affected_hosts
+ - affected_users
+ - case_id
+ - tags
+ - event_time
+ - first_seen
+ - last_seen
+ - created_at
+ - updated_at
+ title: AlertDetailResponse
+ description: "Alert response enriched with everything the Investigation Rail\
+ \ needs.\n\nThe list endpoint stays on the smaller :class:`AlertResponse`\
+ \ shape\nto keep paginated payloads light. The detail endpoint promotes to\n\
+ this enriched shape so the rail renders without extra round-trips:\n\n* ``narrative``\
+ \ — deterministic correlation prose. Cached on the\n ``Alert`` row by the\
+ \ fusion service; lazily filled by the\n endpoint when missing (legacy rows).\
+ \ Always a string by the\n time it leaves the API.\n* ``related_entities``\
+ \ — pivotable entities grouped by\n principal / network / workflow / tenant.\n\
+ * ``mini_timeline`` — up to ``MAX_TIMELINE_EVENTS`` recent events\n merged\
+ \ from the case timeline and the audit log.\n* ``recommended_actions`` — normalised\
+ \ structured actions from\n the ResponderAgent (or the legacy list-of-strings\
+ \ shape)."
AlertLinkCreate:
properties:
alert_id:
@@ -18883,6 +19086,57 @@ components:
- connector_count
- health_score
title: MetricsOut
+ MiniTimelineEvent:
+ properties:
+ id:
+ type: string
+ title: Id
+ ts:
+ type: string
+ format: date-time
+ title: Ts
+ kind:
+ type: string
+ title: Kind
+ description: audit | case_comment | status_change | investigation | …
+ agent:
+ type: string
+ title: Agent
+ description: actor — system | analyst@… | agent-id
+ summary:
+ type: string
+ title: Summary
+ description: One-line description, plain text
+ payload:
+ anyOf:
+ - additionalProperties: true
+ type: object
+ - type: 'null'
+ title: Payload
+ duration_ms:
+ type: integer
+ title: Duration Ms
+ default: 0
+ type: object
+ required:
+ - id
+ - ts
+ - kind
+ - agent
+ - summary
+ title: MiniTimelineEvent
+ description: 'One event in the alert''s condensed timeline.
+
+
+ Modelled after ``LedgerEvent`` in the ledger UI so the rail can
+
+ reuse the same row renderer. Fields the rail doesn''t need
+
+ (``input_hash``/``output_hash``/``duration_ms``) are always
+
+ ``None``/``0`` for non-investigation events. The frontend knows
+
+ to hide those affordances when they''re empty.'
MispDryRunRequest:
properties:
indicator:
@@ -20662,6 +20916,39 @@ components:
required:
- score
title: RatingIn
+ RecommendedAction:
+ properties:
+ priority:
+ type: integer
+ minimum: 1.0
+ title: Priority
+ default: 99
+ action:
+ type: string
+ title: Action
+ rationale:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Rationale
+ risk:
+ type: string
+ title: Risk
+ description: low | medium | high
+ default: low
+ type: object
+ required:
+ - action
+ title: RecommendedAction
+ description: 'Structured action emitted by the ResponderAgent at investigation
+ close.
+
+
+ Tolerates the legacy list-of-strings shape that older demo seeds
+
+ used (string → ``action`` with priority ``99`` and risk ``"low"``).
+
+ The plan calls for the structured shape; this is a migration aid.'
RedispositionApplyRequest:
properties:
alert_ids:
@@ -20739,6 +21026,51 @@ components:
default: My phone
type: object
title: RegisterBeginRequest
+ RelatedEntity:
+ properties:
+ group:
+ type: string
+ title: Group
+ description: 'Rail column: principal | network | workflow | tenant'
+ kind:
+ type: string
+ title: Kind
+ description: 'Concrete entity type: host | ip | user | rule | mitre | …'
+ value:
+ type: string
+ title: Value
+ description: Canonical identifier rendered in the chip
+ label:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Label
+ description: Optional human-friendly label
+ pivot:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pivot
+ description: Frontend route to deep-link into AttackGraphView (or another
+ workbench). When None the chip is informational only.
+ type: object
+ required:
+ - group
+ - kind
+ - value
+ title: RelatedEntity
+ description: 'One pivotable entity attached to an alert.
+
+
+ The ``kind`` field is the *concrete* entity type (``host``, ``ip``,
+
+ ``user``, ``rule``, …) — the frontend keys icons and pivot routes
+
+ off it. The ``group`` field is the rail column the entity renders
+
+ under (``principal``, ``network``, ``workflow``, ``tenant``). One
+
+ entity belongs to exactly one group; we don''t duplicate rows.'
ReviewAction:
properties:
action:
diff --git a/scripts/sync_vendored_narrative.py b/scripts/sync_vendored_narrative.py
new file mode 100755
index 000000000..62f1d73e1
--- /dev/null
+++ b/scripts/sync_vendored_narrative.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python3
+"""Keep ``services/api/app/_vendor/narrative.py`` in lockstep with its source.
+
+The correlation-narrative builder lives canonically under
+``services/fusion/app/services/narrative.py`` and is consumed by both the
+fusion service (at fusion time, to populate ``FusedAlert.narrative``) and the
+API service (lazily, when a row's ``narrative`` column is ``NULL``). Because
+the ``aisoc-api`` Docker image is built with ``services/api`` as its build
+context, anything under ``services/fusion`` is not available at runtime. To
+keep the API container self-contained we ship a vendored mirror of
+``narrative.py`` inside the API package.
+
+Run modes
+---------
+* ``python scripts/sync_vendored_narrative.py`` — copy source → vendored.
+* ``python scripts/sync_vendored_narrative.py --check`` — fail (exit 1) if the
+ vendored file is missing or differs from the source. CI uses this mode.
+
+The script is intentionally tiny and dependency-free so it can run in any CI
+runner.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+import argparse
+import filecmp
+import shutil
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+SOURCE_FILE = REPO_ROOT / "services" / "fusion" / "app" / "services" / "narrative.py"
+VENDORED_FILE = REPO_ROOT / "services" / "api" / "app" / "_vendor" / "narrative.py"
+
+
+def _check() -> int:
+ if not SOURCE_FILE.is_file():
+ print(f"FAIL: source file missing: {SOURCE_FILE}", file=sys.stderr)
+ return 1
+ if not VENDORED_FILE.is_file():
+ print(f"FAIL: vendored file missing: {VENDORED_FILE}", file=sys.stderr)
+ return 1
+ if not filecmp.cmp(SOURCE_FILE, VENDORED_FILE, shallow=False):
+ print(
+ "FAIL: vendored narrative.py is out of sync with source.\n"
+ f" Source: {SOURCE_FILE.relative_to(REPO_ROOT)}\n"
+ f" Vendored: {VENDORED_FILE.relative_to(REPO_ROOT)}\n\n"
+ "Re-run: python scripts/sync_vendored_narrative.py",
+ file=sys.stderr,
+ )
+ return 1
+ print("OK: vendored narrative.py matches source.")
+ return 0
+
+
+def _sync() -> int:
+ if not SOURCE_FILE.is_file():
+ print(f"FAIL: source file missing: {SOURCE_FILE}", file=sys.stderr)
+ return 1
+ VENDORED_FILE.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(SOURCE_FILE, VENDORED_FILE)
+ print(
+ f"copied {SOURCE_FILE.relative_to(REPO_ROOT)} → "
+ f"{VENDORED_FILE.relative_to(REPO_ROOT)}"
+ )
+ print("\nDone. Don't forget to commit services/api/app/_vendor/narrative.py.")
+ return 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--check",
+ action="store_true",
+ help="Fail with a non-zero exit code if the vendored file is out of sync.",
+ )
+ args = parser.parse_args()
+ return _check() if args.check else _sync()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/services/api/app/_vendor/VENDORED_narrative.md b/services/api/app/_vendor/VENDORED_narrative.md
new file mode 100644
index 000000000..12ab8afa4
--- /dev/null
+++ b/services/api/app/_vendor/VENDORED_narrative.md
@@ -0,0 +1,52 @@
+# Vendored: `narrative.py`
+
+This file is an **automatically maintained mirror** of
+`services/fusion/app/services/narrative.py`. Do not hand-edit it.
+
+## Why it exists
+
+The API service ships in a Docker image whose build context is
+`./services/api`. That means modules under `services/fusion/` are not present
+in the running container. The deterministic correlation-narrative builder is
+consumed by both:
+
+- **Fusion** (`services/fusion`), at fusion time, to populate
+ `FusedAlert.narrative` before the alert is published to Kafka.
+- **API** (`services/api`), lazily, when `GET /alerts/{id}` is asked for an
+ alert whose `narrative` column is still `NULL` (e.g. legacy rows fused
+ before the column existed). The API computes the narrative on first read
+ and persists it on the row so subsequent reads are free.
+
+We keep an in-tree copy here so the API container is fully self-contained.
+
+## How it stays in sync
+
+Run `python scripts/sync_vendored_narrative.py` whenever you change
+`services/fusion/app/services/narrative.py`. CI runs the same script in
+`--check` mode in `.github/workflows/ci.yml` and fails the build if the two
+copies drift.
+
+## Files
+
+| Vendored file | Source of truth |
+| ------------------- | ----------------------------------------------------- |
+| `narrative.py` | `services/fusion/app/services/narrative.py` |
+
+## Loader
+
+The dynamic loader at
+`services/api/app/services/narrative_loader.py::_load_narrative_module`
+checks this directory **first**, then falls back to the source-of-truth file
+at `services/fusion/app/services/narrative.py` for local development outside
+Docker.
+
+## Determinism contract
+
+`build_narrative(inputs)` is a **pure, deterministic** function — same
+inputs always produce the same byte-for-byte string. No timestamps, no
+random ordering, no LLM. Callers may safely cache the result on the alert
+row. See the module docstring in `narrative.py` for the full contract.
+
+For the streaming **LLM** explanation surfaced by the "Deep Explain" action
+in the UI, see `/api/v1/alerts/{id}/explain` — that is a separate, on-demand
+endpoint that does **not** use this builder.
diff --git a/services/api/app/_vendor/__init__.py b/services/api/app/_vendor/__init__.py
index 99de4c417..4d75bf3b3 100644
--- a/services/api/app/_vendor/__init__.py
+++ b/services/api/app/_vendor/__init__.py
@@ -3,9 +3,10 @@
This namespace exists so that modules owned by *other* services can be shipped
inside the ``aisoc-api`` Docker image without depending on the rest of the
monorepo being copied in. The build context for ``services/api/Dockerfile`` is
-``./services/api``, which means anything under ``services/agents`` is **not**
-available at runtime — vendoring the bits we actually consume is the simplest,
-most auditable way to keep the container self-contained.
+``./services/api``, which means anything under ``services/agents`` or
+``services/fusion`` is **not** available at runtime — vendoring the bits we
+actually consume is the simplest, most auditable way to keep the container
+self-contained.
Current vendored modules:
@@ -14,8 +15,16 @@ Current vendored modules:
``scripts/sync_vendored_nl_query.py``; CI fails the build if the two trees
drift.
-Do **not** import from this namespace directly outside of
-``services/api/app/api/v1/endpoints/nl_query.py``. The dynamic loader in that
-endpoint resolves the module at runtime under a collision-free name so it does
-not interfere with the rest of the ``app`` package.
+* ``narrative`` — deterministic correlation-narrative builder owned by
+ ``services/fusion/app/services/narrative.py``. Used by the API to lazily
+ compute the narrative on first read for alerts whose ``narrative`` column
+ is still ``NULL`` (e.g. legacy rows fused before the column existed). Kept
+ in lockstep via ``scripts/sync_vendored_narrative.py``; CI fails the build
+ if the two copies drift.
+
+Do **not** import from this namespace directly outside of the dynamic loaders
+in ``services/api/app/api/v1/endpoints/nl_query.py`` and
+``services/api/app/services/narrative_loader.py``. The loaders resolve the
+modules at runtime under collision-free names so they do not interfere with
+the rest of the ``app`` package.
"""
diff --git a/services/api/app/_vendor/narrative.py b/services/api/app/_vendor/narrative.py
new file mode 100644
index 000000000..5519e1b58
--- /dev/null
+++ b/services/api/app/_vendor/narrative.py
@@ -0,0 +1,327 @@
+"""
+Correlation narrative builder.
+
+Wave 6 of the v1.5 SOC Console Parity plan. Every fused alert ships with a
+human-readable, deterministic correlation narrative that the
+``InvestigationRail`` on ``/alerts`` renders verbatim. The narrative answers
+the analyst's first three questions in one short paragraph — *what fired*,
+*what evidence supports it*, and *what we recommend next* — so the right pane
+of the alerts workbench is useful **without** an LLM round-trip. The
+streaming LLM explanation still exists; it sits behind a "Deep Explain"
+button inside the rail (``POST /api/v1/alerts/{id}/explain``).
+
+Design contract
+===============
+
+* **Deterministic.** Given identical inputs the output is byte-for-byte
+ identical. No timestamps, no random ordering, no LLM. The output is safe to
+ cache on the row and serve cold.
+* **Pure.** ``build_narrative`` is a free function that takes a
+ ``NarrativeInputs`` dataclass and returns a string. No database calls, no
+ network, no logging side effects.
+* **Vendored.** This module lives canonically in ``services/fusion`` and is
+ byte-mirrored into ``services/api/app/_vendor/narrative.py`` so the API can
+ lazily compute the narrative on first read for legacy alerts that were
+ fused before the column existed. ``scripts/sync_vendored_narrative.py``
+ guards the mirror; CI fails the build the moment the two copies drift.
+* **Markdown-light.** The output uses a tiny markdown dialect — ``**bold**``,
+ bullet lists, blank-line paragraphs. The rail renders these without a full
+ markdown engine. No tables, no headings, no images.
+
+Schema
+======
+
+The narrative is composed of up to four blocks separated by a blank line:
+
+1. **Summary** — one sentence: *severity*, *title*, *primary entity*.
+2. **Why we believe it** — up to four bullets pulled from the confidence
+ rationale, sorted by impact, prefixed with ``+`` or ``−``.
+3. **Correlated activity** — one short paragraph if the alert is part of an
+ incident, otherwise omitted.
+4. **Recommended next step** — one bullet derived from severity + MITRE
+ tactic. Action surface is deliberately conservative; the rail also
+ surfaces the LLM-generated remediation actions from the responder agent
+ for cases that need richer planning.
+
+If any block has no content it is dropped — the narrative never contains
+empty sections.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Literal
+
+NARRATIVE_VERSION = 1
+"""Bump this whenever the algorithm changes in a way that should invalidate
+existing cached narratives. The API uses this to opportunistically refresh
+rows whose ``narrative`` was generated under a stale version (a follow-up
+PR will add a ``narrative_version`` column once we need it; for now the
+constant simply marks the algorithm revision in code)."""
+
+
+Severity = Literal["critical", "high", "medium", "low", "info"]
+ConfidenceBand = Literal["high", "medium", "low"]
+
+
+@dataclass(frozen=True)
+class NarrativeFactor:
+ """One row of the confidence rationale, as seen by the builder.
+
+ Mirrors ``services/fusion/app/models/alert.py::ConfidenceFactor`` and
+ ``services/api/app/models/alert.py::Alert.confidence_rationale`` (which
+ stores the same shape as JSONB). The builder only needs the human-
+ facing fields, so we keep this dataclass minimal and avoid taking a
+ runtime dependency on either model.
+
+ ``contribution`` is signed in [-1.0, +1.0]; positive nudges the score
+ up, negative nudges it down. ``weight`` is in [0, 1].
+ """
+
+ label: str
+ value: str
+ contribution: float
+ weight: float
+
+ @property
+ def impact(self) -> float:
+ """Absolute signed effect — used to sort the rationale."""
+ return self.contribution * self.weight
+
+
+@dataclass(frozen=True)
+class NarrativeInputs:
+ """Everything ``build_narrative`` needs to produce a narrative.
+
+ Both services construct this from their own native model. Keeping the
+ dataclass deliberately minimal lets us add new signals (RBA score,
+ UEBA z-score, …) by adding optional fields without breaking the
+ fusion-time call site.
+ """
+
+ severity: Severity
+ title: str
+
+ # Detection confidence
+ confidence: int | None = None # 0-100 surfaced on the row
+ confidence_label: ConfidenceBand | None = None
+ rationale: tuple[NarrativeFactor, ...] = ()
+
+ # Entities — first non-empty wins for the "primary entity" mention.
+ src_ip: str | None = None
+ dst_ip: str | None = None
+ hostname: str | None = None
+ username: str | None = None
+ file_hash: str | None = None
+ domain: str | None = None
+ url: str | None = None
+
+ # MITRE coverage — we only use the first tactic + technique count to
+ # keep the prose terse. The full list still lives on the row.
+ mitre_tactics: tuple[str, ...] = ()
+ mitre_techniques: tuple[str, ...] = ()
+
+ # Correlation context — populated when the alert was attached to an
+ # incident at fusion time.
+ incident_alert_count: int | None = None # total alerts on the incident
+ correlation_decision: str | None = None # "new_incident" | "correlated"
+
+ # Risk-Based Alerting — set when the alert touches an entity that
+ # already accumulated RBA points before this fired.
+ rba_entity: str | None = None
+ rba_score: float | None = None
+
+ # Exploit-in-wild boost (Tier 3.5) — the vuln_boost service flips this
+ # when one of the alert's entities matches an asset vulnerability with
+ # ``is_exploited=True``. The narrative calls it out explicitly because
+ # it materially changes the recommended action.
+ exploit_in_wild: bool = False
+
+ # Optional source/connector — included in the summary for context.
+ source: str | None = None
+
+ # Optional tags surfaced verbatim ("byok-llm", "ransomware-family:lockbit").
+ tags: tuple[str, ...] = field(default_factory=tuple)
+
+
+# ─── Helpers ─────────────────────────────────────────────────────────────────
+
+
+# Recommended-next-step lookup. Keyed by ``(severity, mitre_tactic)`` so that
+# the same tactic at different severities gives a proportionate response.
+# ``"*"`` is a wildcard fallback that catches alerts with no MITRE mapping.
+#
+# These are deliberately *operational* sentences — what an analyst would
+# actually do in the next 60 seconds. The richer multi-step LLM remediation
+# plan is generated by the responder agent and surfaced separately.
+_RECOMMENDED_ACTIONS: dict[tuple[str, str], str] = {
+ ("critical", "initial-access"): "Isolate the affected host and revoke the impacted user's sessions immediately.",
+ ("critical", "execution"): "Isolate the host, snapshot volatile memory, and trigger the incident response playbook.",
+ ("critical", "persistence"): "Isolate the host and rotate any credentials with access to the persistence mechanism.",
+ ("critical", "privilege-escalation"): "Quarantine the host and audit privileged-group membership changes in the last 24h.",
+ ("critical", "defense-evasion"): "Isolate the host and validate EDR/AV state on every endpoint sharing the same image.",
+ ("critical", "credential-access"): "Force a password reset and revoke active sessions for every affected identity.",
+ ("critical", "discovery"): "Isolate the host and review authentication logs for lateral pivot attempts.",
+ ("critical", "lateral-movement"): "Quarantine the source and destination hosts; block the SMB/RDP path between them.",
+ ("critical", "collection"): "Isolate the host, preserve the staged data, and notify Legal/DPO of potential exfil.",
+ ("critical", "exfiltration"): "Block the destination at the egress firewall, isolate the source, and start IR.",
+ ("critical", "impact"): "Activate the disaster-recovery runbook and isolate every host in the blast radius.",
+ ("critical", "command-and-control"): "Block the C2 destination at the firewall and isolate the beaconing host.",
+ ("high", "initial-access"): "Investigate the auth/login chain; suspend the user pending verification.",
+ ("high", "execution"): "Triage the process tree and quarantine the binary if it is unsigned or rare.",
+ ("high", "persistence"): "Inspect autoruns / scheduled tasks on the host and capture the persistence artifact.",
+ ("high", "privilege-escalation"): "Review the privilege change chain and validate it against the change calendar.",
+ ("high", "defense-evasion"): "Verify EDR is healthy on the host and compare to a known-good baseline.",
+ ("high", "credential-access"): "Force a password rotation for the affected identity and review session activity.",
+ ("high", "discovery"): "Pull recon-related telemetry and check for follow-on lateral movement.",
+ ("high", "lateral-movement"): "Audit recent authentication on the destination host and block stale credentials.",
+ ("high", "collection"): "Snapshot the staged artifacts and review who else accessed the same data store.",
+ ("high", "exfiltration"): "Rate-limit the destination and confirm whether the upload is sanctioned.",
+ ("high", "impact"): "Verify backup integrity and tighten access to the impacted system.",
+ ("high", "command-and-control"): "Sinkhole the destination and inspect outbound DNS from the host.",
+ ("medium", "*"): "Triage the alert in the queue: confirm whether the activity is sanctioned before escalating.",
+ ("low", "*"): "Acknowledge in the queue; suppress if this is a known benign pattern.",
+ ("info", "*"): "Informational — review during the next batch tuning pass.",
+}
+
+_DEFAULT_ACTION = "Triage the alert in the queue and validate the supporting evidence before escalating."
+
+# Bullet glyph for the action — kept identical with the rationale glyph so
+# the rail can re-flow the list without re-thinking the bullet style.
+_BULLET = "- "
+
+
+def _primary_entity(inputs: NarrativeInputs) -> str | None:
+ """Pick the most informative entity to mention in the summary.
+
+ Order: ``src_ip → hostname → username → domain → url → dst_ip →
+ file_hash``. This matches the precedence used by the deduplicator's
+ correlation key so the narrative and the dedup key always agree on
+ which entity is "primary".
+ """
+ for value in (
+ inputs.src_ip,
+ inputs.hostname,
+ inputs.username,
+ inputs.domain,
+ inputs.url,
+ inputs.dst_ip,
+ inputs.file_hash,
+ ):
+ if value:
+ return value
+ return None
+
+
+def _summary_block(inputs: NarrativeInputs) -> str:
+ severity_word = inputs.severity.capitalize() if inputs.severity else "Unknown"
+ primary = _primary_entity(inputs)
+
+ pieces = [f"**{severity_word}** alert: {inputs.title.strip()}"]
+ if primary:
+ pieces.append(f"on **{primary}**")
+ if inputs.source:
+ pieces.append(f"from `{inputs.source}`")
+
+ sentence = " ".join(pieces).rstrip(".") + "."
+ return sentence
+
+
+def _rationale_block(inputs: NarrativeInputs) -> str | None:
+ if not inputs.rationale:
+ return None
+ # Sort by absolute impact, take the top four. We do *not* drop zero-
+ # impact factors silently — if the only factors we have are noise, the
+ # rail should say so explicitly. We only drop a factor whose absolute
+ # impact rounds to exactly zero *and* there are more impactful factors
+ # available.
+ ordered = sorted(inputs.rationale, key=lambda f: abs(f.impact), reverse=True)
+ keep: list[NarrativeFactor] = []
+ for factor in ordered:
+ if len(keep) >= 4:
+ break
+ # Skip purely zero rows once we already have one bullet.
+ if keep and round(abs(factor.impact), 3) == 0.0:
+ continue
+ keep.append(factor)
+ if not keep:
+ return None
+ lines = ["Why we believe it:"]
+ for factor in keep:
+ sign = "+" if factor.contribution >= 0 else "−"
+ lines.append(f"{_BULLET}{sign} **{factor.label}** — {factor.value}")
+ if inputs.confidence is not None and inputs.confidence_label is not None:
+ lines.append(f"{_BULLET}Confidence: **{inputs.confidence_label}** ({inputs.confidence}/100)")
+ elif inputs.confidence is not None:
+ lines.append(f"{_BULLET}Confidence: **{inputs.confidence}/100**")
+ elif inputs.confidence_label is not None:
+ lines.append(f"{_BULLET}Confidence: **{inputs.confidence_label}**")
+ return "\n".join(lines)
+
+
+def _correlation_block(inputs: NarrativeInputs) -> str | None:
+ pieces: list[str] = []
+ if inputs.correlation_decision == "correlated" and inputs.incident_alert_count and inputs.incident_alert_count > 1:
+ pieces.append(f"Correlated activity: this alert is part of an incident with **{inputs.incident_alert_count}** related alerts.")
+ elif inputs.correlation_decision == "new_incident":
+ pieces.append("Correlated activity: this is the **first** alert on a newly opened incident.")
+ if inputs.rba_entity and inputs.rba_score is not None:
+ pieces.append(
+ f"Risk-based alerting has accumulated **{inputs.rba_score:.0f}** points on `{inputs.rba_entity}` before this alert fired."
+ )
+ if inputs.exploit_in_wild:
+ pieces.append(
+ "**Exploit-in-wild**: one of the indicators on this alert matches an asset vulnerability marked as actively exploited."
+ )
+ if not pieces:
+ return None
+ return " ".join(pieces)
+
+
+def _action_block(inputs: NarrativeInputs) -> str:
+ # Resolve the recommended-action lookup. We use the first declared
+ # tactic; the rest are still visible on the row.
+ severity = inputs.severity or "medium"
+ tactic = inputs.mitre_tactics[0].lower() if inputs.mitre_tactics else "*"
+
+ action = _RECOMMENDED_ACTIONS.get((severity, tactic))
+ if action is None:
+ # Fall back to the severity-wildcard row, then to the default.
+ action = _RECOMMENDED_ACTIONS.get((severity, "*"), _DEFAULT_ACTION)
+ return f"Recommended next step:\n{_BULLET}{action}"
+
+
+# ─── Public API ──────────────────────────────────────────────────────────────
+
+
+def build_narrative(inputs: NarrativeInputs) -> str:
+ """Build the deterministic correlation narrative.
+
+ The output is plain Markdown-light (see module docstring). The same
+ inputs always produce the same string; callers can safely cache the
+ result keyed by the alert id.
+ """
+ blocks: list[str] = [_summary_block(inputs)]
+
+ rationale = _rationale_block(inputs)
+ if rationale:
+ blocks.append(rationale)
+
+ correlation = _correlation_block(inputs)
+ if correlation:
+ blocks.append(correlation)
+
+ blocks.append(_action_block(inputs))
+
+ return "\n\n".join(blocks)
+
+
+__all__ = [
+ "NARRATIVE_VERSION",
+ "NarrativeFactor",
+ "NarrativeInputs",
+ "build_narrative",
+]
diff --git a/services/api/app/api/v1/endpoints/alerts.py b/services/api/app/api/v1/endpoints/alerts.py
index 59e98e0f5..7ab607690 100644
--- a/services/api/app/api/v1/endpoints/alerts.py
+++ b/services/api/app/api/v1/endpoints/alerts.py
@@ -1,5 +1,6 @@
"""Alert management endpoints."""
+import logging
import uuid
from datetime import UTC, datetime
from typing import Annotated, Literal
@@ -18,6 +19,16 @@ from app.services.alert_queue import (
build_queue,
claim_alert,
)
+from app.services.alert_rail import (
+ MiniTimelineEvent,
+ RecommendedAction,
+ RelatedEntity,
+ build_rail_envelope,
+)
+from app.services.narrative_loader import build_narrative
+from app.services.narrative_projection import project_alert_to_narrative_inputs
+
+logger = logging.getLogger(__name__)
router = APIRouter(prefix="/alerts", tags=["alerts"])
@@ -61,6 +72,31 @@ class AlertResponse(BaseModel):
model_config = {"from_attributes": True}
+class AlertDetailResponse(AlertResponse):
+ """Alert response enriched with everything the Investigation Rail needs.
+
+ The list endpoint stays on the smaller :class:`AlertResponse` shape
+ to keep paginated payloads light. The detail endpoint promotes to
+ this enriched shape so the rail renders without extra round-trips:
+
+ * ``narrative`` — deterministic correlation prose. Cached on the
+ ``Alert`` row by the fusion service; lazily filled by the
+ endpoint when missing (legacy rows). Always a string by the
+ time it leaves the API.
+ * ``related_entities`` — pivotable entities grouped by
+ principal / network / workflow / tenant.
+ * ``mini_timeline`` — up to ``MAX_TIMELINE_EVENTS`` recent events
+ merged from the case timeline and the audit log.
+ * ``recommended_actions`` — normalised structured actions from
+ the ResponderAgent (or the legacy list-of-strings shape).
+ """
+
+ narrative: str | None = None
+ related_entities: list[RelatedEntity] = []
+ mini_timeline: list[MiniTimelineEvent] = []
+ recommended_actions: list[RecommendedAction] = []
+
+
class AlertSnoozeRequest(BaseModel):
"""Snooze an alert from the mobile responder PWA."""
@@ -233,18 +269,66 @@ async def get_alert_queue(
)
[email protected]("/{alert_id}", response_model=AlertResponse)
[email protected]("/{alert_id}", response_model=AlertDetailResponse)
async def get_alert(
alert_id: uuid.UUID,
current_user: Annotated[AuthUser, Depends(require_permission("alerts:read"))],
db: DBSession,
-) -> AlertResponse:
- """Get a single alert by ID."""
+) -> AlertDetailResponse:
+ """Get a single alert by ID, enriched with Investigation Rail data.
+
+ The endpoint returns the standard alert fields plus everything the
+ rail needs to render in one shot:
+
+ * a deterministic ``narrative`` (lazily filled and persisted if the
+ row was created before fusion started emitting it),
+ * ``related_entities`` grouped for pivot,
+ * a compact ``mini_timeline``,
+ * normalised ``recommended_actions``.
+
+ The lazy-fill is best-effort: if the narrative builder ever raises
+ we log and return the alert with ``narrative=None`` so the page
+ keeps rendering. The frontend already handles the null case.
+ """
result = await db.execute(select(Alert).where(Alert.id == alert_id, Alert.tenant_id == current_user.tenant_id))
alert = result.scalar_one_or_none()
if alert is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Alert not found")
- return AlertResponse.model_validate(alert)
+
+ # ── Lazy-fill narrative for legacy rows ─────────────────────────────
+ # New alerts get a narrative at fusion time. Older rows predate that
+ # column being populated; the first detail-view read materialises
+ # and persists one so we only pay the cost once per row.
+ if not alert.narrative:
+ try:
+ inputs = project_alert_to_narrative_inputs(alert)
+ narrative_text = build_narrative(inputs)
+ if narrative_text:
+ alert.narrative = narrative_text
+ await db.execute(update(Alert).where(Alert.id == alert.id).values(narrative=narrative_text, updated_at=datetime.now(UTC)))
+ await db.commit()
+ except Exception: # noqa: BLE001 — never let narrative kill a detail view
+ logger.warning(
+ "narrative lazy-fill failed for alert %s; serving without narrative",
+ alert.id,
+ exc_info=True,
+ )
+
+ envelope = await build_rail_envelope(db, alert)
+
+ # ``model_validate`` against the parent class to inherit field
+ # coercion, then merge the rail fields. We don't add the rail data
+ # to the ORM model — keeping the envelope construction in the view
+ # layer means the rail can evolve without migrations.
+ payload = AlertDetailResponse.model_validate(alert)
+ return payload.model_copy(
+ update={
+ "narrative": alert.narrative,
+ "related_entities": envelope.related_entities,
+ "mini_timeline": envelope.mini_timeline,
+ "recommended_actions": envelope.recommended_actions,
+ }
+ )
@router.patch("/{alert_id}", response_model=AlertResponse)
diff --git a/services/api/app/models/alert.py b/services/api/app/models/alert.py
index 3b82477d2..d8d01e5f3 100644
--- a/services/api/app/models/alert.py
+++ b/services/api/app/models/alert.py
@@ -55,6 +55,14 @@ class Alert(Base):
confidence_label: Mapped[str | None] = mapped_column(String(16), nullable=True)
confidence_rationale: Mapped[list | None] = mapped_column(JSONB, nullable=True)
+ # Correlation narrative — deterministic, human-readable text cached on
+ # the alert at fusion-time (or lazily computed by the API on first read
+ # for legacy rows). Surfaced verbatim by the InvestigationRail (W6 in
+ # the v1.5 SOC Console Parity plan) so the right pane renders without
+ # an LLM round-trip. The streaming LLM explanation lives behind the
+ # rail's "Deep Explain" button via /api/v1/alerts/{id}/explain.
+ narrative: Mapped[str | None] = mapped_column(Text, nullable=True)
+
# Entities (denormalized for fast querying)
affected_ips: Mapped[list] = mapped_column(JSONB, default=list)
affected_hosts: Mapped[list] = mapped_column(JSONB, default=list)
diff --git a/services/api/app/services/alert_rail.py b/services/api/app/services/alert_rail.py
new file mode 100644
index 000000000..054e6b526
--- /dev/null
+++ b/services/api/app/services/alert_rail.py
@@ -0,0 +1,518 @@
+"""Assemble structured data for the Investigation Rail on `/alerts`.
+
+The `/alerts` page in v1.5 shows an always-on right rail that surfaces
+*everything* an analyst needs to triage a single alert without bouncing
+between tabs:
+
+* A deterministic correlation **narrative** (already cached on the row
+ by the fusion service or lazily filled here — see
+ ``app/services/narrative_projection.py``).
+* **Related entities** grouped into four columns the analyst pivots
+ from (principal, network, workflow, tenant). Each entity carries
+ enough metadata for the frontend to deep-link into AttackGraphView
+ without an extra round trip.
+* A condensed **mini timeline** — at most ``MAX_TIMELINE_EVENTS``
+ recent events drawn from the alert's case ledger (if any) and the
+ audit log. Same data shape as the ledger's ``LedgerEvent`` so the
+ rail can reuse ``apps/web/src/components/cases/InvestigationLedger.tsx``
+ rendering primitives.
+* **Recommended actions** — read straight off ``Alert.ai_recommendations``
+ which the ResponderAgent populates at investigation-close time. The
+ endpoint normalises both the new structured shape and legacy
+ list-of-strings rows so old demos keep rendering.
+
+The assembler is deliberately *pure with respect to its DB session*:
+every read is `select(...)` + `await db.execute(...)`. No write paths.
+This keeps the lazy-fill flow in the alerts endpoint trivially
+restartable on failure — the rail data is a view, not a side-effect.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any
+
+from pydantic import BaseModel, Field
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.alert import Alert
+from app.models.audit import AuditLog
+from app.models.case import CaseTimeline
+
+# ─── Tunables ────────────────────────────────────────────────────────────────
+
+
+# How many timeline events the rail surfaces. The plan calls for "last
+# 6" — small enough to scan without scrolling, large enough to anchor
+# the analyst's mental model. Both case-timeline and audit-log sources
+# are merged then truncated.
+MAX_TIMELINE_EVENTS = 6
+
+
+# ─── Public Pydantic shapes ──────────────────────────────────────────────────
+
+
+class RelatedEntity(BaseModel):
+ """One pivotable entity attached to an alert.
+
+ The ``kind`` field is the *concrete* entity type (``host``, ``ip``,
+ ``user``, ``rule``, …) — the frontend keys icons and pivot routes
+ off it. The ``group`` field is the rail column the entity renders
+ under (``principal``, ``network``, ``workflow``, ``tenant``). One
+ entity belongs to exactly one group; we don't duplicate rows.
+ """
+
+ group: str = Field(description="Rail column: principal | network | workflow | tenant")
+ kind: str = Field(description="Concrete entity type: host | ip | user | rule | mitre | …")
+ value: str = Field(description="Canonical identifier rendered in the chip")
+ label: str | None = Field(default=None, description="Optional human-friendly label")
+ pivot: str | None = Field(
+ default=None,
+ description=("Frontend route to deep-link into AttackGraphView (or another workbench). When None the chip is informational only."),
+ )
+
+
+class MiniTimelineEvent(BaseModel):
+ """One event in the alert's condensed timeline.
+
+ Modelled after ``LedgerEvent`` in the ledger UI so the rail can
+ reuse the same row renderer. Fields the rail doesn't need
+ (``input_hash``/``output_hash``/``duration_ms``) are always
+ ``None``/``0`` for non-investigation events. The frontend knows
+ to hide those affordances when they're empty.
+ """
+
+ id: str
+ ts: datetime
+ kind: str = Field(description="audit | case_comment | status_change | investigation | …")
+ agent: str = Field(description="actor — system | analyst@… | agent-id")
+ summary: str = Field(description="One-line description, plain text")
+ payload: dict[str, Any] | None = Field(default=None)
+ duration_ms: int = 0
+
+
+class RecommendedAction(BaseModel):
+ """Structured action emitted by the ResponderAgent at investigation close.
+
+ Tolerates the legacy list-of-strings shape that older demo seeds
+ used (string → ``action`` with priority ``99`` and risk ``"low"``).
+ The plan calls for the structured shape; this is a migration aid.
+ """
+
+ priority: int = Field(default=99, ge=1)
+ action: str
+ rationale: str | None = None
+ risk: str = Field(default="low", description="low | medium | high")
+
+
+# ─── Internal helpers ────────────────────────────────────────────────────────
+
+
+def _norm_str(value: Any) -> str | None:
+ """Trim and discard empties. Returns ``None`` for non-strings."""
+ if not isinstance(value, str):
+ return None
+ stripped = value.strip()
+ return stripped or None
+
+
+def _from_blob(blob: Any, keys: Iterable[str]) -> str | None:
+ """Pull the first non-empty string at any of ``keys`` from a dict-ish blob."""
+ if not isinstance(blob, dict):
+ return None
+ for key in keys:
+ value = _norm_str(blob.get(key))
+ if value:
+ return value
+ return None
+
+
+def _dedup_strs(values: Iterable[Any]) -> list[str]:
+ """Stable dedup; case-insensitive but preserves first-seen casing."""
+ seen: set[str] = set()
+ out: list[str] = []
+ for v in values:
+ s = _norm_str(v)
+ if not s:
+ continue
+ key = s.lower()
+ if key in seen:
+ continue
+ seen.add(key)
+ out.append(s)
+ return out
+
+
+# ─── Related entities ────────────────────────────────────────────────────────
+
+
+@dataclass(slots=True)
+class _EntityBucket:
+ """In-flight collector that dedups within a (group, kind, value) tuple."""
+
+ entities: list[RelatedEntity]
+ _seen: set[tuple[str, str, str]]
+
+ @classmethod
+ def empty(cls) -> _EntityBucket:
+ return cls(entities=[], _seen=set())
+
+ def add(
+ self,
+ *,
+ group: str,
+ kind: str,
+ value: str | None,
+ label: str | None = None,
+ pivot: str | None = None,
+ ) -> None:
+ v = _norm_str(value)
+ if not v:
+ return
+ key = (group, kind, v.lower())
+ if key in self._seen:
+ return
+ self._seen.add(key)
+ self.entities.append(RelatedEntity(group=group, kind=kind, value=v, label=label, pivot=pivot))
+
+
+def build_related_entities(alert: Alert) -> list[RelatedEntity]:
+ """Produce the rail's Related Entities list from an ``Alert`` row.
+
+ The function is pure — no DB I/O, no clock reads. Same row →
+ same output. Pivot URLs use the same `?entity=…` query the
+ AttackGraphView already parses, so the rail "just works" when
+ the analyst clicks through.
+ """
+ bucket = _EntityBucket.empty()
+ raw_event = alert.raw_event if isinstance(alert.raw_event, dict) else {}
+ enrichment = alert.enrichment_data if isinstance(alert.enrichment_data, dict) else {}
+
+ # ── Principal ───────────────────────────────────────────────────────
+ # Hosts and users an analyst would isolate / disable. We promote
+ # the denormalised columns first, then mine the raw event blob
+ # for fields the connector didn't curate into a top-level column.
+ for host in _dedup_strs(alert.affected_hosts or ()):
+ bucket.add(
+ group="principal",
+ kind="host",
+ value=host,
+ pivot=f"/attack-graph?entity=host:{host}",
+ )
+ for user in _dedup_strs(alert.affected_users or ()):
+ bucket.add(
+ group="principal",
+ kind="user",
+ value=user,
+ pivot=f"/attack-graph?entity=user:{user}",
+ )
+ for asset in _dedup_strs(alert.affected_assets or ()):
+ bucket.add(
+ group="principal",
+ kind="asset",
+ value=asset,
+ pivot=f"/attack-graph?entity=asset:{asset}",
+ )
+
+ # ── Network ─────────────────────────────────────────────────────────
+ for ip in _dedup_strs(alert.affected_ips or ()):
+ bucket.add(
+ group="network",
+ kind="ip",
+ value=ip,
+ pivot=f"/attack-graph?entity=ip:{ip}",
+ )
+ dst_ip = _from_blob(raw_event, ("dst_ip", "destination_ip", "remote_ip"))
+ if dst_ip:
+ bucket.add(
+ group="network",
+ kind="ip",
+ value=dst_ip,
+ label="destination",
+ pivot=f"/attack-graph?entity=ip:{dst_ip}",
+ )
+ domain = _from_blob(raw_event, ("domain", "target_domain", "host_domain"))
+ if domain:
+ bucket.add(
+ group="network",
+ kind="domain",
+ value=domain,
+ pivot=f"/attack-graph?entity=domain:{domain}",
+ )
+ url = _from_blob(raw_event, ("url", "request_url", "uri"))
+ if url:
+ bucket.add(group="network", kind="url", value=url)
+
+ # ── Workflow ────────────────────────────────────────────────────────
+ # The "what" of the alert — rule name, MITRE coverage, tags that
+ # describe the detection logic. These pivot into detection
+ # tuning / coverage explorers rather than the entity graph.
+ rule_name = _from_blob(raw_event, ("rule_name", "rule", "detection")) or alert.connector_type
+ if rule_name:
+ bucket.add(group="workflow", kind="rule", value=rule_name)
+ for tactic_obj in alert.mitre_tactics or ():
+ if isinstance(tactic_obj, str):
+ name = _norm_str(tactic_obj)
+ if name:
+ bucket.add(group="workflow", kind="mitre_tactic", value=name)
+ elif isinstance(tactic_obj, dict):
+ tid = _norm_str(tactic_obj.get("id"))
+ tname = _norm_str(tactic_obj.get("name"))
+ display = tid or tname
+ if display:
+ bucket.add(
+ group="workflow",
+ kind="mitre_tactic",
+ value=display,
+ label=tname if (tname and tid) else None,
+ )
+ for tech_obj in alert.mitre_techniques or ():
+ if isinstance(tech_obj, str):
+ name = _norm_str(tech_obj)
+ if name:
+ bucket.add(group="workflow", kind="mitre_technique", value=name)
+ elif isinstance(tech_obj, dict):
+ tid = _norm_str(tech_obj.get("id") or tech_obj.get("technique_id"))
+ tname = _norm_str(tech_obj.get("name") or tech_obj.get("technique"))
+ display = tid or tname
+ if display:
+ bucket.add(
+ group="workflow",
+ kind="mitre_technique",
+ value=display,
+ label=tname if (tname and tid) else None,
+ pivot=f"/detection/tuning?technique={tid}" if tid else None,
+ )
+
+ # ── Tenant ──────────────────────────────────────────────────────────
+ # Workspace / org-level pivots. The connector type lives here
+ # because "which data source did this fire on" is an
+ # organisational question, not a workflow one.
+ if alert.connector_type:
+ bucket.add(group="tenant", kind="connector", value=alert.connector_type)
+ if alert.case_id is not None:
+ bucket.add(
+ group="tenant",
+ kind="case",
+ value=str(alert.case_id),
+ pivot=f"/cases/{alert.case_id}",
+ )
+ # RBA promotion entity surfaces *which* identity drove this alert
+ # over its risk threshold — show it as a tenant-level pivot so
+ # analysts can navigate to the entity risk queue.
+ rba_block = enrichment.get("rba_top_promotion") if isinstance(enrichment, dict) else None
+ if isinstance(rba_block, dict):
+ rba_entity = _norm_str(rba_block.get("entity"))
+ if rba_entity:
+ bucket.add(
+ group="tenant",
+ kind="rba_entity",
+ value=rba_entity,
+ label="risk promotion",
+ pivot=f"/alerts?view=entities&entity={rba_entity}",
+ )
+
+ return bucket.entities
+
+
+# ─── Mini timeline ───────────────────────────────────────────────────────────
+
+
+def _audit_event(row: AuditLog) -> MiniTimelineEvent:
+ """Project an ``AuditLog`` row into the rail's timeline shape."""
+ payload: dict[str, Any] | None = None
+ if isinstance(row.changes, dict) and row.changes:
+ payload = dict(row.changes)
+ elif isinstance(row.metadata_, dict) and row.metadata_:
+ payload = dict(row.metadata_)
+ actor = row.actor_email or (str(row.actor_id) if row.actor_id else "system")
+ return MiniTimelineEvent(
+ id=str(row.id),
+ ts=row.created_at,
+ kind=row.action or "audit",
+ agent=actor,
+ summary=_summarise_audit(row),
+ payload=payload,
+ )
+
+
+def _summarise_audit(row: AuditLog) -> str:
+ """One-line audit summary that reads in the rail without payload exposure.
+
+ Audit rows are intentionally low-fidelity — they describe *what
+ happened*, not *why*. The rail's audience is a human analyst, so
+ we render a compact action-on-resource line and let the user click
+ through to the full ledger / case timeline for richer detail.
+ """
+ action = row.action or "audit"
+ if row.resource:
+ return f"{action} on {row.resource}".strip()
+ return action
+
+
+def _case_event(row: CaseTimeline) -> MiniTimelineEvent:
+ """Project a ``CaseTimeline`` row into the rail's timeline shape."""
+ actor = "system" if row.is_automated else (str(row.user_id) if row.user_id else "system")
+ payload: dict[str, Any] | None = None
+ if isinstance(row.event_metadata, dict) and row.event_metadata:
+ payload = dict(row.event_metadata)
+ return MiniTimelineEvent(
+ id=str(row.id),
+ ts=row.created_at,
+ kind=row.event_type or "case_event",
+ agent=actor,
+ summary=row.content or row.event_type or "case event",
+ payload=payload,
+ )
+
+
+async def build_mini_timeline(
+ db: AsyncSession,
+ alert: Alert,
+ *,
+ limit: int = MAX_TIMELINE_EVENTS,
+) -> list[MiniTimelineEvent]:
+ """Assemble the rail's mini-timeline for a single alert.
+
+ Sources, in priority order:
+
+ 1. ``CaseTimeline`` rows for the alert's case (if any) — these are
+ the richest because they include analyst comments and agent
+ turn-by-turn decisions.
+ 2. ``AuditLog`` rows whose ``resource == 'alert'`` and
+ ``resource_id == str(alert.id)`` — covers status/assignment
+ changes that don't go through a case.
+
+ Both feeds are merged, sorted newest-first, and capped at
+ ``limit``. The function is read-only and tenant-scoped at the
+ query level (case timeline already filters by case → tenant; audit
+ log we filter by ``tenant_id == alert.tenant_id`` defensively).
+ """
+ events: list[MiniTimelineEvent] = []
+
+ # ── Case timeline ───────────────────────────────────────────────────
+ if alert.case_id is not None:
+ case_q = select(CaseTimeline).where(CaseTimeline.case_id == alert.case_id).order_by(CaseTimeline.created_at.desc()).limit(limit)
+ case_rows = (await db.execute(case_q)).scalars().all()
+ events.extend(_case_event(row) for row in case_rows)
+
+ # ── Audit log ───────────────────────────────────────────────────────
+ # We query a slightly larger window so the merge step has enough
+ # rows to satisfy ``limit`` after we've already inserted case
+ # events. The audit table is indexed on (tenant_id, created_at),
+ # so this is cheap.
+ audit_q = (
+ select(AuditLog)
+ .where(
+ AuditLog.tenant_id == alert.tenant_id,
+ AuditLog.resource == "alert",
+ AuditLog.resource_id == str(alert.id),
+ )
+ .order_by(AuditLog.created_at.desc())
+ .limit(limit)
+ )
+ audit_rows = (await db.execute(audit_q)).scalars().all()
+ events.extend(_audit_event(row) for row in audit_rows)
+
+ # ── Merge + cap ─────────────────────────────────────────────────────
+ events.sort(key=lambda e: e.ts, reverse=True)
+ return events[:limit]
+
+
+# ─── Recommended actions ─────────────────────────────────────────────────────
+
+
+def build_recommended_actions(alert: Alert) -> list[RecommendedAction]:
+ """Normalise ``Alert.ai_recommendations`` for rendering in the rail.
+
+ The ResponderAgent emits a list of dicts of the form::
+
+ {"priority": 1, "action": "Isolate host …", "rationale": "…", "risk": "high"}
+
+ Older demo seeds wrote a list of bare strings. We accept both and
+ drop everything else (silently — the rail isn't the right surface
+ to surface a schema error). When no actions are present the rail
+ falls back to the analyst's own playbook.
+ """
+ raw = alert.ai_recommendations
+ if not isinstance(raw, list):
+ return []
+ out: list[RecommendedAction] = []
+ for idx, item in enumerate(raw):
+ if isinstance(item, str):
+ text = _norm_str(item)
+ if not text:
+ continue
+ out.append(RecommendedAction(priority=idx + 1, action=text))
+ continue
+ if not isinstance(item, dict):
+ continue
+ action = _norm_str(item.get("action"))
+ if not action:
+ continue
+ try:
+ priority = int(item.get("priority", idx + 1))
+ except (TypeError, ValueError):
+ priority = idx + 1
+ if priority < 1:
+ priority = 1
+ risk = _norm_str(item.get("risk")) or "low"
+ if risk.lower() not in {"low", "medium", "high"}:
+ risk = "low"
+ rationale = _norm_str(item.get("rationale"))
+ out.append(
+ RecommendedAction(
+ priority=priority,
+ action=action,
+ rationale=rationale,
+ risk=risk.lower(),
+ )
+ )
+ # Stable sort by priority so the rail renders in the order the
+ # agent intended even when sources are mixed.
+ out.sort(key=lambda a: a.priority)
+ return out
+
+
+# ─── Convenience composite ───────────────────────────────────────────────────
+
+
+class RailEnvelope(BaseModel):
+ """Composite payload returned alongside the alert detail response."""
+
+ related_entities: list[RelatedEntity]
+ mini_timeline: list[MiniTimelineEvent]
+ recommended_actions: list[RecommendedAction]
+
+
+async def build_rail_envelope(db: AsyncSession, alert: Alert) -> RailEnvelope:
+ """Build the full rail envelope in a single helper.
+
+ Convenience wrapper for the alerts endpoint — avoids the caller
+ having to import three symbols. Keeping it tiny so each subroutine
+ stays individually unit-testable.
+ """
+ return RailEnvelope(
+ related_entities=build_related_entities(alert),
+ mini_timeline=await build_mini_timeline(db, alert),
+ recommended_actions=build_recommended_actions(alert),
+ )
+
+
+__all__ = [
+ "MAX_TIMELINE_EVENTS",
+ "MiniTimelineEvent",
+ "RailEnvelope",
+ "RecommendedAction",
+ "RelatedEntity",
+ "build_mini_timeline",
+ "build_rail_envelope",
+ "build_recommended_actions",
+ "build_related_entities",
+]
diff --git a/services/api/app/services/narrative_loader.py b/services/api/app/services/narrative_loader.py
new file mode 100644
index 000000000..bf3939220
--- /dev/null
+++ b/services/api/app/services/narrative_loader.py
@@ -0,0 +1,141 @@
+"""Dynamic loader for the correlation-narrative builder.
+
+The narrative builder lives canonically in
+``services/fusion/app/services/narrative.py`` and is consumed by both:
+
+* the **fusion service**, at fusion time, to populate
+ ``FusedAlert.narrative`` deterministically before publishing the alert to
+ Kafka; and
+* the **API service**, lazily, when ``GET /alerts/{id}`` is asked for an
+ alert whose ``narrative`` column is still ``NULL`` (e.g. legacy rows that
+ were fused before the column existed).
+
+Because the ``aisoc-api`` Docker image is built with ``services/api`` as its
+build context, anything under ``services/fusion`` is **not** available at
+runtime. ``scripts/sync_vendored_narrative.py`` byte-mirrors the source file
+into ``services/api/app/_vendor/narrative.py``; CI fails the build if the two
+files drift.
+
+This module loads that vendored file under a collision-free name
+(``aisoc_fusion_narrative``) so it does not interfere with anything else in
+the ``app`` package. It also falls back to the source-of-truth file at
+``services/fusion/app/services/narrative.py`` for local development where
+the API runs outside of Docker against a checked-out monorepo.
+
+Public re-exports (one-to-one with ``narrative.py``):
+
+* :data:`build_narrative` — pure function ``(NarrativeInputs) -> str``.
+* :class:`NarrativeInputs` — dataclass of all builder inputs.
+* :class:`NarrativeFactor` — single confidence-factor entry inside
+ ``NarrativeInputs.confidence_factors``.
+
+Determinism guarantee
+---------------------
+``build_narrative`` is a pure, deterministic function. Calling it twice with
+the same ``NarrativeInputs`` returns the same byte-for-byte string. The
+caller (the alerts endpoint) safely persists the result on the row so we
+only pay the build cost once per alert.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+from pathlib import Path
+from types import ModuleType
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ # Static-only re-export so type checkers can see the dataclass fields and
+ # function signature. At runtime we load the module dynamically (see
+ # ``_load_narrative_module`` below) to avoid colliding with any other
+ # ``narrative`` module in the API service.
+ from services.fusion.app.services.narrative import ( # noqa: F401
+ NarrativeFactor,
+ NarrativeInputs,
+ build_narrative,
+ )
+
+
+_MODULE_NAME = "aisoc_fusion_narrative"
+
+
+def _candidate_narrative_files() -> list[Path]:
+ """Return ordered list of files that may contain the narrative module.
+
+ The first entry is the in-tree vendored copy under
+ ``services/api/app/_vendor/narrative.py`` — this is what ships inside
+ the ``aisoc-api`` Docker image. The second entry is the source-of-truth
+ file at ``services/fusion/app/services/narrative.py``, used during local
+ development when the API runs outside of Docker.
+ """
+ here = Path(__file__).resolve()
+ candidates: list[Path] = []
+
+ # 1) Vendored copy — lives at ``<api-app-root>/_vendor/narrative.py``.
+ # parents[2] resolves to the ``app`` directory: services → app.
+ try:
+ api_app_root = here.parents[1]
+ vendored = api_app_root / "_vendor" / "narrative.py"
+ if vendored.is_file():
+ candidates.append(vendored)
+ except IndexError: # pragma: no cover - defensive
+ pass
+
+ # 2) Source-of-truth file — walk up the repo until we find it.
+ for ancestor in here.parents:
+ source = ancestor / "services" / "fusion" / "app" / "services" / "narrative.py"
+ if source.is_file():
+ candidates.append(source)
+ break
+
+ return candidates
+
+
+def _load_narrative_module() -> ModuleType:
+ """Load the narrative builder under a collision-free module name.
+
+ Prefers the in-tree vendored copy (so the module is available inside the
+ Dockerized ``aisoc-api`` service whose build context excludes
+ ``services/fusion``) and falls back to the source-of-truth file at
+ ``services/fusion/app/services/narrative.py`` for local non-Docker
+ development.
+ """
+ if _MODULE_NAME in sys.modules:
+ return sys.modules[_MODULE_NAME]
+
+ candidates = _candidate_narrative_files()
+ if not candidates:
+ raise ImportError(
+ "Correlation-narrative module not found — expected either "
+ "services/api/app/_vendor/narrative.py (vendored) or "
+ "services/fusion/app/services/narrative.py (source). Run "
+ "`python scripts/sync_vendored_narrative.py` to regenerate the "
+ "vendored copy."
+ )
+
+ narrative_file = candidates[0]
+ spec = importlib.util.spec_from_file_location(_MODULE_NAME, narrative_file)
+ if spec is None or spec.loader is None: # pragma: no cover - defensive
+ raise ImportError(f"Could not build spec for {narrative_file}")
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[_MODULE_NAME] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+_narrative = _load_narrative_module()
+
+# Re-export the public API at module scope so callers can write
+# ``from app.services.narrative_loader import build_narrative`` instead of
+# fishing through the dynamically loaded module.
+if not TYPE_CHECKING:
+ build_narrative = _narrative.build_narrative
+ NarrativeInputs = _narrative.NarrativeInputs
+ NarrativeFactor = _narrative.NarrativeFactor
+
+
+__all__ = ["NarrativeFactor", "NarrativeInputs", "build_narrative"]
diff --git a/services/api/app/services/narrative_projection.py b/services/api/app/services/narrative_projection.py
new file mode 100644
index 000000000..9323f912a
--- /dev/null
+++ b/services/api/app/services/narrative_projection.py
@@ -0,0 +1,267 @@
+"""Project an ORM ``Alert`` row into ``NarrativeInputs``.
+
+The fusion service constructs ``NarrativeInputs`` from its native
+``FusedAlert`` Pydantic model at fusion time (see
+``services/fusion/app/services/fusion_engine.py::_to_narrative_inputs``).
+The API service can't reuse that adapter — it never sees ``FusedAlert``;
+it only ever sees the ORM ``Alert`` row that fusion already persisted.
+
+This module is the API's counterpart. It pulls every input the narrative
+builder needs out of:
+
+* the ``Alert`` row itself (``severity``, ``title``, ``confidence``,
+ ``confidence_label``, ``confidence_rationale``, ``mitre_tactics``,
+ ``mitre_techniques``, ``tags``, ``case_id``);
+* the denormalised entity columns (``affected_ips``, ``affected_hosts``,
+ ``affected_users``); and
+* the ``raw_event`` / ``enrichment_data`` JSONB blobs for everything the
+ flat columns don't carry (``dst_ip``, ``file_hash``, ``domain``,
+ ``url``, RBA promotion, ``exploit_in_wild``).
+
+We're deliberately conservative: any field that can't be pulled cleanly
+stays ``None`` and the narrative builder skips that signal — it is
+designed to degrade gracefully.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import Any
+
+from app.models.alert import Alert
+from app.services.narrative_loader import NarrativeFactor, NarrativeInputs
+
+# ─── Helpers ─────────────────────────────────────────────────────────────────
+
+
+_VALID_SEVERITIES = {"critical", "high", "medium", "low", "info"}
+_VALID_BANDS = {"high", "medium", "low"}
+
+
+def _first_str(values: Iterable[Any]) -> str | None:
+ """Return the first non-empty trimmed string from ``values``, else None."""
+ for value in values:
+ if isinstance(value, str):
+ stripped = value.strip()
+ if stripped:
+ return stripped
+ return None
+
+
+def _from_blob(blob: Any, keys: Iterable[str]) -> str | None:
+ """Pull the first non-empty string at any of ``keys`` from a JSONB blob.
+
+ Accepts a ``dict`` (the usual case) and silently returns ``None`` for
+ anything else, including the empty default ``{}``. We never raise —
+ the JSONB shape varies wildly across connectors and the narrative is
+ expected to degrade gracefully when a signal isn't present.
+ """
+ if not isinstance(blob, dict):
+ return None
+ for key in keys:
+ value = blob.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return None
+
+
+def _mitre_names(items: Any) -> tuple[str, ...]:
+ """Normalise a JSONB MITRE list into a tuple of bare names.
+
+ The fusion service stores MITRE coverage as either ``["execution",
+ …]`` or ``[{"name": "execution", "id": "TA0002"}, …]`` depending on
+ the connector. The narrative builder only needs the kebab-case name
+ so we flatten both shapes here.
+ """
+ if not isinstance(items, list):
+ return ()
+ out: list[str] = []
+ for item in items:
+ if isinstance(item, str):
+ stripped = item.strip()
+ if stripped:
+ out.append(stripped)
+ elif isinstance(item, dict):
+ name = item.get("name") or item.get("id")
+ if isinstance(name, str) and name.strip():
+ out.append(name.strip())
+ return tuple(out)
+
+
+def _rationale_factors(rationale: Any) -> tuple[NarrativeFactor, ...]:
+ """Project the JSONB confidence rationale into ``NarrativeFactor`` rows.
+
+ The fusion service stores the rationale as a list of dicts with the
+ shape ``{"factor": "severity", "label": "…", "value": "…",
+ "contribution": 0.4, "weight": 0.25}``. The narrative builder only
+ consumes ``label``, ``value``, ``contribution``, and ``weight`` so
+ we silently drop unrecognised entries.
+ """
+ if not isinstance(rationale, list):
+ return ()
+ factors: list[NarrativeFactor] = []
+ for row in rationale:
+ if not isinstance(row, dict):
+ continue
+ label = row.get("label")
+ value = row.get("value")
+ contribution = row.get("contribution")
+ weight = row.get("weight")
+ if not isinstance(label, str) or not isinstance(value, str):
+ continue
+ try:
+ contribution_f = float(contribution) if contribution is not None else 0.0
+ weight_f = float(weight) if weight is not None else 0.0
+ except (TypeError, ValueError):
+ continue
+ factors.append(
+ NarrativeFactor(
+ label=label,
+ value=value,
+ contribution=contribution_f,
+ weight=weight_f,
+ )
+ )
+ return tuple(factors)
+
+
+def _rba_promotion(enrichment: Any) -> tuple[str | None, float | None]:
+ """Extract the RBA top-promotion entity + score from enrichment_data.
+
+ The fusion service writes a small ``rba_top_promotion`` block into
+ ``enrichment_data`` when the alert tipped an entity's score above
+ its risk threshold. Shape::
+
+ {
+ "rba_top_promotion": {
+ "entity": "host:web-01",
+ "score": 78.3,
+ }
+ }
+
+ Any other shape returns ``(None, None)`` so the narrative builder
+ simply skips the RBA mention.
+ """
+ if not isinstance(enrichment, dict):
+ return None, None
+ rba = enrichment.get("rba_top_promotion") or enrichment.get("rba")
+ if not isinstance(rba, dict):
+ return None, None
+ entity = rba.get("entity")
+ score = rba.get("score")
+ if not isinstance(entity, str) or not entity.strip():
+ entity = None
+ if isinstance(score, (int, float)):
+ score_f: float | None = float(score)
+ else:
+ score_f = None
+ return (entity or None), score_f
+
+
+def _exploit_in_wild(alert: Alert) -> bool:
+ """True iff the alert touches an asset vulnerability marked exploited.
+
+ Surfaced via the ``exploit_in_wild`` flag on ``enrichment_data`` (set
+ by ``services/fusion/app/services/vuln_boost.py``) or the
+ ``exploit-in-wild`` tag. We accept either shape so the narrative
+ keeps working if vuln_boost evolves.
+ """
+ if isinstance(alert.enrichment_data, dict):
+ flag = alert.enrichment_data.get("exploit_in_wild")
+ if isinstance(flag, bool) and flag:
+ return True
+ for tag in alert.tags or ():
+ if isinstance(tag, str) and tag.lower() in {"exploit-in-wild", "exploit_in_wild"}:
+ return True
+ return False
+
+
+def _correlation_decision(alert: Alert) -> str | None:
+ """Return ``correlated`` if the alert is attached to a case, else ``None``.
+
+ The API doesn't preserve the original ``FusionDecision`` enum (DUPLICATE
+ rows never reach the alerts table; NEW_INCIDENT and CORRELATED are
+ both surfaced as alerts with a ``case_id``). For the narrative's
+ "Correlated activity" block we only need to know that *some*
+ incident grouping happened — the prose itself reads naturally in
+ both directions.
+ """
+ if alert.case_id is not None:
+ return "correlated"
+ return None
+
+
+# ─── Public API ──────────────────────────────────────────────────────────────
+
+
+def project_alert_to_narrative_inputs(alert: Alert) -> NarrativeInputs:
+ """Build a ``NarrativeInputs`` dataclass from an ORM ``Alert`` row.
+
+ The function is pure: same row → same output. It performs no I/O.
+ Callers (the alerts endpoint's lazy-fill path) feed the result to
+ :func:`app.services.narrative_loader.build_narrative` and persist
+ the returned string back to ``alert.narrative``.
+ """
+ raw_event = alert.raw_event if isinstance(alert.raw_event, dict) else {}
+ enrichment = alert.enrichment_data if isinstance(alert.enrichment_data, dict) else {}
+
+ # Severity / confidence_label are stored lower-case by the fusion
+ # service but the API is permissive about case. Normalise here so
+ # the narrative builder's Literal type-hints are honoured.
+ severity = (alert.severity or "info").lower()
+ if severity not in _VALID_SEVERITIES:
+ severity = "info"
+ confidence_label = alert.confidence_label.lower() if alert.confidence_label else None
+ if confidence_label is not None and confidence_label not in _VALID_BANDS:
+ confidence_label = None
+
+ # Entity precedence — prefer the denormalised columns (which the
+ # fusion service curated at correlation time) and fall back to the
+ # raw event blob for shapes we don't promote to first-class columns.
+ src_ip = _first_str(alert.affected_ips or ()) or _from_blob(raw_event, ("src_ip", "source_ip", "client_ip"))
+ dst_ip = _from_blob(raw_event, ("dst_ip", "destination_ip", "remote_ip"))
+ hostname = _first_str(alert.affected_hosts or ()) or _from_blob(
+ raw_event, ("host", "hostname", "device_name", "device", "computer_name")
+ )
+ username = _first_str(alert.affected_users or ()) or _from_blob(raw_event, ("user", "username", "user_name", "account_name", "account"))
+ file_hash = _from_blob(raw_event, ("file_hash", "sha256", "sha1", "md5", "hash"))
+ domain = _from_blob(raw_event, ("domain", "target_domain", "host_domain"))
+ url = _from_blob(raw_event, ("url", "request_url", "uri"))
+
+ source = alert.connector_type or _from_blob(raw_event, ("source", "connector", "vendor"))
+
+ rba_entity, rba_score = _rba_promotion(enrichment)
+
+ return NarrativeInputs(
+ severity=severity, # type: ignore[arg-type]
+ title=alert.title,
+ confidence=alert.confidence,
+ confidence_label=confidence_label, # type: ignore[arg-type]
+ rationale=_rationale_factors(alert.confidence_rationale),
+ src_ip=src_ip,
+ dst_ip=dst_ip,
+ hostname=hostname,
+ username=username,
+ file_hash=file_hash,
+ domain=domain,
+ url=url,
+ mitre_tactics=_mitre_names(alert.mitre_tactics),
+ mitre_techniques=_mitre_names(alert.mitre_techniques),
+ # The API can't recompute the incident's total alert count
+ # without an extra query. The narrative gracefully omits the
+ # "n alerts on this incident" suffix when this is None, which
+ # is the right behaviour for the lazy-fill path.
+ incident_alert_count=None,
+ correlation_decision=_correlation_decision(alert),
+ rba_entity=rba_entity,
+ rba_score=rba_score,
+ exploit_in_wild=_exploit_in_wild(alert),
+ source=source,
+ tags=tuple(t for t in (alert.tags or ()) if isinstance(t, str)),
+ )
+
+
+__all__ = ["project_alert_to_narrative_inputs"]
diff --git a/services/api/migrations/041_alert_correlation_narrative.sql b/services/api/migrations/041_alert_correlation_narrative.sql
new file mode 100644
index 000000000..d75d72f5b
--- /dev/null
+++ b/services/api/migrations/041_alert_correlation_narrative.sql
@@ -0,0 +1,32 @@
+-- Migration 041: SOC console parity — alert correlation narrative
+-- Implements W6 (structured InvestigationRail) from the v1.5 SOC Console
+-- Parity plan.
+--
+-- Changes:
+-- alerts.narrative (TEXT, nullable) — a deterministic, human-readable
+-- correlation narrative cached on the alert. Generated by the fusion
+-- service at correlate-time and refreshed by the API at read-time when
+-- missing or stale. The InvestigationRail surfaces this verbatim so the
+-- right pane renders instantly without an LLM round-trip; the
+-- on-demand `ExplainDrawer` (renamed "Deep Explain" in the rail) still
+-- provides the streaming LLM explanation when an analyst wants more.
+--
+-- Backfill: leave narrative NULL on existing rows. The API layer will
+-- compute and cache narrative lazily on first read of an alert, so
+-- legacy rows pick it up the moment an analyst opens them.
+--
+-- Idempotent — safe to re-run.
+
+BEGIN;
+
+ALTER TABLE alerts
+ ADD COLUMN IF NOT EXISTS narrative TEXT;
+
+COMMENT ON COLUMN alerts.narrative IS
+ 'Deterministic correlation narrative cached at fusion time. '
+ 'NULL means "not yet computed"; the API will lazily compute and '
+ 'persist on first read of the alert. Surfaced verbatim by the '
+ 'InvestigationRail. For the streaming LLM explanation, see the '
+ 'Deep Explain action which goes through /api/v1/alerts/{id}/explain.';
+
+COMMIT;
diff --git a/services/api/tests/api/v1/endpoints/test_alerts_detail_envelope.py b/services/api/tests/api/v1/endpoints/test_alerts_detail_envelope.py
new file mode 100644
index 000000000..b15a64c5c
--- /dev/null
+++ b/services/api/tests/api/v1/endpoints/test_alerts_detail_envelope.py
@@ -0,0 +1,663 @@
+"""Tests for ``GET /alerts/{id}`` — Investigation Rail envelope + lazy-fill.
+
+The detail endpoint is the only place in the API that emits the enriched
+``AlertDetailResponse`` shape that the /alerts Investigation Rail relies
+on (PR-4). These tests pin two contracts:
+
+1. **Schema** — ``AlertDetailResponse`` inherits every ``AlertResponse``
+ field, adds the four rail fields (``narrative``, ``related_entities``,
+ ``mini_timeline``, ``recommended_actions``) with sensible defaults,
+ and serialises in snake_case on the wire.
+
+2. **Lazy-fill** — When ``Alert.narrative`` is NULL (pre-W4 rows), the
+ endpoint materialises a narrative through the vendored builder,
+ persists it back to the row, and returns it. When the builder
+ raises we fall back to ``narrative=None`` rather than 500. When
+ the narrative is already cached we never call the builder.
+
+The endpoint is exercised by **direct function invocation** with mocked
+``AsyncSession`` and a synthesized ``CurrentUser`` — the same pattern
+``test_alert_explain.py`` uses for ``alert_explain``. This keeps the
+tests fast and hermetic; the FastAPI plumbing (auth, route binding) is
+covered by higher-level integration tests elsewhere.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.api.v1.deps import CurrentUser
+from app.api.v1.endpoints.alerts import (
+ AlertDetailResponse,
+ AlertResponse,
+ get_alert,
+)
+from app.services.alert_rail import (
+ MiniTimelineEvent,
+ RailEnvelope,
+ RecommendedAction,
+ RelatedEntity,
+)
+from fastapi import HTTPException
+from pydantic import ValidationError
+
+# ─── Schema-only payload helper ──────────────────────────────────────────────
+
+
+def _alert_payload(**overrides: Any) -> dict[str, Any]:
+ """Minimum-viable ``AlertResponse``-shaped dict.
+
+ Mirrors ``test_alerts_confidence_contract._make_alert_payload`` so
+ the two contract suites stay aligned as ``AlertResponse`` evolves.
+ """
+ now = datetime.now(UTC)
+ base: dict[str, Any] = {
+ "id": uuid.uuid4(),
+ "tenant_id": uuid.uuid4(),
+ "title": "Suspicious Login",
+ "description": None,
+ "severity": "medium",
+ "status": "new",
+ "priority": 50,
+ "category": None,
+ "mitre_tactics": [],
+ "mitre_techniques": [],
+ "connector_type": None,
+ "ai_score": None,
+ "ai_summary": None,
+ "ai_recommendations": [],
+ "confidence": None,
+ "confidence_label": None,
+ "confidence_rationale": None,
+ "disposition": None,
+ "affected_ips": [],
+ "affected_hosts": [],
+ "affected_users": [],
+ "case_id": None,
+ "tags": [],
+ "event_time": now,
+ "first_seen": now,
+ "last_seen": now,
+ "snoozed_until": None,
+ "snoozed_by_id": None,
+ "created_at": now,
+ "updated_at": now,
+ }
+ base.update(overrides)
+ return base
+
+
+# ─── ORM stand-in + mock session helpers ─────────────────────────────────────
+
+
+def _orm_alert(**overrides: Any) -> SimpleNamespace:
+ """Build a SimpleNamespace stand-in for the SQLAlchemy ``Alert`` row.
+
+ The endpoint accesses ``alert.id``, ``alert.tenant_id``,
+ ``alert.narrative``, plus everything the rail builders read off the
+ row. We populate the union of those attributes so projection,
+ rail assembly, and ``model_validate(alert)`` all succeed.
+ """
+ now = datetime.now(UTC)
+ base: dict[str, Any] = {
+ "id": uuid.uuid4(),
+ "tenant_id": uuid.uuid4(),
+ "title": "Suspicious Login",
+ "description": None,
+ "severity": "medium",
+ "status": "new",
+ "priority": 50,
+ "category": None,
+ "mitre_tactics": [],
+ "mitre_techniques": [],
+ "connector_type": None,
+ "ai_score": None,
+ "ai_summary": None,
+ "ai_recommendations": [],
+ "confidence": None,
+ "confidence_label": None,
+ "confidence_rationale": None,
+ "disposition": None,
+ "affected_ips": [],
+ "affected_hosts": [],
+ "affected_users": [],
+ "affected_assets": [],
+ "case_id": None,
+ "tags": [],
+ "event_time": now,
+ "first_seen": now,
+ "last_seen": now,
+ "snoozed_until": None,
+ "snoozed_by_id": None,
+ "created_at": now,
+ "updated_at": now,
+ "narrative": None,
+ "raw_event": {},
+ "enrichment_data": {},
+ "rule_lineage_id": None,
+ "fingerprint": None,
+ }
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+
+def _mock_user(tenant_id: uuid.UUID) -> CurrentUser:
+ """Synthesize a ``CurrentUser`` scoped to ``tenant_id``."""
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=tenant_id,
+ role="analyst",
+ )
+
+
+def _mock_session(*, alert: Any) -> MagicMock:
+ """Build a mock ``AsyncSession`` whose execute chain returns ``alert``.
+
+ The detail endpoint issues up to three SELECTs/UPDATEs:
+
+ 1. ``SELECT Alert WHERE id=?`` — must return the alert
+ 2. Optional ``UPDATE Alert SET narrative=…`` — return value unused
+ 3. Inside ``build_rail_envelope``:
+ * optional ``SELECT CaseTimeline …`` (when ``alert.case_id``)
+ * ``SELECT AuditLog …``
+
+ We funnel every ``execute`` through one ``AsyncMock``. The first
+ call returns a "scalar_one_or_none"-ready result holding the
+ alert; subsequent calls return empty results so the rail assembler
+ sees no extra rows. Tests that need richer rail data can replace
+ ``session.execute.side_effect`` after construction.
+ """
+ # First call: scalar_one_or_none() → alert
+ alert_result = MagicMock()
+ alert_result.scalar_one_or_none.return_value = alert
+
+ # Subsequent calls: scalars().all() → []
+ empty_scalars = MagicMock()
+ empty_scalars.all.return_value = []
+ empty_result = MagicMock()
+ empty_result.scalars.return_value = empty_scalars
+ # We also need scalar_one_or_none() on the empty path in case the
+ # endpoint flow shifts; default to None so the test doesn't crash.
+ empty_result.scalar_one_or_none.return_value = None
+
+ session = MagicMock()
+ session.execute = AsyncMock(side_effect=[alert_result, empty_result, empty_result, empty_result])
+ session.commit = AsyncMock(return_value=None)
+ return session
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Section 1: AlertDetailResponse Pydantic contract
+# ────────────────────────────────────────────────────────────────────────────
+
+
+class TestAlertDetailResponseContract:
+ """``AlertDetailResponse`` is the wire format the rail UI reads."""
+
+ def test_inherits_every_alert_response_field(self) -> None:
+ """The detail shape must be a strict superset of the list shape.
+
+ The frontend's ``Alert`` interface unions both shapes; if a
+ column ever gets dropped here the list view keeps working while
+ detail crashes silently. This guard makes the bridge explicit.
+ """
+ list_fields = set(AlertResponse.model_fields)
+ detail_fields = set(AlertDetailResponse.model_fields)
+ # Inheritance: every list field MUST appear in detail.
+ missing = list_fields - detail_fields
+ assert not missing, f"AlertDetailResponse dropped fields: {missing}"
+
+ def test_adds_exactly_the_four_rail_fields(self) -> None:
+ """The four rail fields are the only thing detail adds.
+
+ If a refactor accidentally promotes another column into the
+ detail shape, the frontend's ``DetailAlert`` type union won't
+ know about it. Pin the diff so it's caught at PR review.
+ """
+ added = set(AlertDetailResponse.model_fields) - set(AlertResponse.model_fields)
+ assert added == {
+ "narrative",
+ "related_entities",
+ "mini_timeline",
+ "recommended_actions",
+ }
+
+ def test_defaults_are_safe_when_rail_fields_missing(self) -> None:
+ """A bare ``AlertResponse`` payload promotes cleanly to detail.
+
+ The lazy-fill path constructs the detail payload from a row that
+ has nothing rail-shaped on it. Defaults must be ``None`` for the
+ narrative and empty lists for the three collection fields so the
+ UI never has to null-check.
+ """
+ resp = AlertDetailResponse.model_validate(_alert_payload())
+ assert resp.narrative is None
+ assert resp.related_entities == []
+ assert resp.mini_timeline == []
+ assert resp.recommended_actions == []
+
+ def test_accepts_a_full_rail_envelope(self) -> None:
+ """The full rail payload (the happy path) round-trips."""
+ rail_payload = _alert_payload(
+ narrative="**hosts:** web-01\n\nMITRE T1078.",
+ related_entities=[
+ {
+ "group": "principal",
+ "kind": "host",
+ "value": "web-01",
+ "label": None,
+ "pivot": "/attack-graph?entity=host:web-01",
+ }
+ ],
+ mini_timeline=[
+ {
+ "id": "evt-1",
+ "ts": datetime.now(UTC),
+ "kind": "audit",
+ "agent": "[email protected]",
+ "summary": "status_change on alert",
+ "payload": {"status": ["new", "investigating"]},
+ "duration_ms": 0,
+ }
+ ],
+ recommended_actions=[
+ {
+ "priority": 1,
+ "action": "Isolate host",
+ "rationale": "Lateral movement",
+ "risk": "high",
+ }
+ ],
+ )
+ resp = AlertDetailResponse.model_validate(rail_payload)
+ assert resp.narrative.startswith("**hosts:**")
+ assert len(resp.related_entities) == 1
+ assert isinstance(resp.related_entities[0], RelatedEntity)
+ assert resp.related_entities[0].kind == "host"
+ assert len(resp.mini_timeline) == 1
+ assert isinstance(resp.mini_timeline[0], MiniTimelineEvent)
+ assert len(resp.recommended_actions) == 1
+ assert isinstance(resp.recommended_actions[0], RecommendedAction)
+ assert resp.recommended_actions[0].risk == "high"
+
+ def test_serialises_rail_fields_in_snake_case(self) -> None:
+ """The rail UI consumes snake_case on the wire and normalises FE-side.
+
+ ``apps/web/src/lib/api.ts`` has ``normalizeAlert`` which expects
+ ``related_entities`` / ``mini_timeline`` / ``recommended_actions``
+ on the wire. If anyone ever adds Pydantic ``alias=`` for camelCase
+ here, ``normalizeAlert`` needs to update in lockstep — this guard
+ forces that.
+ """
+ resp = AlertDetailResponse.model_validate(_alert_payload(narrative="x"))
+ dumped = resp.model_dump()
+ assert "narrative" in dumped
+ assert "related_entities" in dumped
+ assert "mini_timeline" in dumped
+ assert "recommended_actions" in dumped
+ # The camelCase variants must NOT be in the wire payload.
+ assert "relatedEntities" not in dumped
+ assert "miniTimeline" not in dumped
+ assert "recommendedActions" not in dumped
+
+ def test_rail_fields_validate_against_their_models(self) -> None:
+ """Garbage in the rail collections must raise rather than coerce.
+
+ Pydantic discriminated parsing means an invalid risk value, for
+ example, must blow up at the API boundary — not get silently
+ replaced with the default. The ``build_recommended_actions``
+ helper does the sanitising; the model just enforces the
+ sanitised contract.
+ """
+ with pytest.raises(ValidationError):
+ AlertDetailResponse.model_validate(
+ _alert_payload(
+ recommended_actions=[
+ {
+ "priority": 0, # ge=1 violated
+ "action": "x",
+ "risk": "low",
+ }
+ ],
+ )
+ )
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Section 2: get_alert endpoint behaviour
+# ────────────────────────────────────────────────────────────────────────────
+
+
+class TestGetAlertEndpoint:
+ """``get_alert`` is the only consumer of the rail builders.
+
+ All tests construct the dependencies by hand and ``await`` the
+ coroutine directly — the same pattern ``test_alert_explain.py``
+ uses. This bypasses the FastAPI dependency graph (auth, route
+ binding) which is covered by higher-level integration tests.
+ """
+
+ @pytest.mark.asyncio
+ async def test_returns_404_when_alert_missing(self) -> None:
+ tenant_id = uuid.uuid4()
+ user = _mock_user(tenant_id)
+
+ empty_result = MagicMock()
+ empty_result.scalar_one_or_none.return_value = None
+ session = MagicMock()
+ session.execute = AsyncMock(return_value=empty_result)
+ session.commit = AsyncMock()
+
+ with pytest.raises(HTTPException) as exc:
+ await get_alert(uuid.uuid4(), user, session)
+
+ assert exc.value.status_code == 404
+ # The narrative builder must NOT have been called.
+ assert session.commit.await_count == 0
+
+ @pytest.mark.asyncio
+ async def test_returns_envelope_with_existing_narrative_no_lazy_fill(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ """Pre-populated narrative is a fast path — builder never runs."""
+ tenant_id = uuid.uuid4()
+ alert = _orm_alert(tenant_id=tenant_id, narrative="**hosts:** web-01\n\nMITRE T1078.")
+ session = _mock_session(alert=alert)
+ user = _mock_user(tenant_id)
+
+ # If the builder were called we'd get a sentinel string;
+ # the assertion below would fail.
+ builder_calls: list[Any] = []
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.build_narrative",
+ lambda inputs: builder_calls.append(inputs) or "SHOULD_NEVER_BE_USED",
+ )
+
+ # Pin the rail envelope so we can assert on the response shape
+ # without re-testing the rail builders (covered in test_alert_rail).
+ envelope = RailEnvelope(
+ related_entities=[
+ RelatedEntity(
+ group="principal",
+ kind="host",
+ value="web-01",
+ label=None,
+ pivot="/attack-graph?entity=host:web-01",
+ )
+ ],
+ mini_timeline=[],
+ recommended_actions=[],
+ )
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.build_rail_envelope",
+ AsyncMock(return_value=envelope),
+ )
+
+ resp = await get_alert(alert.id, user, session)
+
+ assert isinstance(resp, AlertDetailResponse)
+ assert resp.narrative == "**hosts:** web-01\n\nMITRE T1078."
+ assert len(resp.related_entities) == 1
+ assert resp.related_entities[0].value == "web-01"
+ # Builder must NOT have been invoked.
+ assert builder_calls == []
+ # Commit must NOT have been invoked (no lazy-fill happened).
+ assert session.commit.await_count == 0
+
+ @pytest.mark.asyncio
+ async def test_lazy_fills_narrative_when_missing(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ """A legacy row (narrative is None) gets a freshly-built narrative.
+
+ We assert four things in one shot:
+ 1. ``build_narrative`` was called exactly once
+ 2. The result was assigned back to the in-memory row
+ 3. ``db.execute`` was invoked with an UPDATE (the second call)
+ 4. ``db.commit`` was awaited (so the lazy-fill persists)
+ """
+ tenant_id = uuid.uuid4()
+ alert = _orm_alert(tenant_id=tenant_id, narrative=None)
+ session = _mock_session(alert=alert)
+ user = _mock_user(tenant_id)
+
+ builder_calls: list[Any] = []
+
+ def fake_builder(inputs: Any) -> str:
+ builder_calls.append(inputs)
+ return "Generated narrative"
+
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.build_narrative",
+ fake_builder,
+ )
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.build_rail_envelope",
+ AsyncMock(
+ return_value=RailEnvelope(
+ related_entities=[],
+ mini_timeline=[],
+ recommended_actions=[],
+ )
+ ),
+ )
+
+ resp = await get_alert(alert.id, user, session)
+
+ assert resp.narrative == "Generated narrative"
+ # In-memory mutation so subsequent reads in the same request see
+ # the value (the endpoint reuses ``alert.narrative`` for the
+ # response payload).
+ assert alert.narrative == "Generated narrative"
+ # Builder fired exactly once.
+ assert len(builder_calls) == 1
+ # commit() awaited (so the lazy-fill is durable).
+ assert session.commit.await_count == 1
+ # Two execute calls: SELECT alert, then UPDATE narrative.
+ # (build_rail_envelope is mocked out.)
+ assert session.execute.await_count == 2
+
+ @pytest.mark.asyncio
+ async def test_does_not_persist_empty_narrative(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ """A builder returning empty text is a no-op — no UPDATE, no commit.
+
+ ``build_narrative`` can legitimately return ``""`` for an alert
+ with zero structured signal. We must not persist that empty
+ string back to the row (it'd shadow the next backfill attempt).
+ """
+ tenant_id = uuid.uuid4()
+ alert = _orm_alert(tenant_id=tenant_id, narrative=None)
+ session = _mock_session(alert=alert)
+ user = _mock_user(tenant_id)
+
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.build_narrative",
+ lambda inputs: "",
+ )
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.build_rail_envelope",
+ AsyncMock(
+ return_value=RailEnvelope(
+ related_entities=[],
+ mini_timeline=[],
+ recommended_actions=[],
+ )
+ ),
+ )
+
+ resp = await get_alert(alert.id, user, session)
+
+ assert resp.narrative is None
+ # Row stays clean — no shadow write.
+ assert alert.narrative is None
+ # commit() must NOT have been awaited.
+ assert session.commit.await_count == 0
+ # Only the SELECT happened.
+ assert session.execute.await_count == 1
+
+ @pytest.mark.asyncio
+ async def test_returns_alert_when_narrative_builder_raises(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ """A builder crash must NOT 500 the endpoint.
+
+ The frontend already handles ``narrative=null``. Failing soft
+ keeps the detail view useful even when something upstream
+ (vendoring, projection, MITRE map) is misbehaving.
+ """
+ tenant_id = uuid.uuid4()
+ alert = _orm_alert(tenant_id=tenant_id, narrative=None)
+ session = _mock_session(alert=alert)
+ user = _mock_user(tenant_id)
+
+ def explode(inputs: Any) -> str:
+ raise RuntimeError("builder is on fire")
+
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.build_narrative",
+ explode,
+ )
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.build_rail_envelope",
+ AsyncMock(
+ return_value=RailEnvelope(
+ related_entities=[],
+ mini_timeline=[],
+ recommended_actions=[],
+ )
+ ),
+ )
+
+ # The endpoint must return cleanly, not propagate the RuntimeError.
+ resp = await get_alert(alert.id, user, session)
+ assert resp.narrative is None
+ # And we did NOT commit a broken state.
+ assert session.commit.await_count == 0
+
+ @pytest.mark.asyncio
+ async def test_returns_alert_when_projection_raises(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ """Resilience also covers a projection failure (e.g. malformed JSONB)."""
+ tenant_id = uuid.uuid4()
+ alert = _orm_alert(tenant_id=tenant_id, narrative=None)
+ session = _mock_session(alert=alert)
+ user = _mock_user(tenant_id)
+
+ def explode(alert: Any) -> Any:
+ raise KeyError("missing column")
+
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.project_alert_to_narrative_inputs",
+ explode,
+ )
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.build_rail_envelope",
+ AsyncMock(
+ return_value=RailEnvelope(
+ related_entities=[],
+ mini_timeline=[],
+ recommended_actions=[],
+ )
+ ),
+ )
+
+ resp = await get_alert(alert.id, user, session)
+ assert resp.narrative is None
+ assert session.commit.await_count == 0
+
+ @pytest.mark.asyncio
+ async def test_response_includes_rail_envelope_data(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ """The full envelope from ``build_rail_envelope`` lands on the response."""
+ tenant_id = uuid.uuid4()
+ alert = _orm_alert(tenant_id=tenant_id, narrative="cached")
+ session = _mock_session(alert=alert)
+ user = _mock_user(tenant_id)
+
+ envelope = RailEnvelope(
+ related_entities=[
+ RelatedEntity(
+ group="network",
+ kind="ip",
+ value="10.0.0.1",
+ label=None,
+ pivot="/attack-graph?entity=ip:10.0.0.1",
+ ),
+ ],
+ mini_timeline=[
+ MiniTimelineEvent(
+ id="evt-1",
+ ts=datetime.now(UTC),
+ kind="audit",
+ agent="system",
+ summary="status_change on alert",
+ payload={"status": ["new", "investigating"]},
+ ),
+ ],
+ recommended_actions=[
+ RecommendedAction(
+ priority=1,
+ action="Block IP at edge",
+ rationale=None,
+ risk="medium",
+ ),
+ ],
+ )
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.alerts.build_rail_envelope",
+ AsyncMock(return_value=envelope),
+ )
+
+ resp = await get_alert(alert.id, user, session)
+
+ assert resp.narrative == "cached"
+ assert len(resp.related_entities) == 1
+ assert resp.related_entities[0].value == "10.0.0.1"
+ assert len(resp.mini_timeline) == 1
+ assert resp.mini_timeline[0].kind == "audit"
+ assert len(resp.recommended_actions) == 1
+ assert resp.recommended_actions[0].action == "Block IP at edge"
+
+ @pytest.mark.asyncio
+ async def test_tenant_isolation_enforced_via_query_filter(self) -> None:
+ """The endpoint queries with ``tenant_id == current_user.tenant_id``.
+
+ We can't see the SQL directly through the mock, but we can verify
+ the result-resolution sequence: if the alert tenant doesn't match,
+ the mock returns None and we 404. That's the same protection the
+ production SQL filter provides.
+ """
+ querying_tenant = uuid.uuid4()
+ user = _mock_user(querying_tenant)
+
+ # The session is configured to return None — simulating a row
+ # that exists but lives in a different tenant.
+ none_result = MagicMock()
+ none_result.scalar_one_or_none.return_value = None
+ session = MagicMock()
+ session.execute = AsyncMock(return_value=none_result)
+ session.commit = AsyncMock()
+
+ with pytest.raises(HTTPException) as exc:
+ await get_alert(uuid.uuid4(), user, session)
+
+ assert exc.value.status_code == 404
diff --git a/services/api/tests/services/test_alert_rail.py b/services/api/tests/services/test_alert_rail.py
new file mode 100644
index 000000000..35c5c5a98
--- /dev/null
+++ b/services/api/tests/services/test_alert_rail.py
@@ -0,0 +1,519 @@
+"""Unit tests for ``app.services.alert_rail``.
+
+The rail assembler has three pure helpers and one DB-touching helper:
+
+* ``build_related_entities`` — pure (Alert → list[RelatedEntity])
+* ``build_recommended_actions`` — pure (Alert → list[RecommendedAction])
+* ``build_mini_timeline`` — async, DB-bound (AsyncSession + Alert)
+* ``build_rail_envelope`` — composition of the three
+
+We test each one in isolation. Pure helpers use ``SimpleNamespace`` for
+the ORM row. The DB-bound one uses a ``MagicMock(AsyncSession)`` whose
+``execute`` returns canned rows — the same pattern the existing
+``test_alert_explain.py`` uses for ``_resolve_rule_lineage``.
+
+The contracts we're guarding:
+
+* dedup is case-insensitive but preserves first-seen casing,
+* every entity ends up in exactly one group,
+* whitespace-only strings are filtered,
+* MITRE coverage tolerates both bare-string and dict shapes,
+* the case timeline + audit log are merged and capped,
+* recommended actions accept both structured dicts AND legacy strings,
+* priority normalisation clamps to ``>= 1`` and risk to ``low|medium|high``.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.services.alert_rail import (
+ MAX_TIMELINE_EVENTS,
+ MiniTimelineEvent,
+ RailEnvelope,
+ RecommendedAction,
+ RelatedEntity,
+ build_mini_timeline,
+ build_rail_envelope,
+ build_recommended_actions,
+ build_related_entities,
+)
+from pydantic import ValidationError
+
+# ─── Helpers ─────────────────────────────────────────────────────────────────
+
+
+def _alert(**overrides: Any) -> SimpleNamespace:
+ base: dict[str, Any] = {
+ "id": uuid.uuid4(),
+ "tenant_id": uuid.uuid4(),
+ "severity": "high",
+ "title": "Suspicious authentication",
+ "connector_type": "okta",
+ "case_id": None,
+ "ai_recommendations": [],
+ "affected_ips": [],
+ "affected_hosts": [],
+ "affected_users": [],
+ "affected_assets": [],
+ "mitre_tactics": [],
+ "mitre_techniques": [],
+ "raw_event": {},
+ "enrichment_data": {},
+ }
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+
+def _mock_db_returning(*batches: list[Any]) -> MagicMock:
+ """Build a MagicMock(AsyncSession) whose ``execute`` returns canned rows.
+
+ Each ``batch`` corresponds to one ``await db.execute(...)`` call and
+ its scalars().all() result. The MagicMock has an ``AsyncMock``
+ ``execute`` so ``await`` works correctly.
+ """
+ db = MagicMock()
+ db.execute = AsyncMock()
+
+ results = []
+ for batch in batches:
+ scalars = MagicMock()
+ scalars.all.return_value = batch
+ result = MagicMock()
+ result.scalars.return_value = scalars
+ results.append(result)
+ db.execute.side_effect = results
+ return db
+
+
+# ─── build_related_entities ──────────────────────────────────────────────────
+
+
+class TestBuildRelatedEntities:
+ def test_returns_empty_list_for_bare_alert(self) -> None:
+ """A minimal alert with no entities, no MITRE, no case returns []."""
+ # The connector_type column is "okta" by default in our helper —
+ # the rail always emits a tenant chip when connector_type is set.
+ # We strip it to exercise the truly-empty path.
+ entities = build_related_entities(_alert(connector_type=None))
+ assert entities == []
+
+ def test_principal_group_includes_hosts_users_and_assets(self) -> None:
+ entities = build_related_entities(
+ _alert(
+ affected_hosts=["win-finance-07"],
+ affected_users=["[email protected]"],
+ affected_assets=["asset-42"],
+ connector_type=None,
+ )
+ )
+ groups = {(e.group, e.kind, e.value) for e in entities}
+ assert ("principal", "host", "win-finance-07") in groups
+ assert ("principal", "user", "[email protected]") in groups
+ assert ("principal", "asset", "asset-42") in groups
+
+ def test_network_group_promotes_destination_label(self) -> None:
+ entities = build_related_entities(
+ _alert(
+ affected_ips=["10.0.0.5"],
+ raw_event={"dst_ip": "203.0.113.7", "domain": "evil.example"},
+ connector_type=None,
+ )
+ )
+ # Source IP comes from the denormalised column with no label.
+ # Destination is pulled from raw_event and tagged label="destination".
+ by_value = {e.value: e for e in entities}
+ assert by_value["10.0.0.5"].group == "network"
+ assert by_value["10.0.0.5"].label is None
+ assert by_value["203.0.113.7"].group == "network"
+ assert by_value["203.0.113.7"].label == "destination"
+ assert by_value["evil.example"].group == "network"
+ assert by_value["evil.example"].kind == "domain"
+
+ def test_workflow_group_promotes_rule_and_mitre(self) -> None:
+ entities = build_related_entities(
+ _alert(
+ raw_event={"rule_name": "Excessive failed logins"},
+ mitre_tactics=["initial-access"],
+ mitre_techniques=[{"id": "T1078", "name": "Valid Accounts"}],
+ connector_type=None,
+ )
+ )
+ by_kind = {(e.kind, e.value): e for e in entities}
+ assert by_kind[("rule", "Excessive failed logins")].group == "workflow"
+ assert by_kind[("mitre_tactic", "initial-access")].group == "workflow"
+ # Dict MITRE rows render the ID as value and the name as label,
+ # plus they get a /detection/tuning pivot.
+ tech = by_kind[("mitre_technique", "T1078")]
+ assert tech.group == "workflow"
+ assert tech.label == "Valid Accounts"
+ assert tech.pivot == "/detection/tuning?technique=T1078"
+
+ def test_tenant_group_has_connector_and_case_pivots(self) -> None:
+ case_id = uuid.uuid4()
+ entities = build_related_entities(_alert(connector_type="okta", case_id=case_id))
+ by_kind = {e.kind: e for e in entities}
+ assert by_kind["connector"].group == "tenant"
+ assert by_kind["connector"].value == "okta"
+ assert by_kind["case"].group == "tenant"
+ assert by_kind["case"].value == str(case_id)
+ assert by_kind["case"].pivot == f"/cases/{case_id}"
+
+ def test_rba_promotion_surfaces_as_tenant_pivot(self) -> None:
+ entities = build_related_entities(
+ _alert(
+ enrichment_data={"rba_top_promotion": {"entity": "host:web-01"}},
+ connector_type=None,
+ )
+ )
+ by_kind = {e.kind: e for e in entities}
+ assert "rba_entity" in by_kind
+ assert by_kind["rba_entity"].group == "tenant"
+ assert by_kind["rba_entity"].label == "risk promotion"
+ assert by_kind["rba_entity"].pivot == "/alerts?view=entities&entity=host:web-01"
+
+ def test_dedup_is_case_insensitive(self) -> None:
+ """Duplicate IPs (different casing / surrounding whitespace) collapse."""
+ entities = build_related_entities(
+ _alert(
+ affected_ips=["10.0.0.5", "10.0.0.5", " 10.0.0.5 "],
+ connector_type=None,
+ )
+ )
+ # All three collapse to a single network/ip entity.
+ ips = [e for e in entities if e.kind == "ip"]
+ assert len(ips) == 1
+ # First-seen casing wins (no trim/case-change on the kept value
+ # beyond surrounding whitespace).
+ assert ips[0].value == "10.0.0.5"
+
+ def test_whitespace_only_entities_are_dropped(self) -> None:
+ entities = build_related_entities(
+ _alert(
+ affected_hosts=[" ", ""],
+ affected_users=[None, " alice "],
+ connector_type=None,
+ )
+ )
+ hosts = [e for e in entities if e.kind == "host"]
+ users = [e for e in entities if e.kind == "user"]
+ assert hosts == []
+ # whitespace-trimmed alice survives.
+ assert len(users) == 1
+ assert users[0].value == "alice"
+
+ def test_pivot_routes_are_built_per_kind(self) -> None:
+ """The pivot URL contract is part of the public API.
+
+ The frontend keys off the pivot to decide whether a chip is
+ clickable. Pinning the routes prevents an accidental rename.
+ """
+ entities = build_related_entities(
+ _alert(
+ affected_hosts=["h1"],
+ affected_users=["u1"],
+ affected_ips=["1.2.3.4"],
+ connector_type=None,
+ )
+ )
+ by_kind = {e.kind: e for e in entities}
+ assert by_kind["host"].pivot == "/attack-graph?entity=host:h1"
+ assert by_kind["user"].pivot == "/attack-graph?entity=user:u1"
+ assert by_kind["ip"].pivot == "/attack-graph?entity=ip:1.2.3.4"
+
+
+# ─── build_recommended_actions ───────────────────────────────────────────────
+
+
+class TestBuildRecommendedActions:
+ def test_returns_empty_list_when_field_is_none(self) -> None:
+ assert build_recommended_actions(_alert(ai_recommendations=None)) == []
+
+ def test_returns_empty_list_when_field_is_not_a_list(self) -> None:
+ """Whatever the agent emits, anything non-list returns []."""
+ assert build_recommended_actions(_alert(ai_recommendations="oops")) == []
+ assert build_recommended_actions(_alert(ai_recommendations={"a": 1})) == []
+
+ def test_structured_dict_shape_round_trips(self) -> None:
+ actions = build_recommended_actions(
+ _alert(
+ ai_recommendations=[
+ {
+ "priority": 2,
+ "action": "Isolate host win-finance-07",
+ "rationale": "Lateral movement detected",
+ "risk": "high",
+ },
+ {
+ "priority": 1,
+ "action": "Disable account",
+ "rationale": None,
+ "risk": "medium",
+ },
+ ]
+ )
+ )
+ # Sorted by priority so the agent's intended order wins.
+ assert [a.priority for a in actions] == [1, 2]
+ assert actions[0].action == "Disable account"
+ assert actions[0].risk == "medium"
+ assert actions[1].rationale == "Lateral movement detected"
+
+ def test_legacy_list_of_strings_is_promoted(self) -> None:
+ actions = build_recommended_actions(
+ _alert(
+ ai_recommendations=[
+ "Notify on-call",
+ "Open Jira ticket",
+ ]
+ )
+ )
+ assert len(actions) == 2
+ # String rows get priority = idx + 1 and default risk "low".
+ assert actions[0].priority == 1
+ assert actions[0].action == "Notify on-call"
+ assert actions[0].risk == "low"
+ assert actions[1].priority == 2
+
+ def test_risk_outside_canonical_set_falls_back_to_low(self) -> None:
+ """The frontend only knows three risk tints — sanitise here."""
+ actions = build_recommended_actions(_alert(ai_recommendations=[{"action": "x", "risk": "spicy"}]))
+ assert actions[0].risk == "low"
+
+ def test_risk_is_lowercased(self) -> None:
+ actions = build_recommended_actions(_alert(ai_recommendations=[{"action": "x", "risk": "HIGH"}]))
+ assert actions[0].risk == "high"
+
+ def test_priority_lower_than_one_is_clamped(self) -> None:
+ """Pydantic's ``ge=1`` would otherwise raise — the helper clamps first."""
+ actions = build_recommended_actions(_alert(ai_recommendations=[{"action": "x", "priority": 0}]))
+ assert actions[0].priority == 1
+
+ def test_malformed_priority_falls_back_to_index(self) -> None:
+ actions = build_recommended_actions(
+ _alert(
+ ai_recommendations=[
+ {"action": "a"}, # missing priority
+ {"action": "b", "priority": "bogus"},
+ ]
+ )
+ )
+ # Both rows survive; their priorities are idx + 1.
+ assert [a.priority for a in actions] == [1, 2]
+
+ def test_blank_action_strings_are_silently_dropped(self) -> None:
+ actions = build_recommended_actions(
+ _alert(
+ ai_recommendations=[
+ "",
+ " ",
+ None,
+ {"action": " "},
+ "Valid",
+ ]
+ )
+ )
+ assert len(actions) == 1
+ assert actions[0].action == "Valid"
+
+
+# ─── build_mini_timeline (DB-bound) ──────────────────────────────────────────
+
+
+class TestBuildMiniTimeline:
+ def _audit_row(self, **overrides: Any) -> SimpleNamespace:
+ base = {
+ "id": uuid.uuid4(),
+ "tenant_id": uuid.uuid4(),
+ "actor_email": "[email protected]",
+ "actor_id": None,
+ "action": "status_change",
+ "resource": "alert",
+ "changes": {"status": ["new", "investigating"]},
+ "metadata_": {},
+ "created_at": datetime.now(UTC),
+ }
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+ def _case_row(self, **overrides: Any) -> SimpleNamespace:
+ base = {
+ "id": uuid.uuid4(),
+ "event_type": "case_comment",
+ "content": "Looks like a real positive — escalating",
+ "event_metadata": {"channel": "slack"},
+ "is_automated": False,
+ "user_id": uuid.uuid4(),
+ "created_at": datetime.now(UTC),
+ }
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+ @pytest.mark.asyncio
+ async def test_returns_empty_when_no_case_and_no_audit(self) -> None:
+ alert = _alert(case_id=None)
+ # With no case_id we only hit the audit query (one execute call).
+ db = _mock_db_returning([])
+ events = await build_mini_timeline(db, alert)
+ assert events == []
+ # Exactly one query — the audit one. The case query is skipped
+ # entirely when case_id is None.
+ assert db.execute.await_count == 1
+
+ @pytest.mark.asyncio
+ async def test_case_and_audit_events_are_merged(self) -> None:
+ alert = _alert(case_id=uuid.uuid4())
+ now = datetime.now(UTC)
+ case_row = self._case_row(created_at=now - timedelta(minutes=2))
+ audit_row = self._audit_row(created_at=now - timedelta(minutes=1))
+
+ # First execute → case rows; second → audit rows.
+ db = _mock_db_returning([case_row], [audit_row])
+ events = await build_mini_timeline(db, alert)
+
+ assert len(events) == 2
+ # Newest first.
+ assert events[0].id == str(audit_row.id)
+ assert events[1].id == str(case_row.id)
+ assert events[1].kind == "case_comment"
+ assert events[1].agent == str(case_row.user_id)
+ # Two queries — the case one and the audit one.
+ assert db.execute.await_count == 2
+
+ @pytest.mark.asyncio
+ async def test_results_are_capped_at_max_events(self) -> None:
+ alert = _alert(case_id=uuid.uuid4())
+ many_cases = [self._case_row() for _ in range(MAX_TIMELINE_EVENTS + 3)]
+ many_audits = [self._audit_row() for _ in range(MAX_TIMELINE_EVENTS + 3)]
+
+ db = _mock_db_returning(many_cases, many_audits)
+ events = await build_mini_timeline(db, alert)
+
+ assert len(events) == MAX_TIMELINE_EVENTS
+
+ @pytest.mark.asyncio
+ async def test_audit_event_summary_includes_action_and_resource(self) -> None:
+ alert = _alert(case_id=None)
+ audit_row = self._audit_row(action="assign", resource="alert")
+ db = _mock_db_returning([audit_row])
+
+ events = await build_mini_timeline(db, alert)
+
+ assert len(events) == 1
+ assert events[0].summary == "assign on alert"
+ assert events[0].kind == "assign"
+ assert events[0].agent == "[email protected]"
+ # changes blob is surfaced as the payload so the rail row can
+ # expand on click.
+ assert events[0].payload == {"status": ["new", "investigating"]}
+
+ @pytest.mark.asyncio
+ async def test_audit_event_falls_back_to_metadata_when_changes_empty(self) -> None:
+ alert = _alert(case_id=None)
+ audit_row = self._audit_row(changes={}, metadata_={"source_ip": "10.0.0.1"})
+ db = _mock_db_returning([audit_row])
+
+ events = await build_mini_timeline(db, alert)
+ assert events[0].payload == {"source_ip": "10.0.0.1"}
+
+ @pytest.mark.asyncio
+ async def test_audit_event_actor_id_fallback_when_email_missing(self) -> None:
+ alert = _alert(case_id=None)
+ actor_id = uuid.uuid4()
+ audit_row = self._audit_row(actor_email=None, actor_id=actor_id)
+ db = _mock_db_returning([audit_row])
+
+ events = await build_mini_timeline(db, alert)
+ assert events[0].agent == str(actor_id)
+
+ @pytest.mark.asyncio
+ async def test_automated_case_event_attributes_to_system(self) -> None:
+ alert = _alert(case_id=uuid.uuid4())
+ automated_row = self._case_row(is_automated=True, user_id=None)
+ db = _mock_db_returning([automated_row], [])
+
+ events = await build_mini_timeline(db, alert)
+ assert events[0].agent == "system"
+
+
+# ─── build_rail_envelope ─────────────────────────────────────────────────────
+
+
+class TestBuildRailEnvelope:
+ @pytest.mark.asyncio
+ async def test_returns_pydantic_envelope_with_all_three_sections(self) -> None:
+ alert = _alert(
+ affected_ips=["10.0.0.5"],
+ ai_recommendations=[{"action": "Isolate", "priority": 1, "risk": "high"}],
+ case_id=None,
+ )
+ db = _mock_db_returning([]) # one execute call (audit only)
+
+ envelope = await build_rail_envelope(db, alert)
+
+ assert isinstance(envelope, RailEnvelope)
+ assert any(e.kind == "ip" and e.value == "10.0.0.5" for e in envelope.related_entities)
+ assert envelope.mini_timeline == []
+ assert len(envelope.recommended_actions) == 1
+ assert envelope.recommended_actions[0].action == "Isolate"
+
+ @pytest.mark.asyncio
+ async def test_envelope_is_json_serialisable(self) -> None:
+ """The envelope rides on the wire; Pydantic must serialise it."""
+ alert = _alert(
+ affected_ips=["10.0.0.5"],
+ ai_recommendations=[{"action": "Isolate", "priority": 1}],
+ case_id=None,
+ )
+ db = _mock_db_returning([])
+
+ envelope = await build_rail_envelope(db, alert)
+ payload = envelope.model_dump(mode="json")
+
+ # The wire format is snake_case (see normalizeAlert on the FE).
+ assert "related_entities" in payload
+ assert "mini_timeline" in payload
+ assert "recommended_actions" in payload
+ # And the entity fields are also snake_case ready for the rail.
+ assert payload["related_entities"][0]["group"] == "network"
+
+
+# ─── RelatedEntity / RecommendedAction Pydantic contracts ────────────────────
+
+
+class TestPydanticContracts:
+ def test_related_entity_serialises_snake_case(self) -> None:
+ e = RelatedEntity(
+ group="principal",
+ kind="host",
+ value="win-finance-07",
+ label="primary",
+ pivot="/attack-graph?entity=host:win-finance-07",
+ )
+ dump = e.model_dump(mode="json")
+ assert set(dump) == {"group", "kind", "value", "label", "pivot"}
+ assert dump["value"] == "win-finance-07"
+
+ def test_recommended_action_priority_must_be_at_least_one(self) -> None:
+ """Defence in depth — the helper clamps, but the model also enforces."""
+ with pytest.raises(ValidationError):
+ RecommendedAction(priority=0, action="x")
+
+ def test_mini_timeline_event_payload_is_optional(self) -> None:
+ e = MiniTimelineEvent(
+ id="abc",
+ ts=datetime.now(UTC),
+ kind="audit",
+ agent="system",
+ summary="x",
+ )
+ assert e.payload is None
+ assert e.duration_ms == 0
diff --git a/services/api/tests/services/test_narrative_projection.py b/services/api/tests/services/test_narrative_projection.py
new file mode 100644
index 000000000..782e25070
--- /dev/null
+++ b/services/api/tests/services/test_narrative_projection.py
@@ -0,0 +1,399 @@
+"""Unit tests for ``app.services.narrative_projection``.
+
+The projection is pure: ORM ``Alert`` row → ``NarrativeInputs`` dataclass.
+We use ``SimpleNamespace`` stand-ins for the ORM row so the test stays
+hermetic — no SQLAlchemy mapper, no DB. The projection is exercised
+through ``project_alert_to_narrative_inputs`` plus the public-builder
+contract; we never poke at the underscore helpers directly so the test
+keeps tracking the public surface as it evolves.
+
+The contract we're guarding:
+
+1. The denormalised entity columns (``affected_ips``, ``affected_hosts``,
+ ``affected_users``) take precedence over ``raw_event`` fallbacks.
+2. ``severity`` is lower-cased and clamped to the valid five-tier ladder.
+3. ``confidence_label`` is lower-cased and clamped to the three valid
+ bands; out-of-range values fall back to ``None`` (the builder skips
+ the rationale block).
+4. MITRE coverage tolerates both shapes (bare strings *and* dicts).
+5. The RBA promotion block and ``exploit_in_wild`` flag are reflected.
+6. The end-to-end pipeline (project → ``build_narrative``) produces a
+ non-empty, deterministic narrative for a typical alert.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+import uuid
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from app.services.narrative_loader import build_narrative
+from app.services.narrative_projection import project_alert_to_narrative_inputs
+
+# ─── Test fixtures ───────────────────────────────────────────────────────────
+
+
+def _alert(**overrides: Any) -> SimpleNamespace:
+ """Build a stand-in for the ``Alert`` ORM row.
+
+ Only the attributes the projection accesses are populated. Tests
+ override just the field(s) they care about so each assertion stays
+ focused on a single behaviour.
+ """
+ base: dict[str, Any] = {
+ "id": uuid.uuid4(),
+ "tenant_id": uuid.uuid4(),
+ "severity": "high",
+ "title": "Suspicious authentication",
+ "confidence": 75,
+ "confidence_label": "high",
+ "confidence_rationale": [],
+ "mitre_tactics": [],
+ "mitre_techniques": [],
+ "tags": [],
+ "case_id": None,
+ "connector_type": "okta",
+ "affected_ips": [],
+ "affected_hosts": [],
+ "affected_users": [],
+ "raw_event": {},
+ "enrichment_data": {},
+ }
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+
+# ─── Severity / confidence normalisation ─────────────────────────────────────
+
+
+ "raw_severity, expected",
+ [
+ ("CRITICAL", "critical"),
+ ("High", "high"),
+ ("medium", "medium"),
+ ("LOW", "low"),
+ ("info", "info"),
+ ],
+)
+def test_severity_is_lowercased(raw_severity: str, expected: str) -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(severity=raw_severity))
+ assert inputs.severity == expected
+
+
+def test_severity_falls_back_to_info_when_unrecognised() -> None:
+ """The fusion service always emits a known tier, but we defend in depth.
+
+ A bad value reaching the projection (database hand-edit, future
+ schema change, etc.) should *not* break narrative rendering; it
+ should degrade to the informational sentence.
+ """
+ inputs = project_alert_to_narrative_inputs(_alert(severity="nope"))
+ assert inputs.severity == "info"
+
+
+def test_severity_falls_back_to_info_when_null() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(severity=None))
+ assert inputs.severity == "info"
+
+
[email protected]("band", ["high", "medium", "low"])
+def test_confidence_label_passes_through(band: str) -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(confidence_label=band))
+ assert inputs.confidence_label == band
+
+
+def test_confidence_label_is_lowercased() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(confidence_label="HIGH"))
+ assert inputs.confidence_label == "high"
+
+
+def test_confidence_label_falls_back_to_none_for_unrecognised_band() -> None:
+ """The builder's Literal type-hint accepts only high/medium/low.
+
+ Anything else (including the legacy ``"unknown"`` we saw in some
+ early seeds) drops to ``None`` so the rationale block is skipped
+ rather than crashing the renderer.
+ """
+ inputs = project_alert_to_narrative_inputs(_alert(confidence_label="unknown"))
+ assert inputs.confidence_label is None
+
+
+def test_confidence_score_is_preserved_unchanged() -> None:
+ """The 0-100 confidence score round-trips verbatim."""
+ inputs = project_alert_to_narrative_inputs(_alert(confidence=42))
+ assert inputs.confidence == 42
+
+
+# ─── Entity precedence ───────────────────────────────────────────────────────
+
+
+def test_denormalised_column_wins_over_raw_event() -> None:
+ """``affected_ips[0]`` must beat ``raw_event.src_ip``.
+
+ The fusion service curates the denormalised columns at correlation
+ time — they're the authoritative entity set. The raw_event fallback
+ only matters when fusion didn't promote anything to first-class.
+ """
+ inputs = project_alert_to_narrative_inputs(
+ _alert(
+ affected_ips=["10.0.0.5"],
+ raw_event={"src_ip": "192.168.1.99"},
+ )
+ )
+ assert inputs.src_ip == "10.0.0.5"
+
+
+def test_raw_event_fallback_when_denormalised_empty() -> None:
+ """When ``affected_ips`` is empty we fall through to ``raw_event``."""
+ inputs = project_alert_to_narrative_inputs(_alert(raw_event={"source_ip": "192.168.1.99"}))
+ # source_ip is one of the accepted aliases per the projection's
+ # blob key list — see narrative_projection._from_blob.
+ assert inputs.src_ip == "192.168.1.99"
+
+
+def test_hostname_pulls_from_raw_event_aliases() -> None:
+ """``raw_event.computer_name`` is an alias for ``hostname``."""
+ inputs = project_alert_to_narrative_inputs(_alert(raw_event={"computer_name": "win-finance-07"}))
+ assert inputs.hostname == "win-finance-07"
+
+
+def test_username_pulls_from_raw_event_aliases() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(raw_event={"account_name": "svc_backup"}))
+ assert inputs.username == "svc_backup"
+
+
+def test_file_hash_url_domain_dst_ip_from_raw_event() -> None:
+ """All four "fallback-only" fields come from the raw event blob."""
+ inputs = project_alert_to_narrative_inputs(
+ _alert(
+ raw_event={
+ "dst_ip": "203.0.113.7",
+ "sha256": "deadbeef" * 8,
+ "domain": "evil.example",
+ "url": "https://evil.example/payload",
+ }
+ )
+ )
+ assert inputs.dst_ip == "203.0.113.7"
+ assert inputs.file_hash == "deadbeef" * 8
+ assert inputs.domain == "evil.example"
+ assert inputs.url == "https://evil.example/payload"
+
+
+def test_empty_strings_in_columns_are_skipped() -> None:
+ """A whitespace-only entity must not poison the narrative.
+
+ Some legacy connectors emit ``""`` for absent fields; the projection
+ treats those as "not present" so the builder doesn't render a
+ blank entity in the summary line.
+ """
+ inputs = project_alert_to_narrative_inputs(
+ _alert(
+ affected_hosts=[" ", ""],
+ raw_event={"hostname": "real-host"},
+ )
+ )
+ assert inputs.hostname == "real-host"
+
+
+# ─── MITRE coverage ──────────────────────────────────────────────────────────
+
+
+def test_mitre_tactics_accepts_bare_strings() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(mitre_tactics=["initial-access", "execution"]))
+ assert inputs.mitre_tactics == ("initial-access", "execution")
+
+
+def test_mitre_tactics_accepts_dict_shape() -> None:
+ """Some connectors send ``{"name": "...", "id": "TA0001"}`` rows.
+
+ The projection flattens both shapes to a bare tuple of names so the
+ builder doesn't have to know about the heterogeneity.
+ """
+ inputs = project_alert_to_narrative_inputs(
+ _alert(
+ mitre_tactics=[
+ {"name": "initial-access", "id": "TA0001"},
+ {"id": "TA0002"}, # name missing — id is the fallback
+ ]
+ )
+ )
+ assert inputs.mitre_tactics == ("initial-access", "TA0002")
+
+
+def test_mitre_techniques_strip_whitespace() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(mitre_techniques=[" T1078 ", ""]))
+ assert inputs.mitre_techniques == ("T1078",)
+
+
+# ─── Confidence rationale projection ─────────────────────────────────────────
+
+
+def test_rationale_factors_keep_label_value_contribution_weight() -> None:
+ """The builder consumes only label/value/contribution/weight.
+
+ Extra columns the fusion service might add later (e.g. ``factor``
+ enum) are silently dropped — same shape contract as the rest of
+ the projection.
+ """
+ inputs = project_alert_to_narrative_inputs(
+ _alert(
+ confidence_rationale=[
+ {
+ "factor": "asset_criticality",
+ "label": "Asset criticality",
+ "value": "tier-1 critical",
+ "contribution": 0.3,
+ "weight": 0.25,
+ },
+ {
+ "factor": "threat_intel",
+ "label": "Threat intel match",
+ "value": "2 IOCs matched",
+ "contribution": 0.2,
+ "weight": 0.2,
+ },
+ ]
+ )
+ )
+ assert len(inputs.rationale) == 2
+ assert inputs.rationale[0].label == "Asset criticality"
+ assert inputs.rationale[0].value == "tier-1 critical"
+ assert inputs.rationale[0].contribution == pytest.approx(0.3)
+ assert inputs.rationale[0].weight == pytest.approx(0.25)
+
+
+def test_rationale_silently_drops_malformed_rows() -> None:
+ """A bad row (missing required key, wrong type) doesn't crash.
+
+ The projection skips it. We assert on the *count* so any future
+ change that accidentally loosens validation gets caught.
+ """
+ inputs = project_alert_to_narrative_inputs(
+ _alert(
+ confidence_rationale=[
+ {"label": "ok", "value": "v", "contribution": 0.5, "weight": 0.5},
+ {"label": 123, "value": "v", "contribution": 0.1, "weight": 0.1}, # bad label
+ "not a dict",
+ {"label": "ok2", "value": "v", "contribution": "bad", "weight": 0.1}, # bad number
+ ]
+ )
+ )
+ assert len(inputs.rationale) == 1
+ assert inputs.rationale[0].label == "ok"
+
+
+# ─── RBA + exploit-in-wild signals ───────────────────────────────────────────
+
+
+def test_rba_promotion_is_extracted() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(enrichment_data={"rba_top_promotion": {"entity": "host:web-01", "score": 78.3}}))
+ assert inputs.rba_entity == "host:web-01"
+ assert inputs.rba_score == pytest.approx(78.3)
+
+
+def test_rba_promotion_missing_returns_none() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(enrichment_data={}))
+ assert inputs.rba_entity is None
+ assert inputs.rba_score is None
+
+
+def test_exploit_in_wild_flag_via_enrichment_data() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(enrichment_data={"exploit_in_wild": True}))
+ assert inputs.exploit_in_wild is True
+
+
+def test_exploit_in_wild_flag_via_tag() -> None:
+ """The tag is the back-compat path for older vuln_boost rows."""
+ inputs = project_alert_to_narrative_inputs(_alert(tags=["exploit-in-wild"]))
+ assert inputs.exploit_in_wild is True
+
+
+def test_exploit_in_wild_defaults_false() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert())
+ assert inputs.exploit_in_wild is False
+
+
+# ─── Correlation context ─────────────────────────────────────────────────────
+
+
+def test_correlation_decision_is_correlated_when_case_id_set() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(case_id=uuid.uuid4()))
+ assert inputs.correlation_decision == "correlated"
+
+
+def test_correlation_decision_is_none_for_orphan_alerts() -> None:
+ inputs = project_alert_to_narrative_inputs(_alert(case_id=None))
+ assert inputs.correlation_decision is None
+
+
+def test_incident_alert_count_is_always_none_in_api_projection() -> None:
+ """The API can't recompute the incident's total without an extra query.
+
+ The narrative builder gracefully omits the "n alerts on this
+ incident" suffix when ``incident_alert_count`` is ``None`` — that's
+ the contract this test pins.
+ """
+ inputs = project_alert_to_narrative_inputs(_alert(case_id=uuid.uuid4()))
+ assert inputs.incident_alert_count is None
+
+
+# ─── End-to-end: project → build_narrative ───────────────────────────────────
+
+
+def test_project_then_build_produces_non_empty_narrative() -> None:
+ """A typical fusion-emitted alert renders a non-empty narrative.
+
+ This is the integration point between the projection and the
+ vendored builder. We don't assert exact prose (the builder is
+ tested in services/fusion); we only verify the bridge works and
+ keeps the projection wired correctly.
+ """
+ alert = _alert(
+ severity="critical",
+ title="Suspicious authentication burst from new geo",
+ confidence=82,
+ confidence_label="high",
+ confidence_rationale=[
+ {
+ "label": "Asset criticality",
+ "value": "tier-1 critical",
+ "contribution": 0.3,
+ "weight": 0.25,
+ }
+ ],
+ affected_ips=["10.0.0.5"],
+ affected_hosts=["win-finance-07"],
+ affected_users=["[email protected]"],
+ mitre_tactics=["initial-access"],
+ mitre_techniques=["T1078"],
+ connector_type="okta",
+ case_id=uuid.uuid4(),
+ )
+ inputs = project_alert_to_narrative_inputs(alert)
+ narrative = build_narrative(inputs)
+
+ assert isinstance(narrative, str)
+ assert narrative.strip(), "narrative must not be empty"
+ # The summary line always names the primary entity. ``src_ip`` wins
+ # over hostname/user in the precedence chain, so the IP should be
+ # the one rendered.
+ assert "10.0.0.5" in narrative
+
+
+def test_project_then_build_is_deterministic() -> None:
+ """Same row → same narrative. Property the lazy-fill path relies on."""
+ alert = _alert(
+ severity="high",
+ title="Suspicious authentication",
+ affected_hosts=["win-finance-07"],
+ mitre_tactics=["execution"],
+ )
+ n1 = build_narrative(project_alert_to_narrative_inputs(alert))
+ n2 = build_narrative(project_alert_to_narrative_inputs(alert))
+ assert n1 == n2
diff --git a/services/fusion/app/models/alert.py b/services/fusion/app/models/alert.py
index d0fa952b6..b81306a37 100644
--- a/services/fusion/app/models/alert.py
+++ b/services/fusion/app/models/alert.py
@@ -152,6 +152,16 @@ class FusedAlert(BaseModel):
confidence_score: float = Field(default=0.5, ge=0.0, le=1.0)
confidence_rationale: list[ConfidenceFactor] = Field(default_factory=list)
+ # Deterministic correlation narrative — Wave 6 of v1.5 SOC Console Parity.
+ # Populated at fusion time by ``services.fusion.app.services.narrative.build_narrative``
+ # and surfaced verbatim by the InvestigationRail on ``/alerts`` (no LLM
+ # round-trip needed). The streaming LLM explanation lives behind a
+ # "Deep Explain" button at ``POST /alerts/{id}/explain``. ``None`` here
+ # only happens when the fusion engine cannot build a narrative for the
+ # alert (e.g. minimal-content fixture rows in tests); the API will
+ # lazily compute it on first read in that case.
+ narrative: str | None = None
+
fused_at: datetime = Field(default_factory=datetime.utcnow)
diff --git a/services/fusion/app/services/fusion_engine.py b/services/fusion/app/services/fusion_engine.py
index 53094cb9d..4447ca511 100644
--- a/services/fusion/app/services/fusion_engine.py
+++ b/services/fusion/app/services/fusion_engine.py
@@ -9,17 +9,105 @@ from uuid import UUID
import structlog
from app.core.config import settings
-from app.models.alert import FusedAlert, FusionDecision, RawAlert
+from app.models.alert import (
+ ConfidenceFactor,
+ FusedAlert,
+ FusionDecision,
+ IncidentSummary,
+ RawAlert,
+)
from app.services.confidence import ConfidenceScorer
from app.services.correlator import Correlator
from app.services.deduplicator import Deduplicator
-from app.services.entity_risk import EntityRiskEngine
+from app.services.entity_risk import EntityRiskEngine, EntityRiskRecord
from app.services.ml_scorer import MLScorer
+from app.services.narrative import (
+ NarrativeFactor,
+ NarrativeInputs,
+ build_narrative,
+)
from app.services.vuln_boost import apply_vuln_boost
logger = structlog.get_logger()
+def _to_narrative_inputs(
+ fused: FusedAlert,
+ incident: IncidentSummary,
+ top_promotion: EntityRiskRecord | None,
+) -> NarrativeInputs:
+ """Project a fully-scored ``FusedAlert`` into ``NarrativeInputs``.
+
+ This is the only place in the fusion service that knows how to map the
+ domain model onto the narrative builder's contract. The builder itself
+ stays decoupled (it takes a dataclass and returns a string), which is
+ what lets us mirror it byte-for-byte into ``services/api/app/_vendor/``
+ and reuse it for the API's lazy-fill path.
+
+ The shape is intentionally narrow: we surface only the fields the
+ InvestigationRail actually renders. New signals (UEBA z-score, vuln
+ severity, …) are added by extending ``NarrativeInputs`` first, then
+ plumbing them through here — never by bypassing the dataclass.
+ """
+ raw = fused.alert
+
+ rationale_factors: tuple[NarrativeFactor, ...] = tuple(
+ NarrativeFactor(
+ label=row.label,
+ value=row.value,
+ contribution=row.contribution,
+ weight=row.weight,
+ )
+ for row in fused.confidence_rationale
+ if isinstance(row, ConfidenceFactor)
+ )
+
+ # The fusion service speaks ``FusionDecision`` enums. The narrative builder
+ # only needs to know whether the alert opened a new incident or attached
+ # to an existing one — the duplicate path returns earlier and never
+ # reaches this adapter.
+ if fused.fusion_decision == FusionDecision.CORRELATED:
+ correlation_decision: str | None = "correlated"
+ elif fused.fusion_decision == FusionDecision.NEW_INCIDENT:
+ correlation_decision = "new_incident"
+ else:
+ correlation_decision = None
+
+ rba_entity: str | None = None
+ rba_score: float | None = None
+ if top_promotion is not None:
+ rba_entity = f"{top_promotion.entity_type}:{top_promotion.entity_value}"
+ rba_score = top_promotion.score
+
+ # ``confidence_score`` is on [0, 1]; the narrative surfaces a /100 number
+ # so the rail prose reads naturally ("Confidence: high (78/100)").
+ confidence_pct: int | None = round(max(0.0, min(1.0, fused.confidence_score)) * 100) if fused.confidence_score is not None else None
+
+ return NarrativeInputs(
+ severity=raw.severity.value, # type: ignore[arg-type]
+ title=raw.title,
+ confidence=confidence_pct,
+ confidence_label=fused.confidence_label.value, # type: ignore[arg-type]
+ rationale=rationale_factors,
+ src_ip=raw.src_ip,
+ dst_ip=raw.dst_ip,
+ hostname=raw.hostname,
+ username=raw.username,
+ file_hash=raw.file_hash,
+ domain=raw.domain,
+ url=raw.url,
+ mitre_tactics=tuple(raw.mitre_tactics),
+ mitre_techniques=tuple(raw.mitre_techniques),
+ incident_alert_count=incident.alert_count,
+ correlation_decision=correlation_decision,
+ rba_entity=rba_entity,
+ rba_score=rba_score,
+ exploit_in_wild=fused.exploit_in_wild,
+ source=raw.source,
+ tags=tuple(raw.tags),
+ )
+
+
class FusionEngine:
"""Orchestrates the full alert fusion pipeline."""
@@ -110,10 +198,18 @@ class FusionEngine:
# promote one or more of them to an entity-incident. Failures here
# never block the alert pipeline — RBA is additive signal, not
# the primary correlation path.
+ top_promotion: EntityRiskRecord | None = None
if self._entity_risk is not None and self._entity_risk.enabled:
try:
promotions = await self._entity_risk.observe(alert)
if promotions:
+ # Pick the highest-scoring promoted entity as the rail's
+ # headline for the RBA call-out. Ties break on score then
+ # entity_value for determinism (sorted is stable).
+ top_promotion = max(
+ promotions,
+ key=lambda r: (r.score, r.entity_value),
+ )
logger.info(
"rba_promotions",
alert_id=str(alert.id),
@@ -122,6 +218,18 @@ class FusionEngine:
except Exception as exc:
logger.warning("rba_observation_failed", error=str(exc))
+ # --- Step 5: Correlation narrative ---
+ # Deterministic, Markdown-light prose composed from the values already
+ # on ``fused`` plus the RBA promotion (if any) and incident roll-up.
+ # The narrative is cached on the ``alerts`` row so the API and the
+ # InvestigationRail never have to round-trip an LLM to show "why".
+ # Failures here are never fatal — the API will recompute on first read
+ # via the same builder (vendored in ``services/api/app/_vendor/``).
+ try:
+ fused.narrative = build_narrative(_to_narrative_inputs(fused, incident, top_promotion))
+ except Exception as exc:
+ logger.warning("narrative_build_failed", alert_id=str(alert.id), error=str(exc))
+
logger.info(
"Alert fusion complete",
alert_id=str(alert.id),
@@ -131,6 +239,7 @@ class FusionEngine:
anomaly_score=fused.anomaly_score,
priority_score=fused.priority_score,
confidence=fused.confidence_label.value,
+ narrative_present=fused.narrative is not None,
)
return fused
diff --git a/services/fusion/app/services/narrative.py b/services/fusion/app/services/narrative.py
new file mode 100644
index 000000000..5519e1b58
--- /dev/null
+++ b/services/fusion/app/services/narrative.py
@@ -0,0 +1,327 @@
+"""
+Correlation narrative builder.
+
+Wave 6 of the v1.5 SOC Console Parity plan. Every fused alert ships with a
+human-readable, deterministic correlation narrative that the
+``InvestigationRail`` on ``/alerts`` renders verbatim. The narrative answers
+the analyst's first three questions in one short paragraph — *what fired*,
+*what evidence supports it*, and *what we recommend next* — so the right pane
+of the alerts workbench is useful **without** an LLM round-trip. The
+streaming LLM explanation still exists; it sits behind a "Deep Explain"
+button inside the rail (``POST /api/v1/alerts/{id}/explain``).
+
+Design contract
+===============
+
+* **Deterministic.** Given identical inputs the output is byte-for-byte
+ identical. No timestamps, no random ordering, no LLM. The output is safe to
+ cache on the row and serve cold.
+* **Pure.** ``build_narrative`` is a free function that takes a
+ ``NarrativeInputs`` dataclass and returns a string. No database calls, no
+ network, no logging side effects.
+* **Vendored.** This module lives canonically in ``services/fusion`` and is
+ byte-mirrored into ``services/api/app/_vendor/narrative.py`` so the API can
+ lazily compute the narrative on first read for legacy alerts that were
+ fused before the column existed. ``scripts/sync_vendored_narrative.py``
+ guards the mirror; CI fails the build the moment the two copies drift.
+* **Markdown-light.** The output uses a tiny markdown dialect — ``**bold**``,
+ bullet lists, blank-line paragraphs. The rail renders these without a full
+ markdown engine. No tables, no headings, no images.
+
+Schema
+======
+
+The narrative is composed of up to four blocks separated by a blank line:
+
+1. **Summary** — one sentence: *severity*, *title*, *primary entity*.
+2. **Why we believe it** — up to four bullets pulled from the confidence
+ rationale, sorted by impact, prefixed with ``+`` or ``−``.
+3. **Correlated activity** — one short paragraph if the alert is part of an
+ incident, otherwise omitted.
+4. **Recommended next step** — one bullet derived from severity + MITRE
+ tactic. Action surface is deliberately conservative; the rail also
+ surfaces the LLM-generated remediation actions from the responder agent
+ for cases that need richer planning.
+
+If any block has no content it is dropped — the narrative never contains
+empty sections.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Literal
+
+NARRATIVE_VERSION = 1
+"""Bump this whenever the algorithm changes in a way that should invalidate
+existing cached narratives. The API uses this to opportunistically refresh
+rows whose ``narrative`` was generated under a stale version (a follow-up
+PR will add a ``narrative_version`` column once we need it; for now the
+constant simply marks the algorithm revision in code)."""
+
+
+Severity = Literal["critical", "high", "medium", "low", "info"]
+ConfidenceBand = Literal["high", "medium", "low"]
+
+
+@dataclass(frozen=True)
+class NarrativeFactor:
+ """One row of the confidence rationale, as seen by the builder.
+
+ Mirrors ``services/fusion/app/models/alert.py::ConfidenceFactor`` and
+ ``services/api/app/models/alert.py::Alert.confidence_rationale`` (which
+ stores the same shape as JSONB). The builder only needs the human-
+ facing fields, so we keep this dataclass minimal and avoid taking a
+ runtime dependency on either model.
+
+ ``contribution`` is signed in [-1.0, +1.0]; positive nudges the score
+ up, negative nudges it down. ``weight`` is in [0, 1].
+ """
+
+ label: str
+ value: str
+ contribution: float
+ weight: float
+
+ @property
+ def impact(self) -> float:
+ """Absolute signed effect — used to sort the rationale."""
+ return self.contribution * self.weight
+
+
+@dataclass(frozen=True)
+class NarrativeInputs:
+ """Everything ``build_narrative`` needs to produce a narrative.
+
+ Both services construct this from their own native model. Keeping the
+ dataclass deliberately minimal lets us add new signals (RBA score,
+ UEBA z-score, …) by adding optional fields without breaking the
+ fusion-time call site.
+ """
+
+ severity: Severity
+ title: str
+
+ # Detection confidence
+ confidence: int | None = None # 0-100 surfaced on the row
+ confidence_label: ConfidenceBand | None = None
+ rationale: tuple[NarrativeFactor, ...] = ()
+
+ # Entities — first non-empty wins for the "primary entity" mention.
+ src_ip: str | None = None
+ dst_ip: str | None = None
+ hostname: str | None = None
+ username: str | None = None
+ file_hash: str | None = None
+ domain: str | None = None
+ url: str | None = None
+
+ # MITRE coverage — we only use the first tactic + technique count to
+ # keep the prose terse. The full list still lives on the row.
+ mitre_tactics: tuple[str, ...] = ()
+ mitre_techniques: tuple[str, ...] = ()
+
+ # Correlation context — populated when the alert was attached to an
+ # incident at fusion time.
+ incident_alert_count: int | None = None # total alerts on the incident
+ correlation_decision: str | None = None # "new_incident" | "correlated"
+
+ # Risk-Based Alerting — set when the alert touches an entity that
+ # already accumulated RBA points before this fired.
+ rba_entity: str | None = None
+ rba_score: float | None = None
+
+ # Exploit-in-wild boost (Tier 3.5) — the vuln_boost service flips this
+ # when one of the alert's entities matches an asset vulnerability with
+ # ``is_exploited=True``. The narrative calls it out explicitly because
+ # it materially changes the recommended action.
+ exploit_in_wild: bool = False
+
+ # Optional source/connector — included in the summary for context.
+ source: str | None = None
+
+ # Optional tags surfaced verbatim ("byok-llm", "ransomware-family:lockbit").
+ tags: tuple[str, ...] = field(default_factory=tuple)
+
+
+# ─── Helpers ─────────────────────────────────────────────────────────────────
+
+
+# Recommended-next-step lookup. Keyed by ``(severity, mitre_tactic)`` so that
+# the same tactic at different severities gives a proportionate response.
+# ``"*"`` is a wildcard fallback that catches alerts with no MITRE mapping.
+#
+# These are deliberately *operational* sentences — what an analyst would
+# actually do in the next 60 seconds. The richer multi-step LLM remediation
+# plan is generated by the responder agent and surfaced separately.
+_RECOMMENDED_ACTIONS: dict[tuple[str, str], str] = {
+ ("critical", "initial-access"): "Isolate the affected host and revoke the impacted user's sessions immediately.",
+ ("critical", "execution"): "Isolate the host, snapshot volatile memory, and trigger the incident response playbook.",
+ ("critical", "persistence"): "Isolate the host and rotate any credentials with access to the persistence mechanism.",
+ ("critical", "privilege-escalation"): "Quarantine the host and audit privileged-group membership changes in the last 24h.",
+ ("critical", "defense-evasion"): "Isolate the host and validate EDR/AV state on every endpoint sharing the same image.",
+ ("critical", "credential-access"): "Force a password reset and revoke active sessions for every affected identity.",
+ ("critical", "discovery"): "Isolate the host and review authentication logs for lateral pivot attempts.",
+ ("critical", "lateral-movement"): "Quarantine the source and destination hosts; block the SMB/RDP path between them.",
+ ("critical", "collection"): "Isolate the host, preserve the staged data, and notify Legal/DPO of potential exfil.",
+ ("critical", "exfiltration"): "Block the destination at the egress firewall, isolate the source, and start IR.",
+ ("critical", "impact"): "Activate the disaster-recovery runbook and isolate every host in the blast radius.",
+ ("critical", "command-and-control"): "Block the C2 destination at the firewall and isolate the beaconing host.",
+ ("high", "initial-access"): "Investigate the auth/login chain; suspend the user pending verification.",
+ ("high", "execution"): "Triage the process tree and quarantine the binary if it is unsigned or rare.",
+ ("high", "persistence"): "Inspect autoruns / scheduled tasks on the host and capture the persistence artifact.",
+ ("high", "privilege-escalation"): "Review the privilege change chain and validate it against the change calendar.",
+ ("high", "defense-evasion"): "Verify EDR is healthy on the host and compare to a known-good baseline.",
+ ("high", "credential-access"): "Force a password rotation for the affected identity and review session activity.",
+ ("high", "discovery"): "Pull recon-related telemetry and check for follow-on lateral movement.",
+ ("high", "lateral-movement"): "Audit recent authentication on the destination host and block stale credentials.",
+ ("high", "collection"): "Snapshot the staged artifacts and review who else accessed the same data store.",
+ ("high", "exfiltration"): "Rate-limit the destination and confirm whether the upload is sanctioned.",
+ ("high", "impact"): "Verify backup integrity and tighten access to the impacted system.",
+ ("high", "command-and-control"): "Sinkhole the destination and inspect outbound DNS from the host.",
+ ("medium", "*"): "Triage the alert in the queue: confirm whether the activity is sanctioned before escalating.",
+ ("low", "*"): "Acknowledge in the queue; suppress if this is a known benign pattern.",
+ ("info", "*"): "Informational — review during the next batch tuning pass.",
+}
+
+_DEFAULT_ACTION = "Triage the alert in the queue and validate the supporting evidence before escalating."
+
+# Bullet glyph for the action — kept identical with the rationale glyph so
+# the rail can re-flow the list without re-thinking the bullet style.
+_BULLET = "- "
+
+
+def _primary_entity(inputs: NarrativeInputs) -> str | None:
+ """Pick the most informative entity to mention in the summary.
+
+ Order: ``src_ip → hostname → username → domain → url → dst_ip →
+ file_hash``. This matches the precedence used by the deduplicator's
+ correlation key so the narrative and the dedup key always agree on
+ which entity is "primary".
+ """
+ for value in (
+ inputs.src_ip,
+ inputs.hostname,
+ inputs.username,
+ inputs.domain,
+ inputs.url,
+ inputs.dst_ip,
+ inputs.file_hash,
+ ):
+ if value:
+ return value
+ return None
+
+
+def _summary_block(inputs: NarrativeInputs) -> str:
+ severity_word = inputs.severity.capitalize() if inputs.severity else "Unknown"
+ primary = _primary_entity(inputs)
+
+ pieces = [f"**{severity_word}** alert: {inputs.title.strip()}"]
+ if primary:
+ pieces.append(f"on **{primary}**")
+ if inputs.source:
+ pieces.append(f"from `{inputs.source}`")
+
+ sentence = " ".join(pieces).rstrip(".") + "."
+ return sentence
+
+
+def _rationale_block(inputs: NarrativeInputs) -> str | None:
+ if not inputs.rationale:
+ return None
+ # Sort by absolute impact, take the top four. We do *not* drop zero-
+ # impact factors silently — if the only factors we have are noise, the
+ # rail should say so explicitly. We only drop a factor whose absolute
+ # impact rounds to exactly zero *and* there are more impactful factors
+ # available.
+ ordered = sorted(inputs.rationale, key=lambda f: abs(f.impact), reverse=True)
+ keep: list[NarrativeFactor] = []
+ for factor in ordered:
+ if len(keep) >= 4:
+ break
+ # Skip purely zero rows once we already have one bullet.
+ if keep and round(abs(factor.impact), 3) == 0.0:
+ continue
+ keep.append(factor)
+ if not keep:
+ return None
+ lines = ["Why we believe it:"]
+ for factor in keep:
+ sign = "+" if factor.contribution >= 0 else "−"
+ lines.append(f"{_BULLET}{sign} **{factor.label}** — {factor.value}")
+ if inputs.confidence is not None and inputs.confidence_label is not None:
+ lines.append(f"{_BULLET}Confidence: **{inputs.confidence_label}** ({inputs.confidence}/100)")
+ elif inputs.confidence is not None:
+ lines.append(f"{_BULLET}Confidence: **{inputs.confidence}/100**")
+ elif inputs.confidence_label is not None:
+ lines.append(f"{_BULLET}Confidence: **{inputs.confidence_label}**")
+ return "\n".join(lines)
+
+
+def _correlation_block(inputs: NarrativeInputs) -> str | None:
+ pieces: list[str] = []
+ if inputs.correlation_decision == "correlated" and inputs.incident_alert_count and inputs.incident_alert_count > 1:
+ pieces.append(f"Correlated activity: this alert is part of an incident with **{inputs.incident_alert_count}** related alerts.")
+ elif inputs.correlation_decision == "new_incident":
+ pieces.append("Correlated activity: this is the **first** alert on a newly opened incident.")
+ if inputs.rba_entity and inputs.rba_score is not None:
+ pieces.append(
+ f"Risk-based alerting has accumulated **{inputs.rba_score:.0f}** points on `{inputs.rba_entity}` before this alert fired."
+ )
+ if inputs.exploit_in_wild:
+ pieces.append(
+ "**Exploit-in-wild**: one of the indicators on this alert matches an asset vulnerability marked as actively exploited."
+ )
+ if not pieces:
+ return None
+ return " ".join(pieces)
+
+
+def _action_block(inputs: NarrativeInputs) -> str:
+ # Resolve the recommended-action lookup. We use the first declared
+ # tactic; the rest are still visible on the row.
+ severity = inputs.severity or "medium"
+ tactic = inputs.mitre_tactics[0].lower() if inputs.mitre_tactics else "*"
+
+ action = _RECOMMENDED_ACTIONS.get((severity, tactic))
+ if action is None:
+ # Fall back to the severity-wildcard row, then to the default.
+ action = _RECOMMENDED_ACTIONS.get((severity, "*"), _DEFAULT_ACTION)
+ return f"Recommended next step:\n{_BULLET}{action}"
+
+
+# ─── Public API ──────────────────────────────────────────────────────────────
+
+
+def build_narrative(inputs: NarrativeInputs) -> str:
+ """Build the deterministic correlation narrative.
+
+ The output is plain Markdown-light (see module docstring). The same
+ inputs always produce the same string; callers can safely cache the
+ result keyed by the alert id.
+ """
+ blocks: list[str] = [_summary_block(inputs)]
+
+ rationale = _rationale_block(inputs)
+ if rationale:
+ blocks.append(rationale)
+
+ correlation = _correlation_block(inputs)
+ if correlation:
+ blocks.append(correlation)
+
+ blocks.append(_action_block(inputs))
+
+ return "\n\n".join(blocks)
+
+
+__all__ = [
+ "NARRATIVE_VERSION",
+ "NarrativeFactor",
+ "NarrativeInputs",
+ "build_narrative",
+]