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
fix(api,web): case timeline/tasks/investigate routes + fusion gateway fallback
Beenu Arora6ee01ad525a5
diff --git a/apps/web/next.config.js b/apps/web/next.config.jsindex 41dc8dad2..1e04397af 100644--- a/apps/web/next.config.js+++ b/apps/web/next.config.js@@ -16,7 +16,12 @@ const AGENTS_HOST = process.env.AGENTS_URL || 'http://localhost:8001';// Fusion service exposes /entity-risk/*, /ml/*, /metrics, /health at root.// We surface those to the browser under the same-origin namespace// /api/v1/fusion/* so the bundle stays host-agnostic.-const FUSION_HOST = process.env.FUSION_URL || 'http://localhost:8082';+//+// When FUSION_URL is unset (e.g. the demo Fly.io stack with no fusion+// deployment), the rewrite is omitted entirely so /api/v1/fusion/* falls+// through to the core API catch-all, which exposes a graceful fusion+// gateway (services/api/app/api/v1/endpoints/fusion.py).+const FUSION_HOST = process.env.FUSION_URL || '';const ENRICHMENT_HOST = process.env.ENRICHMENT_URL || 'http://localhost:8083';const nextConfig = {@@ -142,10 +147,19 @@ const nextConfig = {// and ML scoring endpoints at its own root (no /api/v1 prefix on the// service side). Proxy /api/v1/fusion/:path* → fusion's /:path* so the// browser only ever sees same-origin URLs.- {- source: '/api/v1/fusion/:path*',- destination: `${FUSION_HOST}/:path*`,- },+ //+ // Only emit the fusion-specific rewrite when FUSION_URL is configured.+ // Without it, /api/v1/fusion/* falls through to the core API, which+ // now hosts a fusion gateway that returns graceful empty payloads+ // when no upstream fusion is reachable.+ ...(FUSION_HOST+ ? [+ {+ source: '/api/v1/fusion/:path*',+ destination: `${FUSION_HOST}/:path*`,+ },+ ]+ : []),// Catch-all for the core API.{source: '/api/v1/:path*',diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.pyindex 531fa5ea5..5c0f9df2c 100644--- a/services/api/app/api/v1/endpoints/cases.py+++ b/services/api/app/api/v1/endpoints/cases.py@@ -19,18 +19,33 @@ Endpointsfrom __future__ import annotations+import logging+import osimport uuidfrom datetime import UTC, datetimefrom typing import Any, Literal-from fastapi import APIRouter, HTTPException, Query, status+import httpx+from fastapi import APIRouter, HTTPException, Query, Response, statusfrom pydantic import BaseModel, Fieldfrom sqlalchemy import textfrom app.api.v1.deps import AuthUser, DBSession+logger = logging.getLogger(__name__)+router = APIRouter(prefix="/cases", tags=["cases"])+# The agents service owns the actual investigation orchestrator (Pillar-1).+# We keep the route surface on `/cases/{id}/investigate` and+# `/cases/{id}/investigations/{run_id}` for the web console and proxy through+# to the agents service so the front end has a single, stable API origin.+_AGENTS_URL = (+ os.getenv("AGENTS_SERVICE_URL")+ or os.getenv("AGENTS_API_URL")+ or "http://agents:8084"+).rstrip("/")+# ────────────────────────────────────────────────────────────────────────────# Pydantic schemas# ────────────────────────────────────────────────────────────────────────────@@ -144,6 +159,68 @@ class EvidenceReport(BaseModel):generated_at: datetime+# Timeline / tasks+TaskStatus = Literal["todo", "in_progress", "done"]+++class TimelineEvent(BaseModel):+ id: str+ type: str # 'created' | 'status_change' | 'comment' | 'alert_linked' | 'task'+ timestamp: datetime+ title: str+ description: str | None = None+ actor: str | None = None+++class TimelineResponse(BaseModel):+ events: list[TimelineEvent]+++class CreateTaskRequest(BaseModel):+ title: str = Field(..., min_length=1)+ status: TaskStatus = "todo"+ assignee: str | None = None+ due_at: datetime | None = Field(None, alias="dueAt")++ model_config = {"populate_by_name": True}+++class UpdateTaskRequest(BaseModel):+ title: str | None = None+ status: TaskStatus | None = None+ assignee: str | None = None+ due_at: datetime | None = Field(None, alias="dueAt")++ model_config = {"populate_by_name": True}+++class TaskResponse(BaseModel):+ id: str+ title: str+ status: TaskStatus+ assignee: str | None = None+ due_at: datetime | None = Field(None, alias="dueAt")+ created_at: datetime = Field(..., alias="createdAt")++ model_config = {"populate_by_name": True}+++def _row_to_task(row: Any) -> TaskResponse:+ return TaskResponse(+ id=str(row.id),+ title=row.title,+ status=row.status,+ assignee=row.assignee,+ dueAt=row.due_at,+ createdAt=row.created_at,+ )+++# Investigation proxy schemas (forwarded to the agents service).+class InvestigateRequest(BaseModel):+ alert_summary: str | None = ""++# ────────────────────────────────────────────────────────────────────────────# Helpers# ────────────────────────────────────────────────────────────────────────────@@ -448,3 +525,322 @@ async def evidence_report(case_id: uuid.UUID, db: DBSession, user: AuthUser) ->evidence_chain=list(row.evidence_chain or []),generated_at=datetime.now(UTC),)+++# ─────────────────────────────────────────────────────────────────────────────+# Timeline+#+# A flattened activity stream that the case workspace renders on the right.+# We synthesize the timeline from the case's own state transitions, linked+# alerts, comments, and tasks so the front end gets one unified view without+# orchestrating four separate calls.+# ─────────────────────────────────────────────────────────────────────────────++[email protected]("/{case_id}/timeline", response_model=TimelineResponse, summary="Case activity timeline")+async def case_timeline(case_id: uuid.UUID, db: DBSession, user: AuthUser) -> TimelineResponse:+ case_row = (+ await db.execute(text("SELECT * FROM aisoc_cases WHERE id = :id").bindparams(id=case_id))+ ).fetchone()+ if not case_row:+ raise HTTPException(status_code=404, detail="Case not found.")++ events: list[TimelineEvent] = []++ # Case creation event+ events.append(+ TimelineEvent(+ id=f"case-{case_row.id}-created",+ type="created",+ timestamp=case_row.created_at,+ title="Case opened",+ description=case_row.title,+ actor=case_row.assignee,+ )+ )++ # Status / severity reflection (we only surface the latest snapshot here;+ # full audit history is available via the audit log endpoints).+ if case_row.updated_at and case_row.updated_at != case_row.created_at:+ events.append(+ TimelineEvent(+ id=f"case-{case_row.id}-status",+ type="status_change",+ timestamp=case_row.updated_at,+ title=f"Status: {case_row.status}",+ description=f"Severity {case_row.severity}",+ actor=case_row.assignee,+ )+ )++ # Comments+ comment_rows = (+ await db.execute(+ text(+ "SELECT id, author, body, is_system, created_at "+ "FROM aisoc_case_comments WHERE case_id = :id ORDER BY created_at"+ ).bindparams(id=case_id)+ )+ ).fetchall()+ for c in comment_rows:+ events.append(+ TimelineEvent(+ id=f"comment-{c.id}",+ type="comment",+ timestamp=c.created_at,+ title="System note" if c.is_system else "Comment",+ description=(c.body or "")[:280],+ actor=c.author,+ )+ )++ # Linked alerts (best-effort — we tolerate a missing alerts table)+ for alert_id in list(case_row.alert_ids or [])[:25]:+ try:+ a = (+ await db.execute(+ text(+ "SELECT id, title, severity, created_at FROM aisoc_alerts WHERE id = :id"+ ).bindparams(id=alert_id)+ )+ ).fetchone()+ if a:+ events.append(+ TimelineEvent(+ id=f"alert-{a.id}",+ type="alert_linked",+ timestamp=a.created_at or case_row.created_at,+ title=f"Alert linked: {a.title}",+ description=f"Severity {a.severity}",+ actor=None,+ )+ )+ except Exception: # noqa: BLE001 — alerts table may not exist in some demos+ continue++ # Tasks+ try:+ task_rows = (+ await db.execute(+ text(+ "SELECT id, title, status, assignee, created_at "+ "FROM aisoc_case_tasks WHERE case_id = :id ORDER BY created_at"+ ).bindparams(id=case_id)+ )+ ).fetchall()+ for t in task_rows:+ events.append(+ TimelineEvent(+ id=f"task-{t.id}",+ type="task",+ timestamp=t.created_at,+ title=f"Task ({t.status}): {t.title}",+ description=None,+ actor=t.assignee,+ )+ )+ except Exception: # noqa: BLE001 — table created by migration 027; tolerate absence+ logger.exception("aisoc_case_tasks not available; skipping task events")++ events.sort(key=lambda e: e.timestamp)+ return TimelineResponse(events=events)+++# ─────────────────────────────────────────────────────────────────────────────+# Tasks+# ─────────────────────────────────────────────────────────────────────────────++[email protected]("/{case_id}/tasks", response_model=list[TaskResponse], summary="List case tasks")+async def list_tasks(case_id: uuid.UUID, db: DBSession, user: AuthUser) -> list[TaskResponse]:+ exists = (+ await db.execute(text("SELECT 1 FROM aisoc_cases WHERE id = :id").bindparams(id=case_id))+ ).fetchone()+ if not exists:+ raise HTTPException(status_code=404, detail="Case not found.")+ rows = (+ await db.execute(+ text(+ "SELECT id, title, status, assignee, due_at, created_at "+ "FROM aisoc_case_tasks WHERE case_id = :id ORDER BY created_at"+ ).bindparams(id=case_id)+ )+ ).fetchall()+ return [_row_to_task(r) for r in rows]++[email protected]("/{case_id}/tasks", response_model=TaskResponse, status_code=201, summary="Create task")+async def create_task(+ case_id: uuid.UUID,+ body: CreateTaskRequest,+ db: DBSession,+ user: AuthUser,+) -> TaskResponse:+ exists = (+ await db.execute(text("SELECT 1 FROM aisoc_cases WHERE id = :id").bindparams(id=case_id))+ ).fetchone()+ if not exists:+ raise HTTPException(status_code=404, detail="Case not found.")++ task_id = uuid.uuid4()+ now = datetime.now(UTC)+ try:+ row = (+ await db.execute(+ text(+ """+ INSERT INTO aisoc_case_tasks+ (id, case_id, title, status, assignee, due_at, created_at, updated_at, created_by)+ VALUES+ (:id, :case_id, :title, :status, :assignee, :due_at, :now, :now, :created_by)+ RETURNING id, title, status, assignee, due_at, created_at+ """+ ).bindparams(+ id=task_id,+ case_id=case_id,+ title=body.title,+ status=body.status,+ assignee=body.assignee,+ due_at=body.due_at,+ now=now,+ created_by=str(user) if user else None,+ )+ )+ ).fetchone()+ await db.commit()+ return _row_to_task(row)+ except Exception as exc:+ await db.rollback()+ raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc++[email protected]("/{case_id}/tasks/{task_id}", response_model=TaskResponse, summary="Update task")+async def update_task(+ case_id: uuid.UUID,+ task_id: uuid.UUID,+ body: UpdateTaskRequest,+ db: DBSession,+ user: AuthUser,+) -> TaskResponse:+ sets: list[str] = []+ params: dict[str, Any] = {"id": task_id, "case_id": case_id, "now": datetime.now(UTC)}+ if body.title is not None:+ sets.append("title = :title")+ params["title"] = body.title+ if body.status is not None:+ sets.append("status = :status")+ params["status"] = body.status+ if body.assignee is not None:+ sets.append("assignee = :assignee")+ params["assignee"] = body.assignee+ if body.due_at is not None:+ sets.append("due_at = :due_at")+ params["due_at"] = body.due_at+ if not sets:+ raise HTTPException(status_code=400, detail="No fields to update.")+ sets.append("updated_at = :now")++ try:+ row = (+ await db.execute(+ text(+ f"""+ UPDATE aisoc_case_tasks+ SET {", ".join(sets)}+ WHERE id = :id AND case_id = :case_id+ RETURNING id, title, status, assignee, due_at, created_at+ """+ ).bindparams(**params)+ )+ ).fetchone()+ if not row:+ raise HTTPException(status_code=404, detail="Task not found.")+ await db.commit()+ return _row_to_task(row)+ except HTTPException:+ raise+ except Exception as exc:+ await db.rollback()+ raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc+++# ─────────────────────────────────────────────────────────────────────────────+# Investigation proxy+#+# The investigation orchestrator lives in the agents service. The web console+# only knows about /api/v1/cases/{id}/..., so we proxy through and keep the+# external API surface stable.+# ─────────────────────────────────────────────────────────────────────────────+++async def _agents_proxy(method: str, path: str, **kwargs: Any) -> httpx.Response:+ url = f"{_AGENTS_URL}{path}"+ timeout = kwargs.pop("timeout", 30.0)+ try:+ async with httpx.AsyncClient(timeout=timeout) as client:+ return await client.request(method, url, **kwargs)+ except httpx.HTTPError as exc:+ logger.exception("Agents service request failed: %s %s", method, url)+ raise HTTPException(+ status_code=503,+ detail=f"Agents service unavailable: {exc}",+ ) from exc++[email protected]("/{case_id}/investigate", summary="Launch investigation for case")+async def case_investigate(+ case_id: uuid.UUID,+ body: InvestigateRequest,+ db: DBSession,+ user: AuthUser,+) -> dict[str, Any]:+ exists = (+ await db.execute(text("SELECT 1 FROM aisoc_cases WHERE id = :id").bindparams(id=case_id))+ ).fetchone()+ if not exists:+ raise HTTPException(status_code=404, detail="Case not found.")++ resp = await _agents_proxy(+ "POST",+ f"/api/v1/cases/{case_id}/investigate",+ json={"alert_summary": body.alert_summary or ""},+ )+ if resp.status_code >= 400:+ raise HTTPException(status_code=resp.status_code, detail=resp.text)+ return resp.json()++[email protected]("/{case_id}/investigations/{run_id}", summary="Get investigation run")+async def case_investigation_run(+ case_id: uuid.UUID,+ run_id: str,+ user: AuthUser,+) -> dict[str, Any]:+ resp = await _agents_proxy("GET", f"/api/v1/investigations/{run_id}")+ if resp.status_code >= 400:+ raise HTTPException(status_code=resp.status_code, detail=resp.text)+ return resp.json()+++ "/{case_id}/investigations/{run_id}/report.pdf",+ summary="Download investigation PDF report",+)+async def case_investigation_pdf(+ case_id: uuid.UUID,+ run_id: str,+ user: AuthUser,+) -> Response:+ resp = await _agents_proxy("GET", f"/api/v1/investigations/{run_id}/report.pdf")+ if resp.status_code >= 400:+ raise HTTPException(status_code=resp.status_code, detail=resp.text)+ return Response(+ content=resp.content,+ media_type=resp.headers.get("content-type", "application/pdf"),+ headers={+ "Content-Disposition": resp.headers.get(+ "content-disposition",+ f'attachment; filename="case-{case_id}-{run_id}.pdf"',+ ),+ },+ )diff --git a/services/api/app/api/v1/endpoints/fusion.py b/services/api/app/api/v1/endpoints/fusion.pynew file mode 100644index 000000000..1a3fe7a00--- /dev/null+++ b/services/api/app/api/v1/endpoints/fusion.py@@ -0,0 +1,183 @@+"""+Fusion gateway / fallback for /api/v1/fusion/*.++The fusion microservice (services/fusion) owns Risk-Based Alerting (RBA) —+entity rollups, decayed risk scoring, and ML-assisted ranking. In a full+deployment the web tier proxies /api/v1/fusion/* directly to that service+(see apps/web/next.config.js → FUSION_HOST). When the fusion service is+not deployed (e.g. the demo Fly.io stack), the web rewrite still hits the+core API service via the catch-all, so we expose a thin gateway here that:++ 1. Forwards to the upstream fusion service if FUSION_URL is set in the+ api environment, preserving full functionality.+ 2. Otherwise returns graceful empty payloads so the console renders an+ empty queue instead of a 500.++Endpoint surface mirrors services/fusion/app/api/router.py:+ GET /api/v1/fusion/health+ GET /api/v1/fusion/metrics+ GET /api/v1/fusion/entity-risk/queue+ GET /api/v1/fusion/entity-risk/stats+ GET /api/v1/fusion/entity-risk/{entity_type}/{entity_value}+ GET /api/v1/fusion/ml/status+"""++from __future__ import annotations++import logging+import os+from typing import Any+from uuid import UUID++import httpx+from fastapi import APIRouter, HTTPException, Query++logger = logging.getLogger(__name__)++router = APIRouter(prefix="/fusion", tags=["fusion"])++# When set, requests are forwarded to the live fusion service. When unset,+# the gateway returns deterministic, empty fallbacks so the UI degrades+# gracefully instead of bubbling 5xx into the analyst console.+_FUSION_URL = (+ os.getenv("FUSION_SERVICE_URL")+ or os.getenv("FUSION_URL")+ or ""+).rstrip("/")+++async def _proxy_get(path: str, params: dict[str, Any] | None = None) -> dict[str, Any] | None:+ """Forward GET to fusion if configured. Return None on transport error."""+ if not _FUSION_URL:+ return None+ try:+ async with httpx.AsyncClient(timeout=15.0) as client:+ resp = await client.get(f"{_FUSION_URL}{path}", params=params or {})+ if resp.status_code >= 500:+ logger.warning(+ "Fusion upstream returned %s for %s; falling back to stub",+ resp.status_code,+ path,+ )+ return None+ if resp.status_code == 404:+ # Let caller surface 404 cleanly.+ raise HTTPException(status_code=404, detail="not_found")+ if resp.status_code >= 400:+ raise HTTPException(status_code=resp.status_code, detail=resp.text)+ return resp.json()+ except HTTPException:+ raise+ except httpx.HTTPError as exc:+ logger.warning("Fusion service unreachable (%s); using stub fallback", exc)+ return None+++# ─── Health / metrics ──────────────────────────────────────────────────────++[email protected]("/health", summary="Fusion service health")+async def fusion_health() -> dict[str, Any]:+ upstream = await _proxy_get("/health")+ if upstream is not None:+ return upstream+ return {+ "status": "stub",+ "service": "aisoc-fusion-gateway",+ "upstream_configured": bool(_FUSION_URL),+ }++[email protected]("/metrics", summary="Fusion worker metrics")+async def fusion_metrics() -> dict[str, Any]:+ upstream = await _proxy_get("/metrics")+ if upstream is not None:+ return upstream+ return {"status": "stub", "metrics": {}}+++# ─── ML status ─────────────────────────────────────────────────────────────++[email protected]("/ml/status", summary="Fusion ML model status")+async def ml_status() -> dict[str, Any]:+ upstream = await _proxy_get("/ml/status")+ if upstream is not None:+ return upstream+ return {+ "status": "stub",+ "model_version": None,+ "trained_at": None,+ "training_samples": 0,+ "feedback_count": 0,+ }+++# ─── Entity risk (RBA) ─────────────────────────────────────────────────────++# The threshold here mirrors services/fusion/app/services/entity_risk.py+# default; the UI displays it as "promotion threshold".+_DEFAULT_THRESHOLD = 100.0++[email protected]("/entity-risk/queue", summary="Top entities by risk score")+async def entity_risk_queue(+ tenant_id: UUID,+ limit: int = Query(default=25, ge=1, le=200),+ promoted_only: bool = False,+) -> dict[str, Any]:+ upstream = await _proxy_get(+ "/entity-risk/queue",+ params={+ "tenant_id": str(tenant_id),+ "limit": limit,+ "promoted_only": str(promoted_only).lower(),+ },+ )+ if upstream is not None:+ return upstream+ return {+ "tenant_id": str(tenant_id),+ "threshold": _DEFAULT_THRESHOLD,+ "entities": [],+ }++[email protected]("/entity-risk/stats", summary="Entity-risk queue stats")+async def entity_risk_stats(tenant_id: UUID) -> dict[str, Any]:+ upstream = await _proxy_get(+ "/entity-risk/stats",+ params={"tenant_id": str(tenant_id)},+ )+ if upstream is not None:+ return upstream+ return {+ "tenant_id": str(tenant_id),+ "threshold": _DEFAULT_THRESHOLD,+ "total": 0,+ "promoted": 0,+ "bands": {"critical": 0, "high": 0, "medium": 0, "low": 0},+ "alerts_total": 0,+ }+++ "/entity-risk/{entity_type}/{entity_value}",+ summary="Entity risk record detail",+)+async def entity_risk_detail(+ entity_type: str,+ entity_value: str,+ tenant_id: UUID,+) -> dict[str, Any]:+ if entity_type == "ip":+ entity_type = "src_ip"+ upstream = await _proxy_get(+ f"/entity-risk/{entity_type}/{entity_value}",+ params={"tenant_id": str(tenant_id)},+ )+ if upstream is not None:+ return upstream+ # No fallback record exists when fusion is offline; surface 404 so the+ # drawer renders its empty state.+ raise HTTPException(status_code=404, detail="entity_not_found")diff --git a/services/api/app/api/v1/endpoints/playbooks.py b/services/api/app/api/v1/endpoints/playbooks.pyindex 9f825ee41..d9400206f 100644--- a/services/api/app/api/v1/endpoints/playbooks.py+++ b/services/api/app/api/v1/endpoints/playbooks.py@@ -15,7 +15,9 @@ from typing import Anyimport httpxfrom fastapi import APIRouter, HTTPException, Request, status-_AGENTS_URL = os.getenv("AGENTS_SERVICE_URL", "http://agents:8084")+_AGENTS_URL = os.getenv("AGENTS_SERVICE_URL") or os.getenv(+ "AGENTS_API_URL", "http://agents:8084"+)router = APIRouter(prefix="/playbooks", tags=["playbooks"])diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex 2be98b793..ada1200e1 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -22,6 +22,7 @@ from app.api.v1.endpoints import (easm,feedback,federated,+ fusion,hunts,identity_timeline,knowledge_base,@@ -135,3 +136,7 @@ api_router.include_router(shifts.router)# Deployment configuration and air-gap bundle managementapi_router.include_router(deployment.router)++# Fusion gateway: proxies to services/fusion when FUSION_URL is set, otherwise+# returns graceful empty payloads so the analyst console renders cleanly.+api_router.include_router(fusion.router)diff --git a/services/api/app/graphql/query.py b/services/api/app/graphql/query.pyindex 63b0ddf50..61e87b93e 100644--- a/services/api/app/graphql/query.py+++ b/services/api/app/graphql/query.py@@ -41,7 +41,9 @@ from app.models.case import Casefrom app.models.connector import Connectorfrom app.models.detection_rule import DetectionRule-_AGENTS_URL = os.getenv("AGENTS_SERVICE_URL", "http://agents:8084")+_AGENTS_URL = os.getenv("AGENTS_SERVICE_URL") or os.getenv(+ "AGENTS_API_URL", "http://agents:8084"+)# ─── helpers ──────────────────────────────────────────────────────────────────diff --git a/services/api/migrations/027_case_tasks.sql b/services/api/migrations/027_case_tasks.sqlnew file mode 100644index 000000000..f46aaac25--- /dev/null+++ b/services/api/migrations/027_case_tasks.sql@@ -0,0 +1,22 @@+-- Migration 027: Per-case investigation/response tasks+--+-- The web console renders a "Tasks" panel in the case workspace where SOC+-- analysts can capture follow-up work (run forensic image, contact owner,+-- block IP at the edge, …) tied to a specific case. Tasks are simple — a+-- title, an optional assignee/due date, and a three-state status.++CREATE TABLE IF NOT EXISTS aisoc_case_tasks (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ case_id UUID NOT NULL REFERENCES aisoc_cases(id) ON DELETE CASCADE,+ title TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'todo'+ CHECK (status IN ('todo','in_progress','done')),+ assignee TEXT,+ due_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ created_by TEXT+);++CREATE INDEX IF NOT EXISTS idx_aisoc_case_tasks_case ON aisoc_case_tasks (case_id);+CREATE INDEX IF NOT EXISTS idx_aisoc_case_tasks_status ON aisoc_case_tasks (status);