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
feat(hunt-reports): a hunt that found something becomes a cited, exportable report
Beenu Arorad60e3a94d557
diff --git a/services/api/app/api/v1/endpoints/hunt_reports.py b/services/api/app/api/v1/endpoints/hunt_reports.pynew file mode 100644index 000000000..8268de167--- /dev/null+++ b/services/api/app/api/v1/endpoints/hunt_reports.py@@ -0,0 +1,215 @@+"""A hunt that found something, written up and exportable.++Depth plan 9.5.++* ``POST /hunt-reports/from-hunt/{saved_hunt_id}`` write one up+* ``POST /hunt-reports/from-retro-hunt/{sighting_id}`` write one up+* ``GET /hunt-reports`` list this tenant's+* ``GET /hunt-reports/{id}?format=json|html|pdf`` read or export++PDF goes through the same WeasyPrint path and the same unavailability error+as the weekly digest, deliberately. A second renderer would drift from the+first and the PDF would stop matching the page somebody approved; a second+error type would mean operators learning two messages for one missing+system library.+"""++from __future__ import annotations++import uuid+from typing import Annotated, Any++import structlog+from fastapi import APIRouter, Depends, HTTPException, Query, Request, status+from fastapi.responses import HTMLResponse, Response+from pydantic import BaseModel, Field+from sqlalchemy import text++from app.api.v1.deps import AuthUser, require_permission+from app.db.rls import TenantDBSession+from app.services.audit import emit_audit+from app.services.digest_pdf import WeasyPrintUnavailableError+from app.services.hunt_report import (+ HuntReportError,+ attach_ledger_citations,+ build_from_hunt,+ build_from_retro_hunt,+ persist,+ render_html,+ render_pdf,+)++logger = structlog.get_logger()++router = APIRouter(prefix="/hunt-reports", tags=["hunt-reports"])+++class BuildRequest(BaseModel):+ #: Attach to a case, which is also what pulls the agent's decisions into+ #: the citation list. Optional because a hunt can find something before+ #: anybody has decided it is a case — forcing the case first would mean+ #: opening one to find out whether you need it.+ case_id: uuid.UUID | None = None+++class HuntReportOut(BaseModel):+ id: str+ source_kind: str+ source_id: str+ case_id: str | None+ title: str+ what: str+ how: str+ where: str+ when: str+ citations: list[dict[str, Any]] = Field(default_factory=list)+ match_count: int+ generated_by: str+ created_at: str+++def _out(row: dict[str, Any]) -> HuntReportOut:+ return HuntReportOut(+ id=str(row["id"]),+ source_kind=row["source_kind"],+ source_id=str(row["source_id"]),+ case_id=str(row["case_id"]) if row.get("case_id") else None,+ title=row["title"],+ what=row["what"],+ how=row["how"],+ where=row["where"],+ when=row["when"],+ citations=list(row["citations"] or []),+ match_count=int(row["match_count"] or 0),+ generated_by=row["generated_by"],+ created_at=str(row["created_at"]),+ )+++async def _build(+ db: Any,+ current_user: Any,+ request: Request,+ *,+ source_kind: str,+ source_id: uuid.UUID,+ case_id: uuid.UUID | None,+) -> HuntReportOut:+ builder = build_from_hunt if source_kind == "hunt" else build_from_retro_hunt+ kwarg = "saved_hunt_id" if source_kind == "hunt" else "sighting_id"+ try:+ report = await builder(db, tenant_id=current_user.tenant_id, **{kwarg: source_id})+ report = await attach_ledger_citations(db, report, tenant_id=current_user.tenant_id, case_id=case_id)+ row = await persist(+ db,+ report,+ tenant_id=current_user.tenant_id,+ source_kind=source_kind,+ source_id=source_id,+ case_id=case_id,+ generated_by=current_user.api_key_prefix or current_user.email,+ )+ except HuntReportError as exc:+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc++ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="hunt_report:create",+ resource="hunt_report",+ resource_id=str(row["id"]),+ changes={"source_kind": source_kind, "citations": len(row["citations"] or [])},+ request=request,+ )+ await db.commit()+ return _out(row)++[email protected]("/from-hunt/{saved_hunt_id}", response_model=HuntReportOut, status_code=status.HTTP_201_CREATED)+async def from_hunt(+ saved_hunt_id: uuid.UUID,+ body: BuildRequest,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("reports:write"))],+) -> HuntReportOut:+ return await _build(db, current_user, request, source_kind="hunt", source_id=saved_hunt_id, case_id=body.case_id)+++ "/from-retro-hunt/{sighting_id}", response_model=HuntReportOut, status_code=status.HTTP_201_CREATED+)+async def from_retro_hunt(+ sighting_id: uuid.UUID,+ body: BuildRequest,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("reports:write"))],+) -> HuntReportOut:+ return await _build(+ db, current_user, request, source_kind="retro_hunt", source_id=sighting_id, case_id=body.case_id+ )++[email protected]("", response_model=list[HuntReportOut])+async def list_reports(+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("reports:read"))],+ case_id: uuid.UUID | None = Query(default=None),+ limit: int = Query(default=50, ge=1, le=200),+) -> list[HuntReportOut]:+ stmt = (+ "SELECT * FROM aisoc_hunt_reports WHERE tenant_id = :tenant_id "+ + ("AND case_id = :case_id " if case_id else "")+ + "ORDER BY created_at DESC LIMIT :limit"+ )+ params: dict[str, Any] = {"tenant_id": current_user.tenant_id, "limit": limit}+ if case_id:+ params["case_id"] = case_id+ rows = (await db.execute(text(stmt).bindparams(**params))).mappings().all() # noqa: S608 - the only variable is a literal clause above+ return [_out(dict(row)) for row in rows]++[email protected]("/{report_id}", response_model=None)+async def get_report(+ report_id: uuid.UUID,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("reports:read"))],+ fmt: str = Query("json", alias="format", pattern="^(json|html|pdf)$"),+) -> HuntReportOut | HTMLResponse | Response:+ row = (+ await db.execute(+ text("SELECT * FROM aisoc_hunt_reports WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ id=report_id, tenant_id=current_user.tenant_id+ )+ )+ ).mappings().one_or_none()+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such hunt report")++ record = dict(row)+ record["created_at"] = str(record["created_at"])++ if fmt == "html":+ return HTMLResponse(content=render_html(record))+ if fmt == "pdf":+ try:+ pdf = render_pdf(record)+ except WeasyPrintUnavailableError as exc:+ # 503 with the reason, and the message names the two formats that+ # do work. A missing system library should not read as "the+ # report is gone".+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc+ return Response(+ content=pdf,+ media_type="application/pdf",+ headers={"Content-Disposition": f'attachment; filename="aisoc-hunt-report-{report_id}.pdf"'},+ )+ return _out(record)diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex 5cadb3d76..5e87c1553 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -42,6 +42,7 @@ from app.api.v1.endpoints import (graph,graph_ws,health,+ hunt_reports,hunts,identity_graph,identity_timeline,@@ -317,6 +318,10 @@ api_router.include_router(posture.router)api_router.include_router(easm.router)api_router.include_router(identity_graph.router)api_router.include_router(reports.router)+# Depth 9.5: a natural-language hunt or a retro-hunt that found something+# becomes a readable, cited report, exportable through the same WeasyPrint+# path the weekly digest already uses.+api_router.include_router(hunt_reports.router)api_router.include_router(retro_hunts.router)# Wave 7 — customizable dashboard / report builderdiff --git a/services/api/app/services/hunt_report.py b/services/api/app/services/hunt_report.pynew file mode 100644index 000000000..5f077929c--- /dev/null+++ b/services/api/app/services/hunt_report.py@@ -0,0 +1,421 @@+"""Turn what a hunt found into something a person can read and cite.++Depth plan 9.5. A natural-language hunt produced rows; a retro-hunt produced+a ``retro_hunt_sightings`` row. Neither produced anything a person could+read, forward or file, and the report surface and the hunt surface did not+know about each other at all — ``grep -n hunt`` across ``report_builder.py``+and ``endpoints/reports.py`` returned nothing.++Four sections, in the order a reader asks+-----------------------------------------+What, how, where, when. Each is derived from facts already recorded, and a+section that cannot be derived stays **empty**. That is the whole discipline+here: a report is a thing somebody forwards to a manager or attaches to a+ticket, and a confident sentence about nothing is worse in that context than+a blank. :func:`build_hunt_report` never writes a sentence it cannot support+from a row.++Citations are not decoration+----------------------------+"With ledger citations" is the load-bearing half of the item. Every citation+names a ``kind``, an ``id`` and a human ``label``, so a renderer can link it+and an auditor can resolve it afterwards. A report that cites nothing is+refused at build time rather than stored — an uncited report is an+assertion, and this product's position is that an assertion is not evidence.++Why the counts are stored and not recomputed+--------------------------------------------+A report is a snapshot. Re-running the hunt tomorrow gives a different+number, and the report has to keep saying what it said when it was written —+the same reasoning that makes ``aisoc_outbound_deliveries`` store its+payload rather than re-serialise it on retry.+"""++from __future__ import annotations++import json+import uuid+from dataclasses import dataclass, field+from datetime import UTC, datetime+from html import escape+from typing import Any++from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession++SOURCE_KINDS: tuple[str, ...] = ("hunt", "retro_hunt")+++class HuntReportError(ValueError):+ """A refusal the caller can act on. Routes render it with the text."""+++@dataclass+class HuntReport:+ """The four sections, their citations, and what produced them."""++ title: str+ what: str = ""+ how: str = ""+ where: str = ""+ when: str = ""+ citations: list[dict[str, str]] = field(default_factory=list)+ match_count: int = 0++ def is_citable(self) -> bool:+ return bool(self.citations)+++def _cite(kind: str, identifier: Any, label: str) -> dict[str, str]:+ return {"kind": kind, "id": str(identifier), "label": label}+++# ---------------------------------------------------------------------------+# From a saved natural-language hunt+# ---------------------------------------------------------------------------+++async def build_from_hunt(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ saved_hunt_id: uuid.UUID,+) -> HuntReport:+ """Write a report for what a saved hunt matched.++ Refuses when the hunt has never run or matched nothing. "A hunt that+ finds something produces a report" is the item's own wording, and a+ report saying a hunt found nothing is a thing nobody forwards — the+ saved-hunt list already shows that.+ """+ hunt = (+ await db.execute(+ text(+ "SELECT id, name, nl_query, translated_query, language, last_run_at, "+ " created_by, created_at "+ "FROM aisoc_saved_hunts WHERE id = :id AND tenant_id = :tenant_id"+ ).bindparams(id=saved_hunt_id, tenant_id=tenant_id)+ )+ ).mappings().one_or_none()+ if hunt is None:+ raise HuntReportError("No such saved hunt in this tenant.")+ if hunt["last_run_at"] is None:+ raise HuntReportError(+ f"{hunt['name']!r} has never run, so there is nothing to report. "+ "Run the hunt first; a report of a hunt that has not executed would be a "+ "statement about a query rather than about the estate."+ )++ # What the hunt matched, now. Alerts carry the hunt's own id when fusion+ # raised them from it; a hunt that matched events without raising alerts+ # is reported by its run metadata alone and says so.+ matches = (+ await db.execute(+ text(+ "SELECT id, title, severity, created_at, "+ " COALESCE(affected_host, '') AS host, COALESCE(affected_user, '') AS actor "+ "FROM alerts WHERE tenant_id = :tenant_id AND raw_event->>'saved_hunt_id' = :hunt "+ "ORDER BY created_at DESC LIMIT 50"+ ).bindparams(tenant_id=tenant_id, hunt=str(saved_hunt_id))+ )+ ).mappings().all()++ translated = hunt["translated_query"] or {}+ query_text = translated.get("query") if isinstance(translated, dict) else None++ report = HuntReport(title=f"Hunt findings: {hunt['name']}", match_count=len(matches))+ report.what = (+ f"The saved hunt {hunt['name']!r} matched {len(matches)} alert(s). "+ f"The analyst asked: {hunt['nl_query']!r}."+ )+ report.how = (+ f"The question was translated into {hunt['language'].upper()} and run against the event "+ f"store. The model never wrote the query text; it chose a template and its parameters, "+ f"which is why the executed query can be shown verbatim"+ + (f":\n\n{query_text}" if query_text else " but was not recorded on this hunt.")+ )+ report.citations.append(+ _cite("saved_hunt", hunt["id"], f"saved hunt {hunt['name']!r} ({hunt['language'].upper()})")+ )++ hosts = sorted({row["host"] for row in matches if row["host"]})+ actors = sorted({row["actor"] for row in matches if row["actor"]})+ if hosts or actors:+ parts = []+ if hosts:+ parts.append(f"{len(hosts)} host(s): {', '.join(hosts[:10])}")+ if actors:+ parts.append(f"{len(actors)} account(s): {', '.join(actors[:10])}")+ report.where = "The matches touch " + "; ".join(parts) + "."+ # No else. An empty `where` renders as "not recorded", which is what it+ # is when every matching alert carried no host and no account.++ times = [row["created_at"] for row in matches if row["created_at"]]+ if times:+ report.when = (+ f"Earliest match {min(times).isoformat()}, latest {max(times).isoformat()}. "+ f"The hunt last ran at {hunt['last_run_at'].isoformat()}."+ )+ else:+ report.when = f"The hunt last ran at {hunt['last_run_at'].isoformat()}."++ for row in matches[:20]:+ report.citations.append(+ _cite("alert", row["id"], f"{row['severity']} · {row['title'][:80]}")+ )+ return report+++# ---------------------------------------------------------------------------+# From a retro-hunt sighting+# ---------------------------------------------------------------------------+++async def build_from_retro_hunt(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ sighting_id: uuid.UUID,+) -> HuntReport:+ """Write a report for an indicator a retro-hunt matched in history.++ A retro-hunt's whole point is the gap between when intelligence arrived+ and when the estate first saw the thing, so that gap is computed and+ stated rather than left for a reader to subtract two timestamps.+ """+ row = (+ await db.execute(+ text(+ "SELECT id, indicator_type, indicator_value, feed_source, intel_first_seen_at, "+ " first_matched_at, last_matched_at, first_sighting_at, last_sighting_at, "+ " sightings, matched_surfaces, alert_id, times_seen "+ "FROM retro_hunt_sightings WHERE id = :id AND tenant_id = :tenant_id"+ ).bindparams(id=sighting_id, tenant_id=tenant_id)+ )+ ).mappings().one_or_none()+ if row is None:+ raise HuntReportError("No such retro-hunt sighting in this tenant.")++ report = HuntReport(+ title=f"Retro-hunt findings: {row['indicator_type']} {row['indicator_value']}",+ match_count=int(row["sightings"] or 0),+ )+ report.what = (+ f"Threat intelligence from {row['feed_source']} named the "+ f"{row['indicator_type']} {row['indicator_value']}, and a retrospective sweep found "+ f"{row['sightings']} prior sighting(s) of it in this estate's history."+ )+ report.how = (+ "The indicator arrived on a feed and was replayed against stored events rather than "+ "only being watched for going forward, which is what surfaces activity that predates "+ "the intelligence."+ )++ surfaces = row["matched_surfaces"] or []+ if surfaces:+ report.where = "Matched on: " + ", ".join(str(s) for s in surfaces[:20]) + "."++ first_seen = row["first_sighting_at"]+ intel_at = row["intel_first_seen_at"]+ when_parts: list[str] = []+ if first_seen and row["last_sighting_at"]:+ when_parts.append(+ f"Seen in this estate from {first_seen.isoformat()} to {row['last_sighting_at'].isoformat()}."+ )+ if intel_at:+ when_parts.append(f"Intelligence first published it at {intel_at.isoformat()}.")+ if first_seen and intel_at:+ gap_days = (intel_at - first_seen).total_seconds() / 86_400.0+ if gap_days > 0:+ # The number a retro-hunt exists to produce, stated rather than+ # left as two timestamps for the reader to subtract.+ when_parts.append(+ f"The estate saw it **{gap_days:.1f} days before** the intelligence named it."+ )+ report.when = " ".join(when_parts)++ report.citations.append(+ _cite("retro_hunt_sighting", row["id"], f"{row['indicator_type']} {row['indicator_value']} via {row['feed_source']}")+ )+ if row["alert_id"]:+ report.citations.append(_cite("alert", row["alert_id"], "the alert this sighting raised"))+ return report+++# ---------------------------------------------------------------------------+# Ledger citations+# ---------------------------------------------------------------------------+++async def attach_ledger_citations(+ db: AsyncSession,+ report: HuntReport,+ *,+ tenant_id: uuid.UUID,+ case_id: uuid.UUID | None,+) -> HuntReport:+ """Add the agent decisions behind this case to the citation list.++ The decision ledger is the artefact that makes the rest of the report+ checkable: it is where the prompt, the response and the tools used are+ recorded. Attached as citations rather than quoted, because a report is+ a summary and the ledger is the long form a reader follows into.++ Silently adds nothing when there is no case or no ledger rows. That is+ not a swallowed failure: a hunt report written before anybody opened a+ case legitimately has no agent decisions behind it, and inventing a+ citation would be the exact defect this function exists to prevent.+ """+ if case_id is None:+ return report+ rows = (+ await db.execute(+ text(+ "SELECT id, kind, created_at FROM investigation_events "+ "WHERE tenant_id = :tenant_id AND case_id = :case_id "+ "ORDER BY created_at ASC LIMIT 20"+ ).bindparams(tenant_id=tenant_id, case_id=case_id)+ )+ ).mappings().all()+ for row in rows:+ report.citations.append(+ _cite("ledger_event", row["id"], f"{row['kind']} at {row['created_at'].isoformat()}")+ )+ return report+++# ---------------------------------------------------------------------------+# Rendering+# ---------------------------------------------------------------------------++_SECTIONS = (("what", "What"), ("how", "How"), ("where", "Where"), ("when", "When"))+++def render_html(row: dict[str, Any], *, product_name: str = "AiSOC") -> str:+ """A self-contained, print-ready page. The same HTML the PDF is made from.++ One renderer, not two. The digest path learned this the hard way: two+ renderers drift and the PDF stops matching the page somebody approved.++ Every interpolation is escaped. A hunt report carries a hunt's own+ natural-language text, host names and indicator values, all of which are+ attacker-influenced in the general case, and this document is opened in+ a browser.+ """+ sections = []+ for key, heading in _SECTIONS:+ body = (row.get(key) or "").strip()+ sections.append(+ f"<section><h2>{escape(heading)}</h2>"+ + (+ f"<p>{escape(body)}</p>"+ if body+ # Not a blank and not a sentence: a reader has to be able to+ # tell "nothing to say" from "nobody filled this in".+ else '<p class="absent">Not recorded. Nothing in the data supported this section.</p>'+ )+ + "</section>"+ )++ citations = row.get("citations") or []+ if citations:+ items = "".join(+ f"<li><span class=\"kind\">{escape(str(c.get('kind', '')))}</span> "+ f"<code>{escape(str(c.get('id', '')))}</code> — {escape(str(c.get('label', '')))}</li>"+ for c in citations+ )+ citation_html = f"<ol>{items}</ol>"+ else:+ citation_html = '<p class="absent">No citations.</p>'++ return f"""<!doctype html>+<html lang="en"><head><meta charset="utf-8">+<title>{escape(str(row.get("title", "Hunt report")))}</title>+<style>+ body {{ font-family: Arial, Helvetica, sans-serif; margin: 2.5rem; color: #111; line-height: 1.5; }}+ h1 {{ font-size: 1.5rem; margin-bottom: 0.25rem; }}+ h2 {{ font-size: 1rem; text-transform: uppercase; letter-spacing: .06em; color: #555; margin: 1.5rem 0 .35rem; }}+ .meta {{ color: #666; font-size: .85rem; }}+ .absent {{ color: #888; font-style: italic; }}+ ol {{ padding-left: 1.2rem; }}+ li {{ margin-bottom: .3rem; font-size: .9rem; }}+ .kind {{ display: inline-block; min-width: 9rem; color: #555; }}+ code {{ background: #f3f3f3; padding: 0 .25rem; }}+</style></head>+<body>+ <h1>{escape(str(row.get("title", "Hunt report")))}</h1>+ <p class="meta">{escape(product_name)} · {escape(str(row.get("source_kind", "")))} ·+ {int(row.get("match_count") or 0)} match(es) ·+ generated {escape(str(row.get("created_at", "")))}</p>+ {"".join(sections)}+ <section><h2>Citations</h2>{citation_html}</section>+</body></html>"""+++def render_pdf(row: dict[str, Any], *, product_name: str = "AiSOC") -> bytes:+ """The same HTML, through WeasyPrint. Raises the shared unavailability error.++ Reuses ``digest_pdf``'s error type rather than defining a second one, so+ the route's 503 branch and its message are the ones operators already+ know from the weekly digest.+ """+ from app.services.digest_pdf import WeasyPrintUnavailableError # noqa: PLC0415 - avoids a cycle at import++ try:+ from weasyprint import HTML # type: ignore[import-untyped] # noqa: PLC0415+ except (ImportError, OSError) as exc:+ raise WeasyPrintUnavailableError(+ "WeasyPrint is not available in this environment, so a PDF cannot be rendered. "+ "The same report is available as HTML and JSON. See services/api/Dockerfile for "+ "the required system packages."+ ) from exc+ pdf: bytes = HTML(string=render_html(row, product_name=product_name)).write_pdf()+ return pdf+++async def persist(+ db: AsyncSession,+ report: HuntReport,+ *,+ tenant_id: uuid.UUID,+ source_kind: str,+ source_id: uuid.UUID,+ case_id: uuid.UUID | None,+ generated_by: str,+) -> dict[str, Any]:+ """Store the report. Refuses an uncited one."""+ if source_kind not in SOURCE_KINDS:+ raise HuntReportError(f"source_kind must be one of {list(SOURCE_KINDS)}")+ if not report.is_citable():+ raise HuntReportError(+ "Refusing to store a report with no citations. An uncited report is an assertion, "+ "and the point of this surface is that an assertion is not evidence."+ )+ row = (+ await db.execute(+ text(+ "INSERT INTO aisoc_hunt_reports "+ '(tenant_id, source_kind, source_id, case_id, title, what, how, "where", "when", '+ " citations, match_count, generated_by) "+ "VALUES (:tenant_id, :source_kind, :source_id, :case_id, :title, :what, :how, "+ " :where_, :when_, CAST(:citations AS jsonb), :match_count, :generated_by) "+ "RETURNING *"+ ).bindparams(+ tenant_id=tenant_id,+ source_kind=source_kind,+ source_id=source_id,+ case_id=case_id,+ title=report.title,+ what=report.what,+ how=report.how,+ where_=report.where,+ when_=report.when,+ citations=json.dumps(report.citations),+ match_count=report.match_count,+ generated_by=generated_by,+ )+ )+ ).mappings().one()+ out = dict(row)+ out["created_at"] = out["created_at"].astimezone(UTC).isoformat() if isinstance(out.get("created_at"), datetime) else out.get("created_at")+ return outdiff --git a/services/api/migrations/108_hunt_reports.sql b/services/api/migrations/108_hunt_reports.sqlnew file mode 100644index 000000000..641271976--- /dev/null+++ b/services/api/migrations/108_hunt_reports.sql@@ -0,0 +1,105 @@+-- 108_hunt_reports.sql — a hunt that found something becomes a case report+-- somebody can hand to a reader.+--+-- Depth plan 9.5. A natural-language hunt produced rows and a retro-hunt+-- produced a `retro_hunt_sightings` row, and neither produced anything a+-- person could read, forward or file. `grep -n hunt` across+-- `services/api/app/services/report_builder.py` and+-- `app/api/v1/endpoints/reports.py` returned nothing at all: the report+-- surface and the hunt surface did not know about each other.+--+-- Why the four sections are columns and not a blob+-- ------------------------------------------------+-- What, how, where and when are the questions the plan names, and they are+-- the questions a reader asks in that order. Storing them separately means+-- the HTML and PDF renderers share one structure, a reader of the row can+-- tell an empty section from an absent one, and a section that could not be+-- derived stays empty rather than being filled with a confident sentence+-- about nothing.+--+-- Why citations are their own column and are required to be a list+-- ----------------------------------------------------------------+-- "With ledger citations" is the load-bearing half of the item. A report+-- with no citation is an assertion, and this product's whole position is+-- that an assertion is not evidence. Each entry names a kind, an id and a+-- human label, so a renderer can link it and an auditor can resolve it+-- after the fact.+--+-- Why `case_id` is nullable+-- -------------------------+-- A hunt can find something before anybody has decided it is a case. The+-- report is written first and attached when the case exists, which is the+-- order the work actually happens in; forcing the case first would mean+-- opening one to find out whether you need it.+--+-- Reversible: DROP TABLE IF EXISTS aisoc_hunt_reports.++CREATE TABLE IF NOT EXISTS aisoc_hunt_reports (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,++ -- Which surface produced it. Closed, because each value has exactly one+ -- builder and an unknown kind is a report nobody can regenerate.+ source_kind TEXT NOT NULL CHECK (source_kind IN ('hunt', 'retro_hunt')),+ -- The saved hunt or the sighting. Not an FK: the two live in different+ -- tables and a report should outlive the hunt definition it came from,+ -- the same reason a closed case outlives the rule that opened it.+ source_id UUID NOT NULL,++ case_id UUID REFERENCES aisoc_cases(id) ON DELETE SET NULL,++ title TEXT NOT NULL,++ -- The four questions, in the order a reader asks them.+ what TEXT NOT NULL DEFAULT '',+ how TEXT NOT NULL DEFAULT '',+ "where" TEXT NOT NULL DEFAULT '',+ "when" TEXT NOT NULL DEFAULT '',++ -- `[{kind, id, label}]`. A report with none is an assertion, which is+ -- the thing this product exists to be the opposite of.+ citations JSONB NOT NULL DEFAULT '[]'::jsonb,++ -- How many rows the hunt matched. Stored because the report is a+ -- snapshot: re-running the hunt tomorrow gives a different number and+ -- the report has to keep saying what it said when it was written.+ match_count INTEGER NOT NULL DEFAULT 0,++ generated_by TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT aisoc_hunt_reports_citations_is_array CHECK (jsonb_typeof(citations) = 'array')+);++CREATE INDEX IF NOT EXISTS aisoc_hunt_reports_tenant_idx+ ON aisoc_hunt_reports (tenant_id, created_at DESC);++CREATE INDEX IF NOT EXISTS aisoc_hunt_reports_case_idx+ ON aisoc_hunt_reports (case_id)+ WHERE case_id IS NOT NULL;++CREATE INDEX IF NOT EXISTS aisoc_hunt_reports_source_idx+ ON aisoc_hunt_reports (tenant_id, source_kind, source_id);++COMMENT ON TABLE aisoc_hunt_reports IS+ 'What a hunt found, written so a person can read it: what, how, where, when, and the '+ 'ledger citations behind each. A snapshot -- re-running the hunt tomorrow gives a '+ 'different answer and the report has to keep saying what it said when it was written.';++-- Written out rather than looped with format(): a loop makes the policy+-- invisible to grep and to scripts/check_tenant_query_predicates.py.+DO $$+BEGIN+ EXECUTE 'ALTER TABLE aisoc_hunt_reports ENABLE ROW LEVEL SECURITY';+ EXECUTE 'ALTER TABLE aisoc_hunt_reports FORCE ROW LEVEL SECURITY';+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON aisoc_hunt_reports';+ EXECUTE+ 'CREATE POLICY tenant_isolation ON aisoc_hunt_reports '+ 'USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '+ 'WITH CHECK (tenant_id = current_tenant_id())';++ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_hunt_reports TO aisoc_app';+ END IF;+END+$$;