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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
ws-d2: case auto-summary artifact at investigation close
Beenu Arora674c444be87f
diff --git a/apps/web/src/components/cases/CaseWorkspace.tsx b/apps/web/src/components/cases/CaseWorkspace.tsxindex 43a745b02..2efbfc71e 100644--- a/apps/web/src/components/cases/CaseWorkspace.tsx+++ b/apps/web/src/components/cases/CaseWorkspace.tsx@@ -477,6 +477,23 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {const [newComment, setNewComment] = useState('');const [newTask, setNewTask] = useState('');const [statusUpdating, setStatusUpdating] = useState(false);+ // WS-D2 — track summary-download state so the button can show "Generating…"+ // and we can surface failures via toast without burying them in the console.+ const [summaryDownloading, setSummaryDownloading] = useState(false);++ const downloadSummary = useCallback(async () => {+ if (!caseRecord || summaryDownloading) return;+ setSummaryDownloading(true);+ try {+ await casesApi.openAutoSummaryHtml(caseRecord.id || caseId);+ toast.success('Summary opened — use Print → Save as PDF to archive');+ } catch (e: unknown) {+ const message = e instanceof Error ? e.message : 'Backend offline';+ toast.error(`Summary unavailable: ${message}`);+ } finally {+ setSummaryDownloading(false);+ }+ }, [caseRecord, caseId, summaryDownloading]);const updateStatus = async (status: CaseStatus) => {if (!caseRecord) return;@@ -687,6 +704,32 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {)}{investigating ? 'Investigating…' : 'Investigate with agent'}</button>+ {/*+ WS-D2 — deterministic, analyst-ready snapshot of the entire case+ (lifecycle, MITRE coverage, observables, evidence, timeline,+ recommendations). Backed by `GET /cases/{id}/summary?format=html`+ which renders a self-contained, print-ready HTML document the+ analyst can save as PDF for compliance / handoff. Available on+ every case so analysts can grab a snapshot any time, but the+ backend also auto-emits a system breadcrumb when status flips to+ resolved/closed.+ */}+ <button+ onClick={() => void downloadSummary()}+ disabled={summaryDownloading || !caseRecord}+ className={clsx(+ 'inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-semibold transition-colors',+ summaryDownloading || !caseRecord+ ? 'cursor-not-allowed border-slate-700/40 bg-slate-800/40 text-slate-500'+ : 'border-indigo-500/40 bg-indigo-500/10 text-indigo-200 hover:bg-indigo-500/20',+ )}+ title="Open a print-ready case summary (HTML → Save as PDF)"+ >+ {summaryDownloading && (+ <span className="h-3 w-3 animate-spin rounded-full border border-indigo-500/30 border-t-indigo-400" />+ )}+ {summaryDownloading ? 'Generating…' : 'Summary'}+ </button></div></div>diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex a06302c09..341cec645 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -603,6 +603,97 @@ export interface CasesResponse {pageSize: number;}+// ─── WS-D2 — Per-case auto-summary artifact ─────────────────────────────────+//+// Mirrors the Pydantic schemas in ``services/api/app/services/case_summary.py``.+// We keep these as a flat block of ``snake_case`` interfaces (matching the+// JSON over the wire) so consumers don't pay a transformation cost — the+// backend is the source of truth for shape, the UI just renders.+export interface CaseSummaryHeader {+ case_id: string;+ case_number: string | null;+ title: string;+ description: string | null;+ severity: string;+ status: string;+ assignee: string | null;+ created_by: string | null;+ tags: Record<string, unknown>;+}++export interface CaseLifecycleTimings {+ opened_at: string;+ triaged_at: string | null;+ resolved_at: string | null;+ closed_at: string | null;+ sla_due_at: string | null;+ time_to_triage_hours: number | null;+ time_to_resolve_hours: number | null;+ time_to_close_hours: number | null;+ sla_breached: boolean;+}++export interface CaseSummaryTaskBreakdown {+ total: number;+ todo: number;+ in_progress: number;+ done: number;+ overdue: number;+}++export interface CaseSummaryCommentBreakdown {+ total: number;+ analyst: number;+ system: number;+ distinct_authors: string[];+}++export interface CaseSummaryCoverage {+ mitre_techniques: string[];+ mitre_tactic_buckets: Record<string, number>;+ compliance_frameworks: string[];+}++export interface CaseSummaryObservables {+ total_nodes: number;+ total_edges: number;+ node_kind_counts: Record<string, number>;+ distinct_kinds: string[];+}++export interface CaseSummaryEvidence {+ total_items: number;+ distinct_kinds: string[];+}++export interface CaseSummaryTimelineEntry {+ ts: string;+ kind: string; // "case" | "comment" | "task"+ label: string;+ detail: string | null;+}++export interface CaseSummaryRecommendation {+ severity: string; // "info" | "warning" | "critical"+ title: string;+ body: string;+}++export interface CaseAutoSummary {+ generated_at: string;+ headline: string;+ case: CaseSummaryHeader;+ lifecycle: CaseLifecycleTimings;+ coverage: CaseSummaryCoverage;+ alerts: { count?: number; ids?: string[] } & Record<string, unknown>;+ observables: CaseSummaryObservables;+ evidence: CaseSummaryEvidence;+ tasks: CaseSummaryTaskBreakdown;+ comments: CaseSummaryCommentBreakdown;+ timeline: CaseSummaryTimelineEntry[];+ recommendations: CaseSummaryRecommendation[];+}+export interface CaseFilters {status?: string;priority?: string;@@ -844,6 +935,64 @@ export const casesApi = {document.body.removeChild(a);URL.revokeObjectURL(url);},++ // WS-D2 — auto-summary at investigation close.+ // The backend renders both the structured payload (json) and a print-ready+ // page (html). We expose JSON for callers that want to drive their own UI+ // (e.g. an inline drawer) and an "open in new tab" helper for the HTML+ // artifact so operators can Cmd/Ctrl-P → Save as PDF for case-file archival.+ /** Fetch the structured per-case auto-summary payload. */+ getAutoSummary: (caseId: string) =>+ request<CaseAutoSummary>(`/api/v1/cases/${caseId}/summary`, {+ params: { format: 'json' },+ }),++ /**+ * Open the per-case auto-summary HTML artifact in a new tab.+ *+ * We deliberately fetch with the auth headers (instead of a plain+ * ``window.open(url)``) because the backend requires the bearer token and+ * tenant header — direct anchor navigation would drop them and 401.+ * Mirrors the WS-G2 ``reportsApi.weeklyDigestHtml`` pattern so both+ * report surfaces behave consistently in the PWA.+ */+ openAutoSummaryHtml: async (caseId: string): Promise<void> => {+ const headers: Record<string, string> = {+ Accept: 'text/html',+ 'X-Tenant-Id': TENANT_ID,+ };+ if (typeof window !== 'undefined') {+ try {+ const token = window.localStorage.getItem(AUTH_TOKEN_KEY);+ if (token) headers.Authorization = `Bearer ${token}`;+ } catch {+ /* localStorage unavailable; ignore */+ }+ }++ const url = `${API_BASE}/api/v1/cases/${caseId}/summary?format=html`;+ const response = await fetch(url, { headers, cache: 'no-store' });+ if (!response.ok) {+ const detail = await response.text().catch(() => '');+ throw new ApiError(+ `API ${response.status} ${response.statusText} — /cases/${caseId}/summary`,+ response.status,+ detail,+ );+ }+ const blob = await response.blob();+ const objectUrl = URL.createObjectURL(blob);+ // Use a transient anchor so the print-ready page lands in its own tab.+ const a = document.createElement('a');+ a.href = objectUrl;+ a.target = '_blank';+ a.rel = 'noopener';+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ // Hold the blob URL long enough for the new tab to read it, then release.+ setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);+ },};// ─── Investigation Ledger (persistent agent decision log) ───────────────────diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.pyindex 99d31641b..800cf7a01 100644--- a/services/api/app/api/v1/endpoints/cases.py+++ b/services/api/app/api/v1/endpoints/cases.py@@ -29,6 +29,7 @@ from urllib.parse import quoteimport httpxfrom fastapi import APIRouter, HTTPException, Query, Response, status+from fastapi.responses import HTMLResponsefrom pydantic import BaseModel, Fieldfrom sqlalchemy import text@@ -39,6 +40,8 @@ from app.services.case_fanout import (fanout_create_case,fanout_status_change,)+from app.services.case_summary import build_case_summary+from app.services.case_summary_html import render_case_summary_htmllogger = logging.getLogger(__name__)@@ -549,6 +552,19 @@ async def update_case(case_id: str, body: UpdateCaseRequest, db: DBSession, userawait db.rollback()response.fanout_results = []+ # WS-D2 — when a case enters its terminal lifecycle stages, drop a+ # system note pointing to the auto-summary artifact. The summary+ # itself is generated on-demand by GET /cases/{id}/summary, so this+ # is a cheap, idempotent breadcrumb rather than a heavy precompute.+ if body.status in {"resolved", "closed"}:+ try:+ await _emit_summary_breadcrumb(db, case_id=row.id, status=body.status)+ except Exception: # pragma: no cover — defensive: never block status change.+ logger.exception(+ "cases.update.summary_breadcrumb_failed case=%s", row.id+ )+ await db.rollback()+return response@@ -1023,6 +1039,84 @@ def _safe_filename_segment(value: str) -> str:return _SAFE_FILENAME_RE.sub("_", value)[:64] or "unknown"+# ────────────────────────────────────────────────────────────────────────────+# WS-D2 — auto-summary artifact at investigation close.+# ────────────────────────────────────────────────────────────────────────────++# We keep the breadcrumb body in one place so the system note stays uniform+# across deployments — easier to grep, easier to redact in CI exports.+_SUMMARY_BREADCRUMB_BODY = (+ "Case auto-summary generated. Download from "+ "/api/v1/cases/{case_id}/summary?format=html "+ "(or ?format=json for the structured payload). "+ "Print the HTML page (Ctrl/Cmd-P → Save as PDF) for case-file archival."+)+++async def _emit_summary_breadcrumb(+ db: Any, *, case_id: uuid.UUID, status: str+) -> None:+ """Drop a system comment pointing to the on-demand summary endpoint.++ Idempotent on repeated status changes — we re-emit only when transitioning+ *into* a terminal state, never on noop updates. The body intentionally+ avoids embedding tenant-specific URLs so the artifact link still works+ behind reverse proxies that rewrite the host.+ """+ body = _SUMMARY_BREADCRUMB_BODY.format(case_id=case_id) + f" (status={status})"+ await db.execute(+ text(+ """+ INSERT INTO aisoc_case_comments+ (id, case_id, author, body, is_system, created_at)+ VALUES (:id, :case_id, :author, :body, true, :now)+ """+ ).bindparams(+ id=uuid.uuid4(),+ case_id=case_id,+ author="aisoc",+ body=body,+ now=datetime.now(UTC),+ )+ )+ await db.commit()+++ "/{case_id}/summary",+ summary="Download the per-case auto-summary (JSON or HTML)",+ response_model=None,+)+async def case_auto_summary(+ case_id: str,+ db: DBSession,+ user: AuthUser,+ format: Literal["json", "html"] = Query(+ "json",+ description=(+ "Response format. ``json`` returns the structured CaseAutoSummary; "+ "``html`` returns a print-ready report (use the browser's "+ "Save-as-PDF affordance for archival)."+ ),+ ),+) -> Any:+ cid = await _resolve_case_id(case_id, db)+ summary = await build_case_summary(db, cid)+ if summary is None:+ raise HTTPException(status_code=404, detail="Case not found.")++ if format == "html":+ rendered = render_case_summary_html(summary)+ case_label = summary.case.case_number or str(summary.case.case_id)[:8]+ filename = _safe_filename_segment(f"case-{case_label}-summary") + ".html"+ return HTMLResponse(+ content=rendered,+ headers={"Content-Disposition": f'inline; filename="{filename}"'},+ )++ return summary++@router.get("/{case_id}/investigations/{run_id}/report.pdf",summary="Download investigation PDF report",diff --git a/services/api/app/services/case_summary.py b/services/api/app/services/case_summary.pynew file mode 100644index 000000000..cb9f57624--- /dev/null+++ b/services/api/app/services/case_summary.py@@ -0,0 +1,757 @@+"""Case auto-summary builder.++WS-D2 — buyer-value plan+========================+Produces a deterministic, analyst-ready snapshot of a single case. Designed+to be generated automatically when a case transitions to ``resolved`` or+``closed``, but the same builder also powers the on-demand+``GET /cases/{id}/summary`` endpoint so analysts can preview the artifact at+any time.++The output is consumed by:++ * The web UI via the JSON shape (interactive panel + download button).+ * The HTML renderer in :pymod:`app.services.case_summary_html`, which is+ print-ready (browser "Save as PDF" gives an archival document with no+ weasyprint dependency).+ * The case-comments stream — when the auto-trigger fires, we emit a+ system comment that links to the artifact.++Architecture mirrors :pymod:`app.services.executive_digest`:++ 1. ``build_summary_from_rows`` — pure, deterministic, fully unit-tested.+ 2. ``build_case_summary`` — async DB orchestrator. Only place SQL lives.++Why a separate module from ``executive_digest``? The two reports answer+different questions: the executive digest is a *tenant-wide* weekly snapshot,+while the case summary is a *single-incident* close-out artifact for the+case file / runbook archive. Sharing the renderer style keeps them visually+consistent without coupling the data shapes.+"""++from __future__ import annotations++import uuid+from collections import Counter+from dataclasses import dataclass, field+from datetime import UTC, datetime, timedelta+from typing import Any++from pydantic import BaseModel, Field+from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession+++# ---------------------------------------------------------------------------+# Output schemas (Pydantic) — what the endpoint actually returns.+# ---------------------------------------------------------------------------+++class CaseSummaryHeader(BaseModel):+ """Identity + lifecycle fields for the case being summarised."""++ case_id: uuid.UUID+ case_number: str | None = None+ title: str+ description: str | None = None+ severity: str+ status: str+ assignee: str | None = None+ created_by: str | None = None+ tags: dict[str, Any] = Field(default_factory=dict)+++class CaseLifecycleTimings(BaseModel):+ """All of the lifecycle timestamps + derived durations (hours).++ Durations are ``None`` when the corresponding timestamp pair is missing.+ """++ opened_at: datetime+ triaged_at: datetime | None = None+ resolved_at: datetime | None = None+ closed_at: datetime | None = None+ sla_due_at: datetime | None = None++ time_to_triage_hours: float | None = None+ time_to_resolve_hours: float | None = None+ time_to_close_hours: float | None = None+ sla_breached: bool = False+++class TaskBreakdown(BaseModel):+ total: int = 0+ todo: int = 0+ in_progress: int = 0+ done: int = 0+ overdue: int = 0+++class CommentBreakdown(BaseModel):+ total: int = 0+ analyst: int = 0+ system: int = 0+ distinct_authors: list[str] = Field(default_factory=list)+++class CoverageSummary(BaseModel):+ """ATT&CK + compliance coverage for the case."""++ mitre_techniques: list[str] = Field(default_factory=list)+ mitre_tactic_buckets: dict[str, int] = Field(default_factory=dict)+ compliance_frameworks: list[str] = Field(default_factory=list)+++class ObservableSummary(BaseModel):+ total_nodes: int = 0+ total_edges: int = 0+ node_kind_counts: dict[str, int] = Field(default_factory=dict)+ distinct_kinds: list[str] = Field(default_factory=list)+++class EvidenceSummary(BaseModel):+ total_items: int = 0+ distinct_kinds: list[str] = Field(default_factory=list)+++class TimelineHighlight(BaseModel):+ """Compact, deterministic timeline emitted in the summary."""++ ts: datetime+ kind: str # "case", "comment", "task"+ label: str+ detail: str | None = None+++class CaseRecommendation(BaseModel):+ severity: str # "info" | "warning" | "critical"+ title: str+ body: str+++class CaseAutoSummary(BaseModel):+ """Top-level deterministic snapshot of a single case."""++ generated_at: datetime+ headline: str+ case: CaseSummaryHeader+ lifecycle: CaseLifecycleTimings+ coverage: CoverageSummary+ alerts: dict[str, Any] = Field(default_factory=dict) # {count, ids}+ observables: ObservableSummary+ evidence: EvidenceSummary+ tasks: TaskBreakdown+ comments: CommentBreakdown+ timeline: list[TimelineHighlight] = Field(default_factory=list)+ recommendations: list[CaseRecommendation] = Field(default_factory=list)+++# ---------------------------------------------------------------------------+# Pure-data input rows — what the orchestrator hands to the builder.+# Kept as plain dataclasses so tests are independent of SQLAlchemy.+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class SummaryCaseRow:+ """The subset of ``aisoc_cases`` we need for the summary."""++ id: uuid.UUID+ case_number: str | None+ title: str+ description: str | None+ severity: str+ status: str+ assignee: str | None+ created_by: str | None+ tags: dict[str, Any]+ mitre_techniques: list[str]+ alert_ids: list[str]+ observable_graph: dict[str, Any]+ evidence_chain: list[Any]+ compliance_frameworks: list[str]+ opened_at: datetime+ triaged_at: datetime | None+ resolved_at: datetime | None+ closed_at: datetime | None+ sla_due_at: datetime | None+ created_at: datetime+ updated_at: datetime+++@dataclass(frozen=True)+class SummaryCommentRow:+ author: str | None+ body: str+ is_system: bool+ created_at: datetime+++@dataclass(frozen=True)+class SummaryTaskRow:+ title: str+ status: str # 'todo' | 'in_progress' | 'done'+ assignee: str | None+ due_at: datetime | None+ created_at: datetime+ updated_at: datetime+++@dataclass+class CaseSummaryInputs:+ """Bundle of pre-fetched rows for a single case."""++ case: SummaryCaseRow+ comments: list[SummaryCommentRow] = field(default_factory=list)+ tasks: list[SummaryTaskRow] = field(default_factory=list)+++# ---------------------------------------------------------------------------+# Pure helpers (independently unit-tested).+# ---------------------------------------------------------------------------+++# Best-effort technique → tactic mapping. We only group what we know about;+# unknown techniques fall into "Other" so the summary stays useful even when+# the detection content drifts ahead of this static map.+#+# Source: MITRE ATT&CK Enterprise tactics. We deliberately keep a small,+# stable set here rather than pulling in a heavy dependency — the summary+# is meant to be deterministic and cheap to render.+_TECHNIQUE_TO_TACTIC: dict[str, str] = {+ "T1078": "Initial Access",+ "T1059": "Execution",+ "T1547": "Persistence",+ "T1098": "Persistence",+ "T1068": "Privilege Escalation",+ "T1055": "Privilege Escalation",+ "T1036": "Defense Evasion",+ "T1027": "Defense Evasion",+ "T1110": "Credential Access",+ "T1003": "Credential Access",+ "T1018": "Discovery",+ "T1057": "Discovery",+ "T1082": "Discovery",+ "T1021": "Lateral Movement",+ "T1005": "Collection",+ "T1119": "Collection",+ "T1071": "Command and Control",+ "T1105": "Command and Control",+ "T1041": "Exfiltration",+ "T1486": "Impact",+ "T1490": "Impact",+}+++def _hours_between(later: datetime | None, earlier: datetime | None) -> float | None:+ if later is None or earlier is None:+ return None+ delta = later - earlier+ return round(delta.total_seconds() / 3600, 2)+++def _bucket_techniques(techniques: list[str]) -> dict[str, int]:+ """Group ATT&CK techniques into their parent tactics (best-effort)."""+ buckets: Counter[str] = Counter()+ for tech in techniques:+ if not isinstance(tech, str):+ continue+ # Use the parent (T1059.001 → T1059) for the lookup.+ root = tech.split(".")[0].strip().upper()+ tactic = _TECHNIQUE_TO_TACTIC.get(root, "Other")+ buckets[tactic] += 1+ return dict(buckets)+++def _summarise_observables(graph: dict[str, Any]) -> ObservableSummary:+ nodes = graph.get("nodes") if isinstance(graph, dict) else None+ edges = graph.get("edges") if isinstance(graph, dict) else None+ nodes_list = nodes if isinstance(nodes, list) else []+ edges_list = edges if isinstance(edges, list) else []++ kind_counter: Counter[str] = Counter()+ for node in nodes_list:+ if not isinstance(node, dict):+ continue+ kind = node.get("kind") or node.get("type") or "unknown"+ kind_counter[str(kind)] += 1++ return ObservableSummary(+ total_nodes=len(nodes_list),+ total_edges=len(edges_list),+ node_kind_counts=dict(kind_counter),+ distinct_kinds=sorted(kind_counter.keys()),+ )+++def _summarise_evidence(items: list[Any]) -> EvidenceSummary:+ if not isinstance(items, list):+ return EvidenceSummary()+ kinds: set[str] = set()+ for item in items:+ if isinstance(item, dict):+ kind = item.get("kind") or item.get("type")+ if isinstance(kind, str) and kind:+ kinds.add(kind)+ return EvidenceSummary(total_items=len(items), distinct_kinds=sorted(kinds))+++def _summarise_tasks(rows: list[SummaryTaskRow], *, now: datetime) -> TaskBreakdown:+ counts: Counter[str] = Counter()+ overdue = 0+ for row in rows:+ counts[row.status] += 1+ if (+ row.status != "done"+ and row.due_at is not None+ and row.due_at < now+ ):+ overdue += 1+ return TaskBreakdown(+ total=len(rows),+ todo=counts.get("todo", 0),+ in_progress=counts.get("in_progress", 0),+ done=counts.get("done", 0),+ overdue=overdue,+ )+++def _summarise_comments(rows: list[SummaryCommentRow]) -> CommentBreakdown:+ analyst = 0+ system = 0+ authors: set[str] = set()+ for row in rows:+ if row.is_system:+ system += 1+ else:+ analyst += 1+ if row.author:+ authors.add(row.author)+ return CommentBreakdown(+ total=len(rows),+ analyst=analyst,+ system=system,+ distinct_authors=sorted(authors),+ )+++def _build_timeline(+ case: SummaryCaseRow,+ comments: list[SummaryCommentRow],+ tasks: list[SummaryTaskRow],+ *,+ limit: int = 25,+) -> list[TimelineHighlight]:+ """Merge case lifecycle events, comments, and tasks into a sorted feed.++ Sort order is strictly chronological, capped to ``limit`` items so the+ summary stays board-ready (recipients should be able to skim it).+ """+ events: list[TimelineHighlight] = []++ events.append(+ TimelineHighlight(ts=case.opened_at, kind="case", label="Case opened")+ )+ if case.triaged_at:+ events.append(+ TimelineHighlight(ts=case.triaged_at, kind="case", label="Triaged")+ )+ if case.resolved_at:+ events.append(+ TimelineHighlight(ts=case.resolved_at, kind="case", label="Resolved")+ )+ if case.closed_at:+ events.append(+ TimelineHighlight(ts=case.closed_at, kind="case", label="Closed")+ )++ for c in comments:+ body_excerpt = (c.body or "").strip().replace("\n", " ")+ if len(body_excerpt) > 140:+ body_excerpt = body_excerpt[:137] + "…"+ events.append(+ TimelineHighlight(+ ts=c.created_at,+ kind="comment",+ label=("System note" if c.is_system else "Analyst note") + (+ f" — {c.author}" if c.author and not c.is_system else ""+ ),+ detail=body_excerpt or None,+ )+ )++ for t in tasks:+ events.append(+ TimelineHighlight(+ ts=t.created_at,+ kind="task",+ label=f"Task created — {t.title}",+ detail=f"status={t.status}"+ + (f" · assignee={t.assignee}" if t.assignee else ""),+ )+ )++ events.sort(key=lambda e: e.ts)+ if len(events) <= limit:+ return events++ # Always keep the case lifecycle events; trim comments/tasks if needed.+ lifecycle = [e for e in events if e.kind == "case"]+ other = [e for e in events if e.kind != "case"]+ keep_other = max(limit - len(lifecycle), 0)+ other = other[-keep_other:] if keep_other else []+ merged = sorted(lifecycle + other, key=lambda e: e.ts)+ return merged+++def _build_headline(+ case: SummaryCaseRow,+ lifecycle: CaseLifecycleTimings,+ tasks: TaskBreakdown,+ coverage: CoverageSummary,+) -> str:+ parts: list[str] = []+ label = case.case_number or str(case.id)[:8]+ parts.append(f"{label} {case.severity.upper()}")+ parts.append(case.status)+ if lifecycle.time_to_resolve_hours is not None:+ parts.append(f"resolved in {lifecycle.time_to_resolve_hours:.1f}h")+ if tasks.total:+ parts.append(f"{tasks.done}/{tasks.total} tasks done")+ if coverage.mitre_techniques:+ parts.append(f"{len(coverage.mitre_techniques)} ATT&CK techniques")+ return " · ".join(parts)+++def _build_recommendations(+ case: SummaryCaseRow,+ lifecycle: CaseLifecycleTimings,+ tasks: TaskBreakdown,+ comments: CommentBreakdown,+ coverage: CoverageSummary,+) -> list[CaseRecommendation]:+ """Heuristic, deterministic post-mortem call-to-actions.++ Designed to nudge the analyst toward the right archival hygiene without+ being prescriptive. Every threshold here is fixed and explainable.+ """+ recs: list[CaseRecommendation] = []++ if lifecycle.sla_breached:+ recs.append(+ CaseRecommendation(+ severity="warning",+ title="SLA breach on this case",+ body=(+ "The case ran past its SLA. Capture the cause (analyst load, "+ "missing playbook, escalation gap) so the post-mortem reaches "+ "the on-call rotation."+ ),+ )+ )++ if tasks.overdue:+ recs.append(+ CaseRecommendation(+ severity="warning",+ title=f"{tasks.overdue} overdue task{'s' if tasks.overdue != 1 else ''}",+ body=(+ "Tasks past their due date are still open. Close them out or "+ "reassign before archiving the case."+ ),+ )+ )++ if (+ case.severity in {"high", "critical"}+ and comments.analyst == 0+ ):+ recs.append(+ CaseRecommendation(+ severity="warning",+ title="No analyst notes on a high-severity case",+ body=(+ "A high or critical case is closing without any analyst "+ "narrative. Add a closing note explaining root cause + "+ "remediation before archival."+ ),+ )+ )++ if not coverage.mitre_techniques:+ recs.append(+ CaseRecommendation(+ severity="info",+ title="No MITRE ATT&CK coverage tagged",+ body=(+ "Tagging at least one technique improves coverage reporting "+ "and helps tune the detection set. Update the case before "+ "archival if applicable."+ ),+ )+ )++ if (+ lifecycle.time_to_resolve_hours is not None+ and lifecycle.time_to_resolve_hours > 24+ ):+ recs.append(+ CaseRecommendation(+ severity="info",+ title=f"MTTR on this case was {lifecycle.time_to_resolve_hours:.1f}h",+ body=(+ "Resolution exceeded 24h. Consider whether automation, a new "+ "playbook, or runbook updates would compress the next "+ "occurrence."+ ),+ )+ )++ if not recs:+ recs.append(+ CaseRecommendation(+ severity="info",+ title="Case closed cleanly",+ body=(+ "All headline metrics look healthy. Archive this case and "+ "fold any new IOCs into your detection content."+ ),+ )+ )++ return recs+++# ---------------------------------------------------------------------------+# Pure top-level builder.+# ---------------------------------------------------------------------------+++def build_summary_from_rows(+ inputs: CaseSummaryInputs,+ *,+ now: datetime | None = None,+) -> CaseAutoSummary:+ """Pure function: rows in → ``CaseAutoSummary`` out. Deterministic."""+ moment = now or datetime.now(UTC)+ case = inputs.case++ lifecycle = CaseLifecycleTimings(+ opened_at=case.opened_at,+ triaged_at=case.triaged_at,+ resolved_at=case.resolved_at,+ closed_at=case.closed_at,+ sla_due_at=case.sla_due_at,+ time_to_triage_hours=_hours_between(case.triaged_at, case.opened_at),+ time_to_resolve_hours=_hours_between(case.resolved_at, case.opened_at),+ time_to_close_hours=_hours_between(case.closed_at, case.opened_at),+ sla_breached=bool(+ case.sla_due_at+ and (case.resolved_at or case.closed_at or moment) > case.sla_due_at+ ),+ )++ coverage = CoverageSummary(+ mitre_techniques=list(case.mitre_techniques or []),+ mitre_tactic_buckets=_bucket_techniques(list(case.mitre_techniques or [])),+ compliance_frameworks=list(case.compliance_frameworks or []),+ )++ observables = _summarise_observables(case.observable_graph or {})+ evidence = _summarise_evidence(case.evidence_chain or [])+ tasks = _summarise_tasks(inputs.tasks, now=moment)+ comments = _summarise_comments(inputs.comments)+ timeline = _build_timeline(case, inputs.comments, inputs.tasks)+ headline = _build_headline(case, lifecycle, tasks, coverage)+ recommendations = _build_recommendations(case, lifecycle, tasks, comments, coverage)++ return CaseAutoSummary(+ generated_at=moment,+ headline=headline,+ case=CaseSummaryHeader(+ case_id=case.id,+ case_number=case.case_number,+ title=case.title,+ description=case.description,+ severity=case.severity,+ status=case.status,+ assignee=case.assignee,+ created_by=case.created_by,+ tags=dict(case.tags or {}),+ ),+ lifecycle=lifecycle,+ coverage=coverage,+ alerts={+ "count": len(case.alert_ids or []),+ "ids": [str(a) for a in (case.alert_ids or [])][:25],+ },+ observables=observables,+ evidence=evidence,+ tasks=tasks,+ comments=comments,+ timeline=timeline,+ recommendations=recommendations,+ )+++# ---------------------------------------------------------------------------+# DB orchestrator — the only place SQL lives.+# ---------------------------------------------------------------------------+++def _row_to_summary_case(row: Any) -> SummaryCaseRow:+ """Map a raw ``aisoc_cases`` row to our pure dataclass."""+ techniques = row.mitre_techniques or []+ if isinstance(techniques, list):+ flat: list[str] = []+ for t in techniques:+ if isinstance(t, str):+ flat.append(t)+ elif isinstance(t, dict):+ tid = t.get("id") or t.get("technique_id") or t.get("name")+ if tid:+ flat.append(str(tid))+ techniques = flat+ else:+ techniques = []++ return SummaryCaseRow(+ id=row.id,+ case_number=getattr(row, "case_number", None),+ title=row.title,+ description=row.description,+ severity=row.severity,+ status=row.status,+ assignee=row.assignee,+ created_by=row.created_by,+ tags=dict(row.tags or {}) if isinstance(row.tags, dict) else {},+ mitre_techniques=techniques,+ alert_ids=[str(a) for a in (row.alert_ids or [])],+ observable_graph=dict(row.observable_graph or {})+ if isinstance(row.observable_graph, dict)+ else {},+ evidence_chain=list(row.evidence_chain or [])+ if isinstance(row.evidence_chain, list)+ else [],+ compliance_frameworks=list(row.compliance_frameworks or []),+ opened_at=row.opened_at,+ triaged_at=row.triaged_at,+ resolved_at=row.resolved_at,+ closed_at=row.closed_at,+ sla_due_at=getattr(row, "sla_due_at", None),+ created_at=row.created_at,+ updated_at=row.updated_at,+ )+++async def _fetch_case_for_summary(db: AsyncSession, case_id: uuid.UUID) -> SummaryCaseRow | None:+ row = (+ await db.execute(+ text("SELECT * FROM aisoc_cases WHERE id = :id").bindparams(id=case_id)+ )+ ).fetchone()+ return _row_to_summary_case(row) if row else None+++async def _fetch_comments(db: AsyncSession, case_id: uuid.UUID) -> list[SummaryCommentRow]:+ rows = (+ await db.execute(+ text(+ "SELECT author, body, is_system, created_at "+ "FROM aisoc_case_comments WHERE case_id = :id ORDER BY created_at"+ ).bindparams(id=case_id)+ )+ ).fetchall()+ return [+ SummaryCommentRow(+ author=r.author,+ body=r.body or "",+ is_system=bool(r.is_system),+ created_at=r.created_at,+ )+ for r in rows+ ]+++async def _fetch_tasks(db: AsyncSession, case_id: uuid.UUID) -> list[SummaryTaskRow]:+ """Pull tasks; tolerate the absence of ``aisoc_case_tasks`` on older deployments."""+ try:+ rows = (+ await db.execute(+ text(+ "SELECT title, status, assignee, due_at, created_at, updated_at "+ "FROM aisoc_case_tasks WHERE case_id = :id ORDER BY created_at"+ ).bindparams(id=case_id)+ )+ ).fetchall()+ except Exception: # pragma: no cover — defensive: missing table on older DBs.+ return []+ return [+ SummaryTaskRow(+ title=r.title,+ status=r.status or "todo",+ assignee=r.assignee,+ due_at=r.due_at,+ created_at=r.created_at,+ updated_at=r.updated_at,+ )+ for r in rows+ ]+++async def build_case_summary(+ db: AsyncSession,+ case_id: uuid.UUID,+ *,+ now: datetime | None = None,+) -> CaseAutoSummary | None:+ """Async orchestrator: pull rows for a single case and build the summary.++ Returns ``None`` if the case isn't found, so endpoints can surface a+ clean 404 without conflating the data layer with HTTP semantics.+ """+ case = await _fetch_case_for_summary(db, case_id)+ if case is None:+ return None+ comments = await _fetch_comments(db, case_id)+ tasks = await _fetch_tasks(db, case_id)+ inputs = CaseSummaryInputs(case=case, comments=comments, tasks=tasks)+ return build_summary_from_rows(inputs, now=now)+++# Dummy import to keep timedelta usage explicit & lint-clean (used in tests).+_unused = timedelta(seconds=0)+++__all__ = [+ "CaseAutoSummary",+ "CaseLifecycleTimings",+ "CaseRecommendation",+ "CaseSummaryHeader",+ "CaseSummaryInputs",+ "CommentBreakdown",+ "CoverageSummary",+ "EvidenceSummary",+ "ObservableSummary",+ "SummaryCaseRow",+ "SummaryCommentRow",+ "SummaryTaskRow",+ "TaskBreakdown",+ "TimelineHighlight",+ "build_case_summary",+ "build_summary_from_rows",+]+++# Internal helpers exported for tests.+_internal_helpers: dict[str, Any] = {+ "_hours_between": _hours_between,+ "_bucket_techniques": _bucket_techniques,+ "_summarise_observables": _summarise_observables,+ "_summarise_evidence": _summarise_evidence,+ "_summarise_tasks": _summarise_tasks,+ "_summarise_comments": _summarise_comments,+ "_build_timeline": _build_timeline,+ "_build_headline": _build_headline,+ "_build_recommendations": _build_recommendations,+}diff --git a/services/api/app/services/case_summary_html.py b/services/api/app/services/case_summary_html.pynew file mode 100644index 000000000..e9eae518c--- /dev/null+++ b/services/api/app/services/case_summary_html.py@@ -0,0 +1,338 @@+"""HTML renderer for the per-case auto-summary.++WS-D2 — buyer-value plan+========================+Produces a self-contained, print-ready document for a ``CaseAutoSummary``.+Mirrors the design language of the executive digest renderer (WS-G2) so+operators get a consistent visual identity across reports — but the data+shape is per-case, not tenant-wide.++Design goals+------------+* Pure function: same summary in, same HTML out (deterministic).+* Inline CSS only, so the document is portable when downloaded.+* Print-friendly typography and colour-blind-safe palette.+* Defensive HTML escaping — every field touches tenant data.+"""++from __future__ import annotations++import html+from datetime import UTC, datetime++from .case_summary import (+ CaseAutoSummary,+ CaseLifecycleTimings,+ CaseRecommendation,+ CaseSummaryHeader,+ CommentBreakdown,+ CoverageSummary,+ EvidenceSummary,+ ObservableSummary,+ TaskBreakdown,+ TimelineHighlight,+)+++_SEVERITY_COLOURS: dict[str, str] = {+ "critical": "#b91c1c",+ "high": "#c2410c",+ "medium": "#a16207",+ "low": "#1d4ed8",+ "info": "#475569",+}++_REC_COLOURS: dict[str, str] = {+ "critical": "#b91c1c",+ "warning": "#a16207",+ "info": "#1d4ed8",+}+++def _esc(value: object) -> str:+ return html.escape("" if value is None else str(value))+++def _fmt_hours(hours: float | None) -> str:+ if hours is None:+ return "—"+ if hours < 1:+ return f"{round(hours * 60)}m"+ return f"{hours:.1f}h"+++def _fmt_datetime(value: datetime | None) -> str:+ if value is None:+ return "—"+ return value.strftime("%Y-%m-%d %H:%M UTC")+++def _severity_chip(severity: str) -> str:+ colour = _SEVERITY_COLOURS.get(severity, "#475569")+ return (+ f'<span style="display:inline-block;padding:2px 8px;border-radius:9999px;'+ f'background:{colour};color:#fff;font-size:11px;text-transform:uppercase;'+ f'letter-spacing:0.04em;">{_esc(severity)}</span>'+ )+++def _kpi(label: str, value: str, *, hint: str | None = None) -> str:+ hint_html = (+ f'<div style="font-size:11px;color:#64748b;margin-top:2px;">{_esc(hint)}</div>'+ if hint+ else ""+ )+ return (+ '<div style="flex:1 1 140px;background:#f8fafc;border:1px solid #e2e8f0;'+ 'border-radius:8px;padding:12px 14px;min-width:140px;">'+ f'<div style="font-size:11px;color:#64748b;text-transform:uppercase;'+ f'letter-spacing:0.06em;">{_esc(label)}</div>'+ f'<div style="font-size:22px;font-weight:600;color:#0f172a;'+ f'margin-top:4px;">{_esc(value)}</div>'+ f"{hint_html}</div>"+ )+++def _header_block(case: CaseSummaryHeader, lifecycle: CaseLifecycleTimings, headline: str) -> str:+ label = case.case_number or str(case.case_id)[:8]+ return (+ '<header>'+ '<div style="font-size:11px;color:#64748b;text-transform:uppercase;'+ 'letter-spacing:0.08em;">AiSOC case auto-summary</div>'+ f'<h1>{_esc(label)} — {_esc(case.title)}</h1>'+ f'<div style="margin-top:6px;">{_severity_chip(case.severity)} '+ f'<span style="display:inline-block;padding:2px 8px;border-radius:9999px;'+ f'background:#e2e8f0;color:#0f172a;font-size:11px;margin-left:6px;">'+ f'{_esc(case.status)}</span></div>'+ f'<div style="color:#334155;font-size:14px;margin-top:8px;">{_esc(headline)}</div>'+ f'<div style="color:#94a3b8;font-size:11px;margin-top:6px;">'+ f'Case {_esc(case.case_id)} · '+ f'opened {_fmt_datetime(lifecycle.opened_at)} · '+ f'generated {_fmt_datetime(datetime.now(UTC))}</div>'+ '</header>'+ )+++def _description_block(case: CaseSummaryHeader) -> str:+ if not case.description:+ return ""+ return (+ '<div style="background:#f8fafc;border:1px solid #e2e8f0;'+ 'border-radius:8px;padding:12px 14px;margin-top:14px;color:#0f172a;'+ f'font-size:13px;line-height:1.55;">{_esc(case.description)}</div>'+ )+++def _kpi_strip(summary: CaseAutoSummary) -> str:+ lifecycle = summary.lifecycle+ return (+ '<div style="display:flex;flex-wrap:wrap;gap:12px;">'+ + _kpi("Opened", _fmt_datetime(lifecycle.opened_at))+ + _kpi("Triaged", _fmt_datetime(lifecycle.triaged_at))+ + _kpi("Resolved", _fmt_datetime(lifecycle.resolved_at))+ + _kpi("Closed", _fmt_datetime(lifecycle.closed_at))+ + _kpi("Time to triage", _fmt_hours(lifecycle.time_to_triage_hours))+ + _kpi("Time to resolve", _fmt_hours(lifecycle.time_to_resolve_hours))+ + _kpi("Time to close", _fmt_hours(lifecycle.time_to_close_hours))+ + _kpi(+ "SLA",+ "Breached" if lifecycle.sla_breached else "Met",+ hint=_fmt_datetime(lifecycle.sla_due_at) if lifecycle.sla_due_at else None,+ )+ + "</div>"+ )+++def _coverage_block(coverage: CoverageSummary) -> str:+ techniques = coverage.mitre_techniques+ tactic_rows = ""+ if coverage.mitre_tactic_buckets:+ tactic_rows = (+ '<table style="width:100%;border-collapse:collapse;font-size:13px;'+ 'margin-top:8px;"><thead><tr style="text-align:left;color:#64748b;'+ 'font-size:11px;text-transform:uppercase;letter-spacing:0.06em;">'+ '<th style="padding:6px 8px;">Tactic</th>'+ '<th style="padding:6px 8px;text-align:right;">Techniques</th></tr></thead>'+ "<tbody>"+ + "".join(+ f'<tr><td style="padding:6px 8px;">{_esc(tactic)}</td>'+ f'<td style="padding:6px 8px;text-align:right;font-weight:600;">{count}</td></tr>'+ for tactic, count in sorted(+ coverage.mitre_tactic_buckets.items(),+ key=lambda x: (-x[1], x[0]),+ )+ )+ + "</tbody></table>"+ )++ technique_chips = (+ '<div style="margin-top:8px;display:flex;flex-wrap:wrap;gap:6px;">'+ + "".join(+ f'<span style="padding:2px 8px;border-radius:9999px;background:#eef2ff;'+ f'color:#3730a3;font-size:11px;">{_esc(t)}</span>'+ for t in techniques+ )+ + "</div>"+ if techniques+ else '<p style="color:#64748b;font-size:13px;">No MITRE techniques tagged.</p>'+ )++ frameworks = (+ '<div style="margin-top:8px;display:flex;flex-wrap:wrap;gap:6px;">'+ + "".join(+ f'<span style="padding:2px 8px;border-radius:9999px;background:#ecfdf5;'+ f'color:#047857;font-size:11px;">{_esc(f)}</span>'+ for f in coverage.compliance_frameworks+ )+ + "</div>"+ if coverage.compliance_frameworks+ else '<p style="color:#64748b;font-size:13px;">No compliance frameworks tagged.</p>'+ )++ return (+ '<h2>MITRE ATT&CK techniques</h2>'+ + technique_chips+ + tactic_rows+ + '<h2>Compliance frameworks</h2>'+ + frameworks+ )+++def _evidence_block(+ observables: ObservableSummary,+ evidence: EvidenceSummary,+ alerts: dict[str, object],+) -> str:+ return (+ '<h2>Evidence & observables</h2>'+ '<div style="display:flex;flex-wrap:wrap;gap:12px;">'+ + _kpi("Linked alerts", str(alerts.get("count", 0)))+ + _kpi(+ "Observables",+ f"{observables.total_nodes} nodes",+ hint=f"{observables.total_edges} edges",+ )+ + _kpi(+ "Evidence items",+ str(evidence.total_items),+ hint=", ".join(evidence.distinct_kinds) or None,+ )+ + "</div>"+ )+++def _activity_block(tasks: TaskBreakdown, comments: CommentBreakdown) -> str:+ overdue_hint = f"{tasks.overdue} overdue" if tasks.overdue else None+ authors_hint = ", ".join(comments.distinct_authors[:3]) if comments.distinct_authors else None+ return (+ '<h2>Activity</h2>'+ '<div style="display:flex;flex-wrap:wrap;gap:12px;">'+ + _kpi("Tasks (total)", str(tasks.total))+ + _kpi("Tasks done", str(tasks.done), hint=overdue_hint)+ + _kpi(+ "Tasks open",+ str(tasks.todo + tasks.in_progress),+ hint=f"{tasks.todo} todo · {tasks.in_progress} in progress",+ )+ + _kpi("Analyst notes", str(comments.analyst), hint=authors_hint)+ + _kpi("System notes", str(comments.system))+ + "</div>"+ )+++def _timeline_block(events: list[TimelineHighlight]) -> str:+ if not events:+ return ""+ rows = "".join(+ '<tr>'+ f'<td style="padding:6px 8px;color:#64748b;font-size:11px;'+ f'white-space:nowrap;">{_fmt_datetime(e.ts)}</td>'+ f'<td style="padding:6px 8px;color:#475569;font-size:11px;text-transform:uppercase;'+ f'letter-spacing:0.06em;">{_esc(e.kind)}</td>'+ f'<td style="padding:6px 8px;color:#0f172a;">{_esc(e.label)}</td>'+ f'<td style="padding:6px 8px;color:#475569;font-size:12px;">'+ f'{_esc(e.detail) if e.detail else "—"}</td>'+ '</tr>'+ for e in events+ )+ return (+ '<h2>Timeline</h2>'+ '<table style="width:100%;border-collapse:collapse;font-size:13px;">'+ '<thead><tr style="text-align:left;color:#64748b;font-size:11px;'+ 'text-transform:uppercase;letter-spacing:0.06em;">'+ '<th style="padding:6px 8px;">When</th>'+ '<th style="padding:6px 8px;">Kind</th>'+ '<th style="padding:6px 8px;">Label</th>'+ '<th style="padding:6px 8px;">Detail</th></tr></thead>'+ f"<tbody>{rows}</tbody></table>"+ )+++def _recommendation_block(recs: list[CaseRecommendation]) -> str:+ if not recs:+ return ""+ cards = "".join(+ '<div style="border-left:4px solid {colour};background:#f8fafc;'+ 'padding:12px 14px;border-radius:6px;margin-bottom:10px;">'+ '<div style="font-weight:600;color:#0f172a;font-size:14px;'+ f'margin-bottom:4px;">{_esc(r.title)}</div>'+ f'<div style="color:#334155;font-size:13px;line-height:1.45;">{_esc(r.body)}</div>'+ "</div>".format(colour=_REC_COLOURS.get(r.severity, "#475569"))+ for r in recs+ )+ return '<h2>Post-mortem</h2>' + cards+++def render_case_summary_html(summary: CaseAutoSummary) -> str:+ """Render a ``CaseAutoSummary`` to a self-contained HTML document."""+ return f"""<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="utf-8">+<title>AiSOC Case Summary — {_esc(summary.case.case_number or summary.case.title)}</title>+<style>+ @page {{ margin: 18mm; }}+ body {{+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+ color: #0f172a;+ background: #ffffff;+ margin: 0;+ padding: 24px 32px;+ line-height: 1.45;+ }}+ h1, h2, h3 {{ color: #0f172a; margin-top: 0; }}+ h1 {{ font-size: 22px; margin-bottom: 4px; }}+ h2 {{ font-size: 15px; text-transform: uppercase; letter-spacing: 0.08em; color: #475569; margin: 20px 0 10px; border-top: 1px solid #e2e8f0; padding-top: 14px; }}+ table th, table td {{ border-bottom: 1px solid #f1f5f9; }}+ @media print {{+ body {{ padding: 0; }}+ h2 {{ page-break-after: avoid; }}+ }}+</style>+</head>+<body>+ {_header_block(summary.case, summary.lifecycle, summary.headline)}+ {_description_block(summary.case)}++ <h2>Lifecycle</h2>+ {_kpi_strip(summary)}++ {_coverage_block(summary.coverage)}++ {_evidence_block(summary.observables, summary.evidence, summary.alerts)}++ {_activity_block(summary.tasks, summary.comments)}++ {_timeline_block(summary.timeline)}++ {_recommendation_block(summary.recommendations)}++ <footer style="margin-top:32px;color:#94a3b8;font-size:11px;text-align:center;">+ AiSOC — open-source AI Security Operations Center.+ Print this page (Ctrl/Cmd-P → Save as PDF) for case-file archival.+ </footer>+</body>+</html>"""+++__all__ = ["render_case_summary_html"]diff --git a/services/api/tests/test_case_summary.py b/services/api/tests/test_case_summary.pynew file mode 100644index 000000000..53e33e5b6--- /dev/null+++ b/services/api/tests/test_case_summary.py@@ -0,0 +1,388 @@+"""Tests for WS-D2 — per-case auto-summary builder + HTML renderer.++Mirrors the structure of ``test_executive_digest`` so the two artefacts stay+consistent: pure builder gets exercised against deterministic input rows, and+the HTML renderer is verified end-to-end for structure + safe escaping.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta++import pytest+from app.services.case_summary import (+ CaseSummaryInputs,+ SummaryCaseRow,+ SummaryCommentRow,+ SummaryTaskRow,+ _internal_helpers,+ build_summary_from_rows,+)+from app.services.case_summary_html import render_case_summary_html++OPENED = datetime(2026, 5, 2, 10, 0, tzinfo=UTC)+NOW = datetime(2026, 5, 9, 12, 0, tzinfo=UTC)+CASE_ID = uuid.uuid4()+++def _case(+ *,+ severity: str = "high",+ status: str = "resolved",+ opened_at: datetime | None = None,+ triaged_at: datetime | None = None,+ resolved_at: datetime | None = None,+ closed_at: datetime | None = None,+ sla_due_at: datetime | None = None,+ title: str = "Suspected ransomware",+ description: str | None = "Initial ransomware indicators on FIN-LAPTOP-04",+ assignee: str | None = "[email protected]",+ created_by: str | None = "alert-fusion",+ mitre_techniques: list[str] | None = None,+ alert_ids: list[str] | None = None,+ observable_graph: dict[str, object] | None = None,+ evidence_chain: list[object] | None = None,+ compliance_frameworks: list[str] | None = None,+ tags: dict[str, object] | None = None,+ case_number: str | None = "CASE-2026-0042",+) -> SummaryCaseRow:+ open_ts = opened_at or OPENED+ return SummaryCaseRow(+ id=CASE_ID,+ case_number=case_number,+ title=title,+ description=description,+ severity=severity,+ status=status,+ assignee=assignee,+ created_by=created_by,+ tags=tags or {},+ mitre_techniques=list(mitre_techniques or []),+ alert_ids=list(alert_ids or []),+ observable_graph=observable_graph or {},+ evidence_chain=list(evidence_chain or []),+ compliance_frameworks=list(compliance_frameworks or []),+ opened_at=open_ts,+ triaged_at=triaged_at,+ resolved_at=resolved_at,+ closed_at=closed_at,+ sla_due_at=sla_due_at,+ created_at=open_ts,+ updated_at=closed_at or resolved_at or triaged_at or open_ts,+ )+++# ---------------------------------------------------------------------------+# Pure helpers+# ---------------------------------------------------------------------------+++def test_hours_between_handles_missing_endpoints() -> None:+ fn = _internal_helpers["_hours_between"]+ assert fn(None, OPENED) is None+ assert fn(OPENED, None) is None+ assert fn(OPENED + timedelta(hours=3), OPENED) == 3.0+++def test_bucket_techniques_groups_known_and_unknowns() -> None:+ fn = _internal_helpers["_bucket_techniques"]+ buckets = fn(["T1059.001", "T1059", "T1486", "T9999", "junk"])+ # Two execution entries (sub-tech + parent), one impact, two unknowns.+ assert buckets["Execution"] == 2+ assert buckets["Impact"] == 1+ assert buckets["Other"] == 2+++def test_summarise_observables_counts_kinds() -> None:+ fn = _internal_helpers["_summarise_observables"]+ summary = fn(+ {+ "nodes": [+ {"kind": "host"},+ {"kind": "host"},+ {"kind": "user"},+ {"type": "ip"}, # tolerate "type" alias+ "garbage", # tolerate junk+ ],+ "edges": [{"src": 1, "dst": 2}, {"src": 2, "dst": 3}],+ }+ )+ assert summary.total_nodes == 5+ assert summary.total_edges == 2+ assert summary.node_kind_counts["host"] == 2+ assert "ip" in summary.distinct_kinds+++def test_summarise_evidence_counts_kinds() -> None:+ fn = _internal_helpers["_summarise_evidence"]+ summary = fn(+ [+ {"kind": "file_hash"},+ {"kind": "file_hash"},+ {"kind": "memory_dump"},+ "junk",+ ]+ )+ assert summary.total_items == 4+ assert summary.distinct_kinds == ["file_hash", "memory_dump"]+++def test_summarise_tasks_handles_overdue_and_status_counts() -> None:+ fn = _internal_helpers["_summarise_tasks"]+ rows = [+ SummaryTaskRow(+ title="Contain host",+ status="todo",+ assignee=None,+ due_at=NOW - timedelta(hours=1),+ created_at=OPENED,+ updated_at=OPENED,+ ),+ SummaryTaskRow(+ title="Pull memory",+ status="in_progress",+ assignee=None,+ due_at=NOW + timedelta(hours=2),+ created_at=OPENED,+ updated_at=OPENED,+ ),+ SummaryTaskRow(+ title="Reset password",+ status="done",+ assignee=None,+ due_at=NOW - timedelta(hours=2), # done tasks aren't overdue+ created_at=OPENED,+ updated_at=OPENED,+ ),+ ]+ summary = fn(rows, now=NOW)+ assert summary.total == 3+ assert summary.todo == 1+ assert summary.in_progress == 1+ assert summary.done == 1+ assert summary.overdue == 1+++def test_summarise_comments_separates_system_and_authors() -> None:+ fn = _internal_helpers["_summarise_comments"]+ rows = [+ SummaryCommentRow(author="alice", body="Looking", is_system=False, created_at=OPENED),+ SummaryCommentRow(author="bob", body="Joining", is_system=False, created_at=OPENED),+ SummaryCommentRow(author=None, body="auto", is_system=True, created_at=OPENED),+ ]+ summary = fn(rows)+ assert summary.total == 3+ assert summary.analyst == 2+ assert summary.system == 1+ assert summary.distinct_authors == ["alice", "bob"]+++def test_build_timeline_caps_to_limit_but_keeps_lifecycle() -> None:+ fn = _internal_helpers["_build_timeline"]+ case = _case(+ triaged_at=OPENED + timedelta(hours=1),+ resolved_at=OPENED + timedelta(hours=4),+ closed_at=OPENED + timedelta(hours=5),+ )+ comments = [+ SummaryCommentRow(+ author=f"a{i}",+ body=f"note {i}",+ is_system=False,+ created_at=OPENED + timedelta(minutes=i),+ )+ for i in range(50)+ ]+ timeline = fn(case, comments, [], limit=10)+ assert len(timeline) == 10+ # All 4 lifecycle events must survive truncation.+ lifecycle_kinds = sum(1 for e in timeline if e.kind == "case")+ assert lifecycle_kinds == 4+++def test_build_recommendations_sla_breach_triggers_warning() -> None:+ fn = _internal_helpers["_build_recommendations"]+ from app.services.case_summary import (+ CaseLifecycleTimings,+ CommentBreakdown,+ CoverageSummary,+ TaskBreakdown,+ )++ case = _case(severity="critical")+ lifecycle = CaseLifecycleTimings(+ opened_at=OPENED,+ sla_due_at=OPENED + timedelta(hours=2),+ resolved_at=OPENED + timedelta(hours=5),+ sla_breached=True,+ )+ recs = fn(+ case,+ lifecycle,+ TaskBreakdown(),+ CommentBreakdown(),+ CoverageSummary(),+ )+ assert any("SLA" in r.title for r in recs)+++# ---------------------------------------------------------------------------+# Pure top-level builder+# ---------------------------------------------------------------------------+++def baseline_inputs() -> CaseSummaryInputs:+ case = _case(+ triaged_at=OPENED + timedelta(hours=1),+ resolved_at=OPENED + timedelta(hours=6),+ closed_at=OPENED + timedelta(hours=8),+ sla_due_at=OPENED + timedelta(hours=4), # breach: resolved at +6h+ mitre_techniques=["T1486", "T1059.001", "T1003"],+ alert_ids=[str(uuid.uuid4()) for _ in range(3)],+ observable_graph={+ "nodes": [{"kind": "host"}, {"kind": "user"}, {"kind": "user"}],+ "edges": [{"src": 0, "dst": 1}],+ },+ evidence_chain=[{"kind": "file_hash"}, {"kind": "memory_dump"}],+ compliance_frameworks=["SOC2", "ISO27001"],+ )+ comments = [+ SummaryCommentRow(+ author="alice",+ body="Containing the host",+ is_system=False,+ created_at=OPENED + timedelta(minutes=15),+ ),+ SummaryCommentRow(+ author=None,+ body="Auto-triage routed to playbook PB-001",+ is_system=True,+ created_at=OPENED + timedelta(minutes=5),+ ),+ ]+ tasks = [+ SummaryTaskRow(+ title="Isolate host",+ status="done",+ assignee="alice",+ due_at=OPENED + timedelta(hours=1),+ created_at=OPENED,+ updated_at=OPENED + timedelta(hours=1),+ ),+ SummaryTaskRow(+ title="Reset credentials",+ status="todo",+ assignee=None,+ due_at=OPENED - timedelta(hours=1), # already overdue+ created_at=OPENED,+ updated_at=OPENED,+ ),+ ]+ return CaseSummaryInputs(case=case, comments=comments, tasks=tasks)+++def test_build_summary_basic_shape(baseline_inputs: CaseSummaryInputs) -> None:+ summary = build_summary_from_rows(baseline_inputs, now=NOW)++ assert summary.case.case_id == CASE_ID+ assert summary.case.case_number == "CASE-2026-0042"+ assert summary.case.severity == "high"++ # Lifecycle.+ assert summary.lifecycle.time_to_triage_hours == 1.0+ assert summary.lifecycle.time_to_resolve_hours == 6.0+ assert summary.lifecycle.time_to_close_hours == 8.0+ assert summary.lifecycle.sla_breached is True++ # Coverage.+ assert summary.coverage.mitre_techniques == ["T1486", "T1059.001", "T1003"]+ assert summary.coverage.compliance_frameworks == ["SOC2", "ISO27001"]+ # Tactic buckets should bucket T1486 → Impact, T1059.001 → Execution, T1003 → Credential Access.+ assert summary.coverage.mitre_tactic_buckets["Impact"] == 1+ assert summary.coverage.mitre_tactic_buckets["Execution"] == 1+ assert summary.coverage.mitre_tactic_buckets["Credential Access"] == 1++ # Activity counts.+ assert summary.tasks.total == 2+ assert summary.tasks.done == 1+ assert summary.tasks.todo == 1+ assert summary.tasks.overdue == 1+ assert summary.comments.analyst == 1+ assert summary.comments.system == 1++ # Alerts.+ assert summary.alerts["count"] == 3++ # Observables / evidence.+ assert summary.observables.total_nodes == 3+ assert summary.evidence.total_items == 2++ # Timeline non-empty + sorted.+ assert summary.timeline+ timestamps = [e.ts for e in summary.timeline]+ assert timestamps == sorted(timestamps)+++def test_build_summary_recommends_when_sla_breached(baseline_inputs: CaseSummaryInputs) -> None:+ summary = build_summary_from_rows(baseline_inputs, now=NOW)+ titles = [r.title for r in summary.recommendations]+ assert any("SLA" in t for t in titles)+ assert any("overdue" in t.lower() for t in titles)+++def test_build_summary_minimal_inputs_returns_neutral_recommendation() -> None:+ case = _case(+ status="closed",+ severity="low",+ triaged_at=OPENED + timedelta(minutes=5),+ resolved_at=OPENED + timedelta(minutes=20),+ closed_at=OPENED + timedelta(minutes=25),+ sla_due_at=None,+ mitre_techniques=["T1078"],+ )+ summary = build_summary_from_rows(CaseSummaryInputs(case=case), now=NOW)+ assert summary.recommendations+ # With nothing concerning, we get the neutral "case closed cleanly" rec.+ assert any("cleanly" in r.title.lower() for r in summary.recommendations)+++def test_build_summary_is_deterministic(baseline_inputs: CaseSummaryInputs) -> None:+ a = build_summary_from_rows(baseline_inputs, now=NOW).model_dump_json()+ b = build_summary_from_rows(baseline_inputs, now=NOW).model_dump_json()+ assert a == b+++# ---------------------------------------------------------------------------+# HTML renderer+# ---------------------------------------------------------------------------+++def test_render_case_summary_html_contains_sections(baseline_inputs: CaseSummaryInputs) -> None:+ summary = build_summary_from_rows(baseline_inputs, now=NOW)+ html = render_case_summary_html(summary)++ assert "<!DOCTYPE html>" in html+ assert "AiSOC case auto-summary" in html+ assert "Lifecycle" in html+ assert "MITRE ATT&CK techniques" in html+ assert "Compliance frameworks" in html+ assert "Evidence" in html+ assert "Activity" in html+ assert "Timeline" in html+ assert "Post-mortem" in html+++def test_render_case_summary_html_escapes_user_data() -> None:+ case = _case(+ title="<script>alert('xss')</script>",+ description="<img src=x onerror=alert(1)>",+ severity="critical",+ )+ summary = build_summary_from_rows(CaseSummaryInputs(case=case), now=NOW)+ html = render_case_summary_html(summary)++ assert "<script>alert" not in html+ assert "<script>alert" in html+ assert "<img src=x" not in html