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(cases): depth 9.3 — merge, bulk triage, custom fields and analyst workload (#1314)
Beenu Arora869ae8d09fa0
diff --git a/.github/workflows/case-depth-live.yml b/.github/workflows/case-depth-live.ymlnew file mode 100644index 000000000..182e251cc--- /dev/null+++ b/.github/workflows/case-depth-live.yml@@ -0,0 +1,172 @@+# Case depth — through the real app and real Postgres (depth 9.3, parity 5.6).+#+# Why this needs a live database rather than the usual SQLite stand-in+# --------------------------------------------------------------------+# Every statement under test is Postgres-only by necessity: `uuid[]`+# parameters, `array_agg(DISTINCT …)` over a `uuid[]` column, `unnest`,+# `count(*) FILTER (WHERE …)` and `EXTRACT(EPOCH FROM …)`. A SQLite+# stand-in would be a *different query* than the one that ships, which is the+# "test double more capable than the real thing" failure this repository+# keeps finding — and it found it again here: the first version of the case+# merge assumed `aisoc_cases.alert_ids` was JSONB like the two columns beside+# it. It is `uuid[]`, and the statement raised+# `jsonb_array_elements_text(uuid[]) does not exist` on the first live run.+#+# The suites skip when no database answers, which is why this job sets+# CASE_DEPTH_PROOF_REQUIRED=1: here, a skip is a failure.+#+# No `paths:` filter, for the reason alert-audit-live.yml states: a guard that+# only grades pull requests touching a named path is one the next refactor+# walks around.+name: Case depth (live)++on:+ push:+ branches: [main]+ pull_request:+ workflow_dispatch:++concurrency:+ group: case-depth-live-${{ github.ref }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.sha }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ case-depth-live:+ name: A merge keeps history, a bulk triage has a preflight, a mean has a denominator+ runs-on: ubuntu-latest+ timeout-minutes: 20++ services:+ postgres:+ image: public.ecr.aws/docker/library/postgres:16-alpine+ env:+ POSTGRES_USER: aisoc+ POSTGRES_PASSWORD: aisoc_ci_only+ POSTGRES_DB: aisoc+ ports: ["5432:5432"]+ options: >-+ --health-cmd "pg_isready -U aisoc"+ --health-interval 5s+ --health-timeout 5s+ --health-retries 20++ env:+ # aisoc-db-role: owner — the suite creates scratch tenants and users, which the DML-only runtime role cannot+ DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_ci_only@localhost:5432/aisoc+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:aisoc_ci_only@localhost:5432/aisoc+ PGPASSWORD: aisoc_ci_only+ # Not a bypass environment: the suite mints real JWTs and travels+ # through the real auth dependencies. A dev-mode principal would make+ # "the actor is the authenticated analyst" pass for the wrong reason.+ ENVIRONMENT: production+ SECRET_KEY: ci-case-depth-signing-secret-at-least-32-chars+ CASE_DEPTH_PROOF_REQUIRED: "1"+ OTEL_SDK_DISABLED: "true"++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6+ with:+ python-version: "3.11"++ - name: Install api from its lockfile+ working-directory: services/api+ run: |+ set -euo pipefail+ python -m pip install --quiet --upgrade pip "poetry==2.4.1"+ poetry config virtualenvs.create false+ poetry install --no-root --no-interaction+ python -m pip install --quiet pytest pytest-asyncio++ - name: Apply every migration, in order+ run: |+ for f in services/api/migrations/*.sql; do+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"+ done++ - name: Merge, bulk triage, custom fields and workload+ working-directory: services/api+ run: python -m pytest tests/test_case_depth.py -v --tb=short++ # ── Negative controls ──────────────────────────────────────────────+ #+ # Each one puts a defect back and requires the matching assertion to go+ # red. Without them a suite that stopped exercising the path — a fixture+ # that seeds nothing, a skip that reads as a pass — stays green forever.++ - name: Removing the bulk-triage preflight makes the suite fail+ working-directory: services/api+ run: |+ cp app/services/case_depth.py /tmp/case_depth.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/services/case_depth.py")+ s = p.read_text()+ needle = " if matched > max_count:"+ if needle not in s:+ print("negative control: no preflight comparison to remove — the service has "+ "been reshaped and this control no longer proves anything")+ sys.exit(1)+ p.write_text(s.replace(needle, " if False: # NEGATIVE CONTROL", 1))+ PY+ if python -m pytest tests/test_case_depth.py -q >/dev/null 2>&1; then+ cp /tmp/case_depth.bak app/services/case_depth.py+ echo "FAIL: the suite passed with a bulk triage that writes past its stated max_count."+ exit 1+ fi+ cp /tmp/case_depth.bak app/services/case_depth.py+ echo "OK: removing the preflight makes the suite fail, as it must."++ - name: Counting merged-away cases as work makes the workload proof fail+ working-directory: services/api+ run: |+ cp app/services/case_depth.py /tmp/case_depth.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/services/case_depth.py")+ s = p.read_text()+ needle = " AND merged_into_id IS NULL\n)"+ if needle not in s:+ print("negative control: the workload query no longer excludes merged cases "+ "in the shape this control edits")+ sys.exit(1)+ p.write_text(s.replace(needle, " -- NEGATIVE CONTROL\n)", 1))+ PY+ if python -m pytest tests/test_case_depth.py -q >/dev/null 2>&1; then+ cp /tmp/case_depth.bak app/services/case_depth.py+ echo "FAIL: the suite passed while a merge counted as throughput."+ exit 1+ fi+ cp /tmp/case_depth.bak app/services/case_depth.py+ echo "OK: counting merged cases makes the suite fail, as it must."++ - name: Deleting the absorbed case instead of keeping it makes the merge proof fail+ working-directory: services/api+ run: |+ cp app/services/case_depth.py /tmp/case_depth.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/services/case_depth.py")+ s = p.read_text()+ needle = " text(\n \"UPDATE aisoc_cases SET merged_into_id = :primary,"+ if needle not in s:+ print("negative control: the statement that marks the absorbed case was not found")+ sys.exit(1)+ s = s.replace(+ needle,+ " text(\n \"DELETE FROM aisoc_cases \" # NEGATIVE CONTROL\n \"-- UPDATE aisoc_cases SET merged_into_id = :primary,",+ 1,+ )+ p.write_text(s)+ PY+ if python -m pytest tests/test_case_depth.py -q >/dev/null 2>&1; then+ cp /tmp/case_depth.bak app/services/case_depth.py+ echo "FAIL: the suite passed with a merge that deletes the absorbed case."+ exit 1+ fi+ cp /tmp/case_depth.bak app/services/case_depth.py+ echo "OK: deleting the absorbed case makes the suite fail, as it must."diff --git a/DEPTH_PROGRESS.md b/DEPTH_PROGRESS.mdindex 52b94ffa9..f89214461 100644--- a/DEPTH_PROGRESS.md+++ b/DEPTH_PROGRESS.md@@ -486,7 +486,34 @@ invented fields on the first run of the gate.against real Postgres 16, real Qdrant v1.7.0 and a real embedding backend,recorded in the PR. **The measurement is published as it came out, and it isunflattering:** see D11.-- [ ] **9.3** Case depth (parity 5.6 remainder)+- [x] **9.3** Case depth (parity 5.6 remainder). All four open bullets.+ **Alert merge needed no schema at all**: `is_merged`, `parent_alert_id` and+ `child_alert_ids` have been on `alerts` since migration 001 with the ORM+ model as their only mention anywhere — the repository's recurring defect,+ and worth naming so "new" means something. Merge keeps every row: a+ duplicate is marked and pointed at its parent, the survivor's children are+ **appended** not replaced, re-merging and merging into a merged alert are+ both refused because each would orphan or cycle the chain, and the+ survivor inherits the case a duplicate was already on. Case merge (migration+ `106`) repoints the alerts and keeps both case rows, because deleting loses+ the audit chain, the custody entries and any vendor ticket already naming+ that id. Bulk triage is new in the route **and** the console: a checkbox per+ row, a select-all that selects this page only, and a bar whose Apply+ performs a real write and surfaces the preflight 409 with the real matched+ count instead of silently retrying. `closed` is deliberately unreachable+ there — `bulk-close` snapshots every row first and a weaker second path to+ one destination is how the weaker one wins. Tenant custom fields are two+ tables rather than a JSONB blob so a field can be enumerated, rendered,+ validated at write time and retired cleanly; values are canonicalised on+ write. Workload is counted per request over rows the query selected, a+ merged-away case is not counted as work, and **a mean over nothing is+ `null`, never `0.0`** — with the count it was taken over beside it. Graded+ by `.github/workflows/case-depth-live.yml` against a real Postgres with+ three negative controls, because every statement here is Postgres-only and+ a SQLite stand-in would be a different query. 29 new tests (23 API live, 6+ web). The live suite earned its keep immediately: it caught that+ `aisoc_cases.alert_ids` is `uuid[]` while the two columns beside it are+ JSONB, which a stand-in would have accepted.- [ ] **9.4** War rooms- [ ] **9.5** Hunt to report- [ ] **9.6** Native responder@@ -500,6 +527,7 @@ invented fields on the first run of the gate.| Date | Item | What happened ||---|---|---|+| 2026-10-11 | 9.3 | Reproduced: the alert merge columns had zero writers outside the ORM model; `grep -rn custom_field services/api` and `grep -rn workload` (excluding workload *identities*) both counted zero; and `grep -rn bulk apps/web/src/components/alerts` found only unrelated comments, so the only bulk verb in the product was `POST /alerts/bulk-close` with no console surface at all. The two-case-table trap named in the brief was already closed by migration 083 and `check_one_case_table.py` reports OK, so `aisoc_cases` is the table this item deepens. Three negative controls recorded in the PR and wired into the live workflow. The live suite found a real defect on its first run: `aisoc_cases.alert_ids` is `uuid[]` while `ioc_ids` and `artifact_ids` beside it are JSONB, and the merge statement had assumed JSONB. || 2026-10-11 | 9.2 | Reproduced: `knowledge_base.py` searched with `to_tsvector`/`plainto_tsquery` and nothing else; `grep -rn qdrant services/api/app/` found only the migration runner and the tenant-deletion sweep, no recall path; and no memory row anywhere carried an author, a source, a scope, an expiry or a state. Built the store of record, the Qdrant index over it, the conflict state machine, the case-closure writer and the recall scorer. Two negative controls recorded in the PR: restoring last-write-wins on a contradiction fails three tests, and restoring vector truncation fails one. The measurement is negative and is published as such — see D11, which also records that it caught the truncation defect. || 2026-10-07 | 0.1 | This file created at base commit `1b8bc2d4`. || 2026-10-07 | 0.2 | Every figure re-derived. Two matched exactly (detections, unreachable families); executor arms measured 74 against a captured 73; the cloud/identity/SaaS/code figure measured 395 against a captured 461 on a grouping the plan does not pin, recorded above. Two measurement caveats found: executable and quarantined overlap by 1,724 rules, and the "69% Windows" figure does not reproduce from the index. |diff --git a/apps/web/src/components/alerts/AlertsQueryOrder.test.tsx b/apps/web/src/components/alerts/AlertsQueryOrder.test.tsxindex 21545de7e..54bae17df 100644--- a/apps/web/src/components/alerts/AlertsQueryOrder.test.tsx+++ b/apps/web/src/components/alerts/AlertsQueryOrder.test.tsx@@ -22,6 +22,12 @@ const swrKeys = vi.hoisted(() => [] as unknown[]);vi.mock('swr', () => ({__esModule: true,+ // `AlertsTable` revalidates through `useSWRConfig().mutate` after a+ // bulk triage. A module mock replaces the whole module, so a named+ // export the component imports has to exist here or the render dies+ // with "useSWRConfig is not a function" — which reads as a broken+ // component rather than an incomplete double.+ useSWRConfig: () => ({ mutate: vi.fn() }),default: (key: unknown) => {swrKeys.push(key);return { data: undefined, error: undefined, isLoading: false, mutate: vi.fn() };diff --git a/apps/web/src/components/alerts/AlertsTileCounts.test.tsx b/apps/web/src/components/alerts/AlertsTileCounts.test.tsxindex 5803c90a8..93f206aa7 100644--- a/apps/web/src/components/alerts/AlertsTileCounts.test.tsx+++ b/apps/web/src/components/alerts/AlertsTileCounts.test.tsx@@ -32,6 +32,12 @@ const swrState = vi.hoisted(() => ({ data: undefined as unknown }));vi.mock('swr', () => ({__esModule: true,+ // `AlertsTable` revalidates through `useSWRConfig().mutate` after a+ // bulk triage. A module mock replaces the whole module, so a named+ // export the component imports has to exist here or the render dies+ // with "useSWRConfig is not a function" — which reads as a broken+ // component rather than an incomplete double.+ useSWRConfig: () => ({ mutate: vi.fn() }),// Key-aware: the page also mounts `SavedViewsBar`, which calls `useSWR` on// its own key and expects an array. Answering every key with the alert// payload crashes it.diff --git a/apps/web/src/components/alerts/AlertsView.tsx b/apps/web/src/components/alerts/AlertsView.tsxindex c5fbf44d1..0549bf7e9 100644--- a/apps/web/src/components/alerts/AlertsView.tsx+++ b/apps/web/src/components/alerts/AlertsView.tsx@@ -1,8 +1,9 @@'use client';import { useState, useCallback } from 'react';-import useSWR from 'swr';+import useSWR, { useSWRConfig } from 'swr';import Link from 'next/link';+import { BulkTriageBar } from './BulkTriageBar';import { alertsApi, type Alert, type AlertFacets, type AlertFilters, type ConfidenceLabel } from '@/lib/api';import { clsx } from 'clsx';import { formatDistanceToNow } from 'date-fns';@@ -223,10 +224,14 @@ function AlertRow({alert,selected,onSelect,+ checked,+ onToggleChecked,}: {alert: Alert;selected: boolean;onSelect: (id: string) => void;+ checked: boolean;+ onToggleChecked: (id: string) => void;}) {return (<Link@@ -247,6 +252,24 @@ function AlertRow({: 'border-l-transparent hover:bg-gray-800/20',)}>+ {/*+ Depth 9.3. The row is a Link, so the checkbox has to stop the event+ before it reaches it — otherwise ticking a box navigates to the+ alert, which is the single most irritating way to break a bulk+ selection.+ */}+ <input+ type="checkbox"+ checked={checked}+ aria-label={`Select ${alert.title}`}+ onClick={(e) => e.stopPropagation()}+ onChange={(e) => {+ e.stopPropagation();+ onToggleChecked(alert.id);+ }}+ className="accent-blue-500 shrink-0"+ />+<SeverityDot severity={alert.severity} /><div className="flex-1 min-w-0">@@ -433,6 +456,20 @@ function AlertsTable({// Switching to the entities tab unmounts this state cleanly, which is// what we want — the rail is alert-scoped, not entity-scoped.const [selectedAlertId, setSelectedAlertId] = useState<string | null>(null);+ // Depth 9.3 — bulk selection, separate from the rail's single selection.+ // A Set rather than an array so toggling is O(1) and the "select all on+ // this page" header checkbox does not have to scan.+ const [checkedIds, setCheckedIds] = useState<Set<string>>(new Set());+ const { mutate } = useSWRConfig();++ const toggleChecked = useCallback((id: string) => {+ setCheckedIds((previous) => {+ const next = new Set(previous);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ }, []);return (<div className="space-y-4">@@ -475,6 +512,15 @@ function AlertsTable({<FiltersBar filters={filters} onChange={onFilterChange} total={total} />+ <BulkTriageBar+ selectedIds={[...checkedIds]}+ onClearSelection={() => setCheckedIds(new Set())}+ // Revalidate rather than patching rows locally: the server decided+ // what changed and an optimistic update would show a state it may+ // not have written.+ onApplied={() => void mutate((key) => Array.isArray(key) && key[0] === 'alerts')}+ />+{/*v1.5 W6 — two-pane layout. On wide screens the queue takes the leftseven cols and the Investigation Rail takes the right five; on narrow@@ -492,6 +538,9 @@ function AlertsTable({selectedAlertId={selectedAlertId}onSelect={setSelectedAlertId}onFilterChange={onFilterChange}+ checkedIds={checkedIds}+ onToggleChecked={toggleChecked}+ onSetChecked={setCheckedIds}/><AlertsPaginationalerts={alerts}@@ -523,6 +572,9 @@ function AlertsTableGrid({selectedAlertId,onSelect,onFilterChange,+ checkedIds,+ onToggleChecked,+ onSetChecked,}: {alerts: Alert[];isLoading: boolean;@@ -531,11 +583,35 @@ function AlertsTableGrid({selectedAlertId: string | null;onSelect: (id: string) => void;onFilterChange: (f: AlertFilters) => void;+ checkedIds: Set<string>;+ onToggleChecked: (id: string) => void;+ onSetChecked: (next: Set<string>) => void;}) {+ const pageIds = alerts.map((a) => a.id);+ const allOnPageChecked = pageIds.length > 0 && pageIds.every((id) => checkedIds.has(id));+return (<div className="bg-gray-900/60 border border-gray-800/60 rounded-xl overflow-hidden">- <div className="flex items-center px-4 py-2 border-b border-gray-800/60 bg-gray-900/80">- <span className="text-xs text-gray-500 flex-1 pl-2">ALERT</span>+ <div className="flex items-center gap-4 px-4 py-2 border-b border-gray-800/60 bg-gray-900/80">+ {/*+ Selects this page only, never "everything matching the filter".+ A control that silently selects rows the analyst cannot see is the+ shape that turns a bulk action into an incident.+ */}+ <input+ type="checkbox"+ aria-label="Select all alerts on this page"+ checked={allOnPageChecked}+ disabled={pageIds.length === 0}+ onChange={(e) => {+ const next = new Set(checkedIds);+ if (e.target.checked) pageIds.forEach((id) => next.add(id));+ else pageIds.forEach((id) => next.delete(id));+ onSetChecked(next);+ }}+ className="accent-blue-500"+ />+ <span className="text-xs text-gray-500 flex-1">ALERT</span><span className="text-xs text-gray-500 w-20">SEVERITY</span><span className="text-xs text-gray-500 w-24">STATUS</span><span className="text-xs text-gray-500 w-24 text-right">TIME</span>@@ -590,6 +666,8 @@ function AlertsTableGrid({alert={alert}selected={selectedAlertId === alert.id}onSelect={onSelect}+ checked={checkedIds.has(alert.id)}+ onToggleChecked={onToggleChecked}/>))}</div>diff --git a/apps/web/src/components/alerts/BulkTriageBar.test.tsx b/apps/web/src/components/alerts/BulkTriageBar.test.tsxnew file mode 100644index 000000000..cd506d943--- /dev/null+++ b/apps/web/src/components/alerts/BulkTriageBar.test.tsx@@ -0,0 +1,141 @@+/**+ * The bulk triage bar: real writes, a surfaced preflight, and honest failure.+ *+ * Depth 9.3 (parity 5.6 remainder).+ *+ * Asserted by name below:+ *+ * * **first paint shows nothing invented** -- with no selection the bar is+ * absent, and with a selection it shows the count the caller passed and no+ * result text. A UI honesty test has to assert on first paint, not only on+ * the error branch, because the error branch runs before the list does and+ * a `data?.x ?? MOCK` is only reachable during first paint;+ * * **the button performs a real write** -- the fetch really happens, with+ * the ids and the change the analyst chose;+ * * **the preflight 409 is surfaced, not swallowed** -- the real matched+ * count is shown and nothing is retried automatically;+ * * **a failure renders as a failure** -- no success text, no cleared+ * selection.+ */++import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { BulkTriageBar } from './BulkTriageBar';++const IDS = ['11111111-1111-1111-1111-111111111111', '22222222-2222-2222-2222-222222222222'];++function mockFetch(impl: (url: string, init?: RequestInit) => Promise<Response>) {+ const spy = vi.fn(impl);+ vi.stubGlobal('fetch', spy as unknown as typeof fetch);+ return spy;+}++function ok(body: unknown): Promise<Response> {+ return Promise.resolve(+ new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } }),+ );+}++beforeEach(() => {+ vi.unstubAllGlobals();+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('BulkTriageBar', () => {+ it('renders nothing when nothing is selected', () => {+ const { container } = render(+ <BulkTriageBar selectedIds={[]} onClearSelection={() => {}} onApplied={() => {}} />,+ );+ expect(container).toBeEmptyDOMElement();+ });++ it('shows the real selection count on first paint and claims no result', () => {+ mockFetch(() => ok({}));+ render(<BulkTriageBar selectedIds={IDS} onClearSelection={() => {}} onApplied={() => {}} />);++ expect(screen.getByText('2 selected')).toBeInTheDocument();+ // Nothing has been applied, so nothing may say so. This is the first+ // paint, which is where an invented value would live.+ expect(screen.queryByText(/Updated/)).not.toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ // And no request has been made just by rendering.+ expect(fetch).not.toHaveBeenCalled();+ });++ it('refuses to apply until a change is chosen', () => {+ render(<BulkTriageBar selectedIds={IDS} onClearSelection={() => {}} onApplied={() => {}} />);+ expect(screen.getByRole('button', { name: 'Apply' })).toBeDisabled();+ });++ it('performs a real write with the chosen change and the selected ids', async () => {+ const user = userEvent.setup();+ const spy = mockFetch(() => ok({ matched_count: 2, updated_count: 2, changes: { status: 'in_progress' } }));+ const onApplied = vi.fn();+ const onClear = vi.fn();++ render(<BulkTriageBar selectedIds={IDS} onClearSelection={onClear} onApplied={onApplied} />);+ await user.selectOptions(screen.getByLabelText('Set status'), 'in_progress');+ await user.click(screen.getByRole('button', { name: 'Apply' }));++ await waitFor(() => expect(spy).toHaveBeenCalledTimes(1), { timeout: 4000 });+ const [url, init] = spy.mock.calls[0];+ expect(String(url)).toContain('/api/v1/case-depth/alerts/bulk-triage');+ const body = JSON.parse(String((init as RequestInit).body));+ expect(body.alert_ids).toEqual(IDS);+ expect(body.set_status).toBe('in_progress');+ expect(body.max_count).toBe(2);++ await screen.findByText(/Updated 2 alerts/);+ expect(onApplied).toHaveBeenCalledWith(2);+ expect(onClear).toHaveBeenCalled();+ }, 15_000);++ it('surfaces the preflight count and does not retry on its own', async () => {+ const user = userEvent.setup();+ const spy = mockFetch(() =>+ Promise.resolve(+ new Response('410 alert(s) match and max_count is 2. Nothing was changed.', { status: 409 }),+ ),+ );+ const onApplied = vi.fn();+ const onClear = vi.fn();++ render(<BulkTriageBar selectedIds={IDS} onClearSelection={onClear} onApplied={onApplied} />);+ await user.selectOptions(screen.getByLabelText('Set severity'), 'low');+ await user.click(screen.getByRole('button', { name: 'Apply' }));++ await screen.findByText(/410 alerts match and nothing was changed/);+ // Exactly one request. Retrying with a larger number on the analyst's+ // behalf would turn a deliberate guard into a formality.+ expect(spy).toHaveBeenCalledTimes(1);+ expect(onApplied).not.toHaveBeenCalled();+ expect(onClear).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: 'Apply to all 410' })).toBeInTheDocument();+ }, 15_000);++ it('renders a failure as a failure and keeps the selection', async () => {+ const user = userEvent.setup();+ mockFetch(() => Promise.resolve(new Response('upstream exploded', { status: 500 })));+ const onApplied = vi.fn();+ const onClear = vi.fn();++ render(<BulkTriageBar selectedIds={IDS} onClearSelection={onClear} onApplied={onApplied} />);+ await user.selectOptions(screen.getByLabelText('Set status'), 'open');+ await user.click(screen.getByRole('button', { name: 'Apply' }));++ const alert = await screen.findByRole('alert');+ expect(alert).toBeInTheDocument();+ expect(screen.queryByText(/Updated/)).not.toBeInTheDocument();+ expect(onApplied).not.toHaveBeenCalled();+ // The selection survives a failure: clearing it would make the analyst+ // reselect rows whose state did not change.+ expect(onClear).not.toHaveBeenCalled();+ expect(screen.getByText('2 selected')).toBeInTheDocument();+ }, 15_000);+});diff --git a/apps/web/src/components/alerts/BulkTriageBar.tsx b/apps/web/src/components/alerts/BulkTriageBar.tsxnew file mode 100644index 000000000..d81361c20--- /dev/null+++ b/apps/web/src/components/alerts/BulkTriageBar.tsx@@ -0,0 +1,213 @@+'use client';++/**+ * Bulk triage for the alert queue.+ *+ * Depth 9.3 (parity 5.6 remainder). The route half existed only as+ * `POST /alerts/bulk-close`, and there was no selection anywhere in the+ * console — an analyst clearing a morning queue clicked through it one alert+ * at a time. Closing is also one triage decision out of several: the same+ * analyst reassigns, re-severities and moves things to in progress.+ *+ * Three rules this bar follows, each one a defect this repository has+ * shipped before:+ *+ * - **No toast-only control.** Every button here performs a real write and+ * the bar reports what the server said it did, by count. A control that+ * shows a success toast and changes nothing is worse than no control.+ * - **The preflight is surfaced, not swallowed.** The route refuses a match+ * larger than `max_count` with a 409 carrying the real figure and writes+ * nothing. The bar shows that figure and asks again, rather than retrying+ * with a bigger number on the analyst's behalf — which would turn a+ * deliberate guard into a formality.+ * - **A failure says so.** There is no optimistic update and no local+ * "saved" state: the selection clears only after the server confirms, and+ * an error renders as an error.+ */++import { useCallback, useState } from 'react';+import clsx from 'clsx';++import { ApiError, caseDepthApi, type BulkTriageChange } from '@/lib/api';++/** Statuses the route accepts. `closed` is absent on purpose — see below. */+const STATUSES = ['new', 'open', 'in_progress', 'resolved', 'dismissed'] as const;+const SEVERITIES = ['info', 'low', 'medium', 'high', 'critical'] as const;++export interface BulkTriageBarProps {+ selectedIds: string[];+ onClearSelection: () => void;+ /** Called after a successful write so the caller can revalidate its list. */+ onApplied: (updated: number) => void;+}++type Outcome =+ | { kind: 'idle' }+ | { kind: 'working' }+ | { kind: 'applied'; updated: number; summary: string }+ | { kind: 'preflight'; matched: number; message: string }+ | { kind: 'failed'; message: string };++export function BulkTriageBar({ selectedIds, onClearSelection, onApplied }: BulkTriageBarProps) {+ const [status, setStatus] = useState<string>('');+ const [severity, setSeverity] = useState<string>('');+ const [unassign, setUnassign] = useState(false);+ const [outcome, setOutcome] = useState<Outcome>({ kind: 'idle' });++ const nothingChosen = status === '' && severity === '' && !unassign;++ const apply = useCallback(+ async (maxCount: number) => {+ const change: BulkTriageChange = {};+ if (status) change.set_status = status;+ if (severity) change.set_severity = severity;+ if (unassign) change.unassign = true;++ setOutcome({ kind: 'working' });+ try {+ const result = await caseDepthApi.bulkTriage(selectedIds, change, maxCount, 'bulk triage from the console');+ const parts = Object.entries(result.changes).map(([k, v]) => `${k}=${String(v)}`);+ setOutcome({+ kind: 'applied',+ updated: result.updated_count,+ summary: parts.join(', ') || 'no change',+ });+ onApplied(result.updated_count);+ onClearSelection();+ } catch (err) {+ if (err instanceof ApiError && err.status === 409) {+ // The server counted more rows than the caller said it expected and+ // wrote nothing. Show the real figure and let the analyst decide;+ // retrying automatically with a larger number would make the guard+ // a formality.+ const matched = Number(/(\d+) alert\(s\) match/.exec(err.body)?.[1] ?? selectedIds.length);+ setOutcome({ kind: 'preflight', matched, message: err.body || err.message });+ return;+ }+ setOutcome({+ kind: 'failed',+ message: err instanceof Error ? err.message : 'The bulk triage request failed.',+ });+ }+ },+ [onApplied, onClearSelection, selectedIds, severity, status, unassign],+ );++ if (selectedIds.length === 0) return null;++ return (+ <div+ className="bg-blue-500/10 border border-blue-500/30 rounded-xl px-4 py-3 space-y-2"+ role="region"+ aria-label="Bulk triage"+ >+ <div className="flex flex-wrap items-center gap-3">+ <span className="text-sm text-blue-200 font-medium">+ {selectedIds.length} selected+ </span>++ <label className="text-xs text-gray-400">+ Status+ <select+ aria-label="Set status"+ value={status}+ onChange={(e) => setStatus(e.target.value)}+ className="ml-2 bg-gray-900 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200"+ >+ <option value="">leave as is</option>+ {STATUSES.map((s) => (+ <option key={s} value={s}>+ {s}+ </option>+ ))}+ </select>+ </label>++ <label className="text-xs text-gray-400">+ Severity+ <select+ aria-label="Set severity"+ value={severity}+ onChange={(e) => setSeverity(e.target.value)}+ className="ml-2 bg-gray-900 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200"+ >+ <option value="">leave as is</option>+ {SEVERITIES.map((s) => (+ <option key={s} value={s}>+ {s}+ </option>+ ))}+ </select>+ </label>++ <label className="text-xs text-gray-400 flex items-center gap-1.5">+ <input+ type="checkbox"+ aria-label="Unassign"+ checked={unassign}+ onChange={(e) => setUnassign(e.target.checked)}+ className="accent-blue-500"+ />+ Unassign+ </label>++ <button+ type="button"+ disabled={nothingChosen || outcome.kind === 'working'}+ onClick={() => void apply(selectedIds.length)}+ className={clsx(+ 'text-xs px-3 py-1.5 rounded-md border transition-colors',+ nothingChosen || outcome.kind === 'working'+ ? 'border-gray-700 bg-gray-800 text-gray-500 cursor-not-allowed'+ : 'border-blue-500/40 bg-blue-500/20 text-blue-200 hover:bg-blue-500/30',+ )}+ >+ {outcome.kind === 'working' ? 'Applying…' : 'Apply'}+ </button>++ <button+ type="button"+ onClick={onClearSelection}+ className="text-xs px-3 py-1.5 rounded-md border border-gray-700 text-gray-400 hover:text-gray-200"+ >+ Clear+ </button>++ {/*+ Closing in bulk deliberately is not here. It has its own route that+ snapshots every affected row into a named backup table first, and a+ second path to the same destination with weaker guarantees is how+ the weaker one becomes the one everybody uses.+ */}+ <span className="text-[11px] text-gray-500 ml-auto">+ To close in bulk, use the noise sweep — it snapshots every row first.+ </span>+ </div>++ {outcome.kind === 'applied' && (+ <p className="text-xs text-emerald-300" role="status">+ Updated {outcome.updated} alert{outcome.updated === 1 ? '' : 's'} ({outcome.summary}).+ </p>+ )}+ {outcome.kind === 'preflight' && (+ <div className="text-xs text-amber-300 space-y-1" role="status">+ <p>+ {outcome.matched} alert{outcome.matched === 1 ? '' : 's'} match and nothing was changed.+ </p>+ <button+ type="button"+ onClick={() => void apply(outcome.matched)}+ className="px-2 py-1 rounded border border-amber-400/40 bg-amber-400/10 hover:bg-amber-400/20"+ >+ Apply to all {outcome.matched}+ </button>+ </div>+ )}+ {outcome.kind === 'failed' && (+ <p className="text-xs text-red-400" role="alert">+ {outcome.message}+ </p>+ )}+ </div>+ );+}diff --git a/apps/web/src/components/cases/AnalystWorkload.tsx b/apps/web/src/components/cases/AnalystWorkload.tsxnew file mode 100644index 000000000..46486b978--- /dev/null+++ b/apps/web/src/components/cases/AnalystWorkload.tsx@@ -0,0 +1,112 @@+'use client';++/**+ * Per-analyst workload.+ *+ * Depth 9.3 (parity 5.6 remainder). There was no workload surface anywhere:+ * a lead could not answer "who is carrying what" without reading the case+ * list by hand.+ *+ * The honesty rules this panel exists under, each one a defect this+ * repository has shipped:+ *+ * - **No `fallbackData`.** Setting it disables revalidation, so a mock stops+ * being a first paint and becomes what the view *shows*. There is no mock+ * here at all, and the first paint is a loading state.+ * - **`mean_hours_to_close: null` renders as "no data", never `0.0`.** A+ * zero there reads as "closed instantly", which is the opposite of what it+ * means, and that exact confusion left two console figures wrong for+ * months.+ * - **Every mean shows the count it was taken over.** A mean over three+ * cases and a mean over three hundred are different claims.+ * - **An error says it is an error.** No invented rows, no empty list+ * standing in for a failed fetch.+ */++import useSWR from 'swr';++import { caseDepthApi, type AnalystWorkloadRow } from '@/lib/api';++function MeanToClose({ row }: { row: AnalystWorkloadRow }) {+ if (row.mean_hours_to_close === null) {+ return (+ <span className="text-gray-600" title="This analyst has closed no cases in the window, so there is nothing to average.">+ no data+ </span>+ );+ }+ return (+ <span className="text-gray-300">+ {row.mean_hours_to_close.toFixed(1)}h{' '}+ <span className="text-gray-600 text-[11px]">over {row.mean_over_cases}</span>+ </span>+ );+}++export function AnalystWorkload({ days = 30 }: { days?: number }) {+ const { data, error, isLoading } = useSWR(['case-workload', days], () => caseDepthApi.workload(days), {+ refreshInterval: 60_000,+ });++ return (+ <section+ className="bg-gray-900/60 border border-gray-800/60 rounded-xl overflow-hidden"+ aria-label="Analyst workload"+ >+ <header className="px-4 py-3 border-b border-gray-800/60 flex items-baseline justify-between">+ <h2 className="text-sm font-semibold text-gray-200">Analyst workload</h2>+ <span className="text-[11px] text-gray-500">last {days} days</span>+ </header>++ {isLoading ? (+ <p className="px-4 py-6 text-xs text-gray-500">Loading…</p>+ ) : error ? (+ <p className="px-4 py-6 text-xs text-red-400" role="alert">+ Couldn't load workload. The cases API didn't respond.+ </p>+ ) : !data || data.analysts.length === 0 ? (+ <p className="px-4 py-6 text-xs text-gray-500">+ No case has an assignee in this window, so there is no workload to show.+ {data ? ` ${data.unassigned.open_cases} open case(s) are unassigned.` : ''}+ </p>+ ) : (+ <table className="w-full text-xs">+ <thead>+ <tr className="text-gray-500 border-b border-gray-800/60">+ <th className="text-left font-normal px-4 py-2">Analyst</th>+ <th className="text-right font-normal px-3 py-2">Open</th>+ <th className="text-right font-normal px-3 py-2">High / critical</th>+ <th className="text-right font-normal px-3 py-2">Overdue</th>+ <th className="text-right font-normal px-3 py-2">Closed</th>+ <th className="text-right font-normal px-4 py-2">Mean to close</th>+ </tr>+ </thead>+ <tbody>+ {data.analysts.map((row) => (+ <tr key={row.analyst} className="border-b border-gray-800/30 last:border-0">+ <td className="px-4 py-2 text-gray-200 truncate max-w-[14rem]">{row.analyst}</td>+ <td className="px-3 py-2 text-right text-gray-300">{row.open_cases}</td>+ <td className="px-3 py-2 text-right text-orange-300">{row.open_high_or_critical}</td>+ <td className="px-3 py-2 text-right text-red-300">{row.overdue}</td>+ <td className="px-3 py-2 text-right text-gray-400">{row.closed_cases}</td>+ <td className="px-4 py-2 text-right">+ <MeanToClose row={row} />+ </td>+ </tr>+ ))}+ {data.unassigned.open_cases > 0 && (+ <tr className="border-t border-gray-800/60 bg-gray-900/40">+ <td className="px-4 py-2 text-gray-500 italic">Unassigned</td>+ <td className="px-3 py-2 text-right text-gray-300">{data.unassigned.open_cases}</td>+ <td className="px-3 py-2 text-right text-orange-300">{data.unassigned.open_high_or_critical}</td>+ <td className="px-3 py-2 text-right text-gray-600">—</td>+ <td className="px-3 py-2 text-right text-gray-600">—</td>+ <td className="px-4 py-2 text-right text-gray-600">—</td>+ </tr>+ )}+ </tbody>+ </table>+ )}+ </section>+ );+}diff --git a/apps/web/src/components/cases/CasesView.tsx b/apps/web/src/components/cases/CasesView.tsxindex 311325431..cb770cb92 100644--- a/apps/web/src/components/cases/CasesView.tsx+++ b/apps/web/src/components/cases/CasesView.tsx@@ -1,6 +1,7 @@'use client';import { useState } from 'react';+import { AnalystWorkload } from './AnalystWorkload';import useSWR from 'swr';import Link from 'next/link';import toast from 'react-hot-toast';@@ -222,6 +223,11 @@ export function CasesView() {</div></div>+ {/* Depth 9.3 — who is carrying what. Its own fetch, so a workload+ failure does not blank the case list and a case-list failure does+ not blank the workload. */}+ <AnalystWorkload />+{/* Stats */}<div className="grid grid-cols-5 gap-3">{/*diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex fd03befde..ff80dac2a 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -7374,3 +7374,114 @@ export const evaluationsApi = {`${API_BASE}/api/v1/evaluations/replay/${id}/export` +`?format=${format}&exclude_latency=${excludeLatency ? 'true' : 'false'}`,};++// ─── Case depth (depth 9.3 / parity 5.6 remainder) ───────────────────────────++export interface BulkTriageChange {+ set_status?: string;+ set_severity?: string;+ assign_to?: string;+ unassign?: boolean;+}++export interface BulkTriageResult {+ matched_count: number;+ updated_count: number;+ changes: Record<string, unknown>;+}++export interface AnalystWorkloadRow {+ analyst: string;+ total: number;+ open_cases: number;+ closed_cases: number;+ open_high_or_critical: number;+ overdue: number;+ /**+ * `null` when the analyst has closed nothing in the window. The console+ * must render that as "no data" and never as `0.0`, which reads as+ * "instant" — the exact confusion that left two console figures wrong for+ * months.+ */+ mean_hours_to_close: number | null;+ /** How many closed cases the mean above was taken over. */+ mean_over_cases: number;+}++export interface AnalystWorkload {+ since: string;+ computed_at: string;+ analysts: AnalystWorkloadRow[];+ unassigned: { open_cases: number; open_high_or_critical: number };+}++export const caseDepthApi = {+ /**+ * Apply one triage decision to many alerts.+ *+ * `maxCount` is a preflight the caller states: a larger match is refused+ * with a 409 carrying the real figure and **nothing is written**, so the+ * first call is a dry run. The bar surfaces that count and asks again+ * rather than retrying silently with a bigger number.+ */+ bulkTriage: (alertIds: string[], change: BulkTriageChange, maxCount: number, comment = '') =>+ request<BulkTriageResult>('/api/v1/case-depth/alerts/bulk-triage', {+ method: 'POST',+ body: JSON.stringify({ alert_ids: alertIds, max_count: maxCount, comment, ...change }),+ }),++ mergeAlerts: (primaryId: string, duplicateIds: string[], reason = '') =>+ request<{ primary_id: string; merged_ids: string[]; case_id: string | null }>(+ '/api/v1/case-depth/alerts/merge',+ {+ method: 'POST',+ body: JSON.stringify({ primary_id: primaryId, duplicate_ids: duplicateIds, reason }),+ },+ ),++ mergeCases: (primaryId: string, duplicateIds: string[], reason = '') =>+ request<{ primary_id: string; merged_ids: string[]; case_id: string | null }>(+ '/api/v1/case-depth/cases/merge',+ {+ method: 'POST',+ body: JSON.stringify({ primary_id: primaryId, duplicate_ids: duplicateIds, reason }),+ },+ ),++ workload: (days = 30) =>+ request<AnalystWorkload>('/api/v1/case-depth/workload', { params: { days: String(days) } }),++ customFields: () =>+ request<+ Array<{+ id: string;+ key: string;+ label: string;+ help_text: string;+ field_type: string;+ choices: string[];+ required: boolean;+ position: number;+ active: boolean;+ }>+ >('/api/v1/case-depth/custom-fields'),++ caseCustomValues: (caseId: string) =>+ request<+ Array<{+ key: string;+ label: string;+ field_type: string;+ value: string;+ required: boolean;+ updated_by: string;+ updated_at: string | null;+ }>+ >(`/api/v1/case-depth/cases/${caseId}/custom-values`),++ setCaseCustomValues: (caseId: string, values: Record<string, string>) =>+ request<unknown>(`/api/v1/case-depth/cases/${caseId}/custom-values`, {+ method: 'PUT',+ body: JSON.stringify({ values }),+ }),+};diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 0ccdaa92f..977d4b391 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -2070,6 +2070,343 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/case-depth/alerts/merge:+ post:+ tags:+ - case-depth+ summary: Merge Alerts Route+ description: Fold duplicate alerts into one. Every row survives.+ operationId: merge_alerts_route_api_v1_case_depth_alerts_merge_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/MergeRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/MergeResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/case-depth/cases/merge:+ post:+ tags:+ - case-depth+ summary: Merge Cases Route+ description: Fold duplicate cases into one. Alerts follow; both rows survive.+ operationId: merge_cases_route_api_v1_case_depth_cases_merge_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/MergeRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/MergeResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/case-depth/alerts/bulk-triage:+ post:+ tags:+ - case-depth+ summary: Bulk Triage Route+ description: 'Apply one triage decision to many alerts, with a preflight count.+++ A match larger than ``max_count`` is a **409 carrying the real figure**++ and nothing is written — the same contract ``POST /alerts/bulk-close``++ uses, deliberately, because a second bulk path with weaker guarantees is++ how the weaker one becomes the one everybody reaches for.'+ operationId: bulk_triage_route_api_v1_case_depth_alerts_bulk_triage_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BulkTriageRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BulkTriageResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/case-depth/custom-fields:+ get:+ tags:+ - case-depth+ summary: List Custom Fields+ operationId: list_custom_fields_api_v1_case_depth_custom_fields_get+ security:+ - HTTPBearer: []+ parameters:+ - name: include_inactive+ in: query+ required: false+ schema:+ type: boolean+ default: false+ title: Include Inactive+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: array+ items:+ $ref: '#/components/schemas/CustomFieldOut'+ title: Response List Custom Fields Api V1 Case Depth Custom Fields+ Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ post:+ tags:+ - case-depth+ summary: Create Custom Field+ operationId: create_custom_field_api_v1_case_depth_custom_fields_post+ security:+ - HTTPBearer: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CustomFieldIn'+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CustomFieldOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/case-depth/custom-fields/{field_id}:+ patch:+ tags:+ - case-depth+ summary: Update Custom Field+ operationId: update_custom_field_api_v1_case_depth_custom_fields__field_id__patch+ security:+ - HTTPBearer: []+ parameters:+ - name: field_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Field Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CustomFieldPatch'+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CustomFieldOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ delete:+ tags:+ - case-depth+ summary: Retire Custom Field+ description: 'Retire, never delete: values already written stay readable and+ attributable.'+ operationId: retire_custom_field_api_v1_case_depth_custom_fields__field_id__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: field_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Field Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CustomFieldOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/case-depth/cases/{case_id}/custom-values:+ get:+ tags:+ - case-depth+ summary: Get Custom Values+ description: 'Every active field, with this case''s value or an empty one.+++ Returns the *fields*, not the stored rows, so a field defined after the++ case was created still renders — the alternative is a form that silently++ omits whatever was added last week.'+ operationId: get_custom_values_api_v1_case_depth_cases__case_id__custom_values_get+ security:+ - HTTPBearer: []+ parameters:+ - name: case_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Case Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: array+ items:+ $ref: '#/components/schemas/CustomValueOut'+ title: Response Get Custom Values Api V1 Case Depth Cases Case Id Custom+ Values Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ put:+ tags:+ - case-depth+ summary: Set Custom Values+ operationId: set_custom_values_api_v1_case_depth_cases__case_id__custom_values_put+ security:+ - HTTPBearer: []+ parameters:+ - name: case_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Case Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CustomValuesIn'+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: array+ items:+ $ref: '#/components/schemas/CustomValueOut'+ title: Response Set Custom Values Api V1 Case Depth Cases Case Id Custom+ Values Put+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/case-depth/workload:+ get:+ tags:+ - case-depth+ summary: Workload+ description: 'Per-analyst open, closed, overdue and mean time to close.+++ Every number is counted by this request over rows it selected. An analyst++ who has closed nothing gets ``mean_hours_to_close: null`` and the console++ renders that as "no data" — never ``0.0``, which reads as "instant".'+ operationId: workload_api_v1_case_depth_workload_get+ security:+ - HTTPBearer: []+ parameters:+ - name: days+ in: query+ required: false+ schema:+ type: integer+ maximum: 365+ minimum: 1+ default: 30+ title: Days+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: object+ additionalProperties: true+ title: Response Workload Api V1 Case Depth Workload Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/cases/{case_id}/attack-chain:get:tags:@@ -22767,6 +23104,69 @@ components:- updated- skippedtitle: BulkToggleResponse+ BulkTriageRequest:+ properties:+ alert_ids:+ items:+ type: string+ format: uuid+ type: array+ maxItems: 5000+ minItems: 1+ title: Alert Ids+ set_status:+ anyOf:+ - type: string+ - type: 'null'+ title: Set Status+ set_severity:+ anyOf:+ - type: string+ - type: 'null'+ title: Set Severity+ assign_to:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Assign To+ unassign:+ type: boolean+ title: Unassign+ default: false+ max_count:+ type: integer+ maximum: 5000.0+ minimum: 1.0+ title: Max Count+ default: 100+ comment:+ type: string+ maxLength: 500+ title: Comment+ default: ''+ type: object+ required:+ - alert_ids+ title: BulkTriageRequest+ BulkTriageResponse:+ properties:+ matched_count:+ type: integer+ title: Matched Count+ updated_count:+ type: integer+ title: Updated Count+ changes:+ additionalProperties: true+ type: object+ title: Changes+ type: object+ required:+ - matched_count+ - updated_count+ - changes+ title: BulkTriageResponseBundleJob:properties:job_id:@@ -25075,6 +25475,180 @@ components:- summary- evidencetitle: CspmScanResponse+ CustomFieldIn:+ properties:+ key:+ type: string+ maxLength: 64+ minLength: 1+ pattern: ^[a-z][a-z0-9_]*$+ title: Key+ label:+ type: string+ maxLength: 120+ minLength: 1+ title: Label+ field_type:+ type: string+ title: Field Type+ help_text:+ type: string+ maxLength: 400+ title: Help Text+ default: ''+ choices:+ items:+ type: string+ type: array+ maxItems: 50+ title: Choices+ required:+ type: boolean+ title: Required+ default: false+ position:+ type: integer+ maximum: 999.0+ minimum: 0.0+ title: Position+ default: 0+ type: object+ required:+ - key+ - label+ - field_type+ title: CustomFieldIn+ CustomFieldOut:+ properties:+ id:+ type: string+ title: Id+ key:+ type: string+ title: Key+ label:+ type: string+ title: Label+ help_text:+ type: string+ title: Help Text+ field_type:+ type: string+ title: Field Type+ choices:+ items:+ type: string+ type: array+ title: Choices+ required:+ type: boolean+ title: Required+ position:+ type: integer+ title: Position+ active:+ type: boolean+ title: Active+ type: object+ required:+ - id+ - key+ - label+ - help_text+ - field_type+ - choices+ - required+ - position+ - active+ title: CustomFieldOut+ CustomFieldPatch:+ properties:+ label:+ anyOf:+ - type: string+ maxLength: 120+ - type: 'null'+ title: Label+ help_text:+ anyOf:+ - type: string+ maxLength: 400+ - type: 'null'+ title: Help Text+ choices:+ anyOf:+ - items:+ type: string+ type: array+ maxItems: 50+ - type: 'null'+ title: Choices+ required:+ anyOf:+ - type: boolean+ - type: 'null'+ title: Required+ position:+ anyOf:+ - type: integer+ maximum: 999.0+ minimum: 0.0+ - type: 'null'+ title: Position+ active:+ anyOf:+ - type: boolean+ - type: 'null'+ title: Active+ type: object+ title: CustomFieldPatch+ CustomValueOut:+ properties:+ key:+ type: string+ title: Key+ label:+ type: string+ title: Label+ field_type:+ type: string+ title: Field Type+ value:+ type: string+ title: Value+ required:+ type: boolean+ title: Required+ updated_by:+ type: string+ title: Updated By+ updated_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Updated At+ type: object+ required:+ - key+ - label+ - field_type+ - value+ - required+ - updated_by+ - updated_at+ title: CustomValueOut+ CustomValuesIn:+ properties:+ values:+ additionalProperties:+ type: string+ type: object+ title: Values+ type: object+ required:+ - values+ title: CustomValuesInDashboardMetrics:properties:period:@@ -30253,6 +30827,51 @@ components:required:- querytitle: MemoryRecallIn+ MergeRequest:+ properties:+ primary_id:+ type: string+ format: uuid+ title: Primary Id+ duplicate_ids:+ items:+ type: string+ format: uuid+ type: array+ maxItems: 200+ minItems: 1+ title: Duplicate Ids+ reason:+ type: string+ maxLength: 500+ title: Reason+ default: ''+ type: object+ required:+ - primary_id+ - duplicate_ids+ title: MergeRequest+ MergeResponse:+ properties:+ primary_id:+ type: string+ title: Primary Id+ merged_ids:+ items:+ type: string+ type: array+ title: Merged Ids+ case_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Case Id+ type: object+ required:+ - primary_id+ - merged_ids+ - case_id+ title: MergeResponseMetricsOut:properties:tenant_id:diff --git a/services/api/app/api/v1/endpoints/case_depth.py b/services/api/app/api/v1/endpoints/case_depth.pynew file mode 100644index 000000000..a7994157e--- /dev/null+++ b/services/api/app/api/v1/endpoints/case_depth.py@@ -0,0 +1,664 @@+"""Routes for case depth: merge, bulk triage, custom fields, workload.++Depth plan 9.3 (parity 5.6 remainder).++* ``POST /case-depth/alerts/merge`` fold duplicate alerts into one+* ``POST /case-depth/cases/merge`` fold duplicate cases into one+* ``POST /case-depth/alerts/bulk-triage`` one triage decision, many alerts+* ``GET/POST/PATCH/DELETE /case-depth/custom-fields`` the tenant's case schema+* ``GET/PUT /case-depth/cases/{id}/custom-values`` the values on one case+* ``GET /case-depth/workload`` per-analyst counts, computed now++Why a prefix of its own rather than hanging these off ``/alerts`` and+``/cases``+---------------------------------------------------------------------+``cases.py`` is 1,400 lines and already owns a six-state machine, SLA+projection and connector fan-out; ``alerts.py`` is larger. Both have a+history of a path parameter swallowing a sibling segment — ``GET /{hunt_id}``+ate ``/runs`` and ``/findings`` because a path parameter compiles to+``[^/]+``. Adding ``/alerts/merge`` beside ``/alerts/{alert_id}`` is exactly+that shape again, and the fix for it last time was a path convertor rather+than a declaration-order convention a later edit can undo. A separate prefix+has no such parameter to collide with.++Authorization is per verb, not per module+-----------------------------------------+Merging and bulk triage are ``alerts:write`` / ``cases:write``. Defining the+tenant's case schema is ``settings:write``, because it changes what every+analyst's form looks like. Reading workload is ``cases:read``: a lead+looking at their team's queue is reading cases.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta+from typing import Annotated, Any++import structlog+from fastapi import APIRouter, Depends, HTTPException, Query, Request, status+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.case_depth import (+ BULK_TRIAGE_STATUSES,+ FIELD_TYPES,+ SEVERITIES,+ CaseDepthError,+ analyst_workload,+ bulk_triage,+ merge_alerts,+ merge_cases,+ validate_custom_value,+)++logger = structlog.get_logger()++router = APIRouter(prefix="/case-depth", tags=["case-depth"])+++# ---------------------------------------------------------------------------+# Wire models+# ---------------------------------------------------------------------------+++class MergeRequest(BaseModel):+ primary_id: uuid.UUID+ duplicate_ids: list[uuid.UUID] = Field(min_length=1, max_length=200)+ reason: str = Field(default="", max_length=500)+++class MergeResponse(BaseModel):+ primary_id: str+ merged_ids: list[str]+ case_id: str | None+++class BulkTriageRequest(BaseModel):+ alert_ids: list[uuid.UUID] = Field(min_length=1, max_length=5_000)+ set_status: str | None = None+ set_severity: str | None = None+ assign_to: uuid.UUID | None = None+ unassign: bool = False+ #: The caller states what they expect to touch. A larger match is refused+ #: with the real figure and nothing is written, so the first call is a+ #: dry run the caller did not have to ask for. Same contract as+ #: ``POST /alerts/bulk-close``.+ max_count: int = Field(default=100, ge=1, le=5_000)+ comment: str = Field(default="", max_length=500)+++class BulkTriageResponse(BaseModel):+ matched_count: int+ updated_count: int+ changes: dict[str, Any]+++class CustomFieldIn(BaseModel):+ key: str = Field(min_length=1, max_length=64, pattern=r"^[a-z][a-z0-9_]*$")+ label: str = Field(min_length=1, max_length=120)+ field_type: str+ help_text: str = Field(default="", max_length=400)+ choices: list[str] = Field(default_factory=list, max_length=50)+ required: bool = False+ position: int = Field(default=0, ge=0, le=999)+++class CustomFieldPatch(BaseModel):+ label: str | None = Field(default=None, max_length=120)+ help_text: str | None = Field(default=None, max_length=400)+ choices: list[str] | None = Field(default=None, max_length=50)+ required: bool | None = None+ position: int | None = Field(default=None, ge=0, le=999)+ active: bool | None = None+++class CustomFieldOut(BaseModel):+ id: str+ key: str+ label: str+ help_text: str+ field_type: str+ choices: list[str]+ required: bool+ position: int+ active: bool+++class CustomValuesIn(BaseModel):+ #: ``{field key: value}``. A key the tenant has not defined is refused+ #: rather than stored: an unvalidated value under an unknown key is the+ #: JSONB-blob failure this schema exists to avoid.+ values: dict[str, str]+++class CustomValueOut(BaseModel):+ key: str+ label: str+ field_type: str+ value: str+ required: bool+ updated_by: str+ updated_at: datetime | None+++# ---------------------------------------------------------------------------+# Merge+# ---------------------------------------------------------------------------++[email protected]("/alerts/merge", response_model=MergeResponse)+async def merge_alerts_route(+ body: MergeRequest,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("alerts:write"))],+) -> MergeResponse:+ """Fold duplicate alerts into one. Every row survives."""+ actor = current_user.api_key_prefix or current_user.email+ try:+ result = await merge_alerts(+ db,+ tenant_id=current_user.tenant_id,+ primary_id=body.primary_id,+ duplicate_ids=body.duplicate_ids,+ actor=actor,+ )+ except CaseDepthError 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="alerts:merge",+ resource="alert",+ resource_id=str(result.primary_id),+ changes={"merged": [str(i) for i in result.merged_ids], "reason": body.reason},+ request=request,+ )+ await db.commit()+ return MergeResponse(+ primary_id=str(result.primary_id),+ merged_ids=[str(i) for i in result.merged_ids],+ case_id=str(result.case_id) if result.case_id else None,+ )++[email protected]("/cases/merge", response_model=MergeResponse)+async def merge_cases_route(+ body: MergeRequest,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("cases:write"))],+) -> MergeResponse:+ """Fold duplicate cases into one. Alerts follow; both rows survive."""+ actor = current_user.api_key_prefix or current_user.email+ try:+ result = await merge_cases(+ db,+ tenant_id=current_user.tenant_id,+ primary_id=body.primary_id,+ duplicate_ids=body.duplicate_ids,+ actor=actor,+ reason=body.reason,+ )+ except CaseDepthError 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="cases:merge",+ resource="case",+ resource_id=str(result.primary_id),+ changes={"merged": [str(i) for i in result.merged_ids], "reason": body.reason},+ request=request,+ )+ await db.commit()+ return MergeResponse(+ primary_id=str(result.primary_id),+ merged_ids=[str(i) for i in result.merged_ids],+ case_id=str(result.primary_id),+ )+++# ---------------------------------------------------------------------------+# Bulk triage+# ---------------------------------------------------------------------------++[email protected]("/alerts/bulk-triage", response_model=BulkTriageResponse)+async def bulk_triage_route(+ body: BulkTriageRequest,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("alerts:write"))],+) -> BulkTriageResponse:+ """Apply one triage decision to many alerts, with a preflight count.++ A match larger than ``max_count`` is a **409 carrying the real figure**+ and nothing is written — the same contract ``POST /alerts/bulk-close``+ uses, deliberately, because a second bulk path with weaker guarantees is+ how the weaker one becomes the one everybody reaches for.+ """+ try:+ result = await bulk_triage(+ db,+ tenant_id=current_user.tenant_id,+ alert_ids=body.alert_ids,+ set_status=body.set_status,+ set_severity=body.set_severity,+ assign_to=body.assign_to,+ unassign=body.unassign,+ max_count=body.max_count,+ )+ except CaseDepthError as exc:+ code = status.HTTP_409_CONFLICT if "max_count" in str(exc) else status.HTTP_422_UNPROCESSABLE_ENTITY+ raise HTTPException(status_code=code, 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="alerts:bulk_triage",+ resource="alert",+ resource_id=f"{result.updated_count} alert(s)",+ changes={"changes": result.changes, "matched": result.matched_count, "comment": body.comment},+ request=request,+ )+ await db.commit()+ return BulkTriageResponse(+ matched_count=result.matched_count,+ updated_count=result.updated_count,+ changes=result.changes,+ )+++# ---------------------------------------------------------------------------+# Tenant custom fields+# ---------------------------------------------------------------------------+++#: Every column COALESCEd against itself, so an absent field in the PATCH+#: body leaves the column alone without the statement changing shape. Each+#: parameter carries an explicit cast: inside a COALESCE a bare parameter+#: has no inferable type and asyncpg refuses the statement with+#: `could not determine data type of parameter $n`.+_UPDATE_FIELD_SQL = """+UPDATE aisoc_tenant_custom_fields SET+ label = COALESCE(CAST(:label AS text), label),+ help_text = COALESCE(CAST(:help_text AS text), help_text),+ required = COALESCE(CAST(:required AS boolean), required),+ position = COALESCE(CAST(:position AS integer), position),+ active = COALESCE(CAST(:active AS boolean), active),+ choices = COALESCE(CAST(:choices AS text[]), choices),+ updated_at = NOW()+WHERE id = :id AND tenant_id = :tenant_id+RETURNING *+"""+++def _field_out(row: Any) -> CustomFieldOut:+ return CustomFieldOut(+ id=str(row["id"]),+ key=row["key"],+ label=row["label"],+ help_text=row["help_text"],+ field_type=row["field_type"],+ choices=list(row["choices"] or []),+ required=row["required"],+ position=row["position"],+ active=row["active"],+ )++[email protected]("/custom-fields", response_model=list[CustomFieldOut])+async def list_custom_fields(+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("cases:read"))],+ include_inactive: bool = Query(default=False),+) -> list[CustomFieldOut]:+ # A parameter, not a clause spliced into the statement. Both forms were+ # correct and only this one stops reading as dynamic SQL to every+ # scanner and every reviewer that looks at it.+ rows = (+ (+ await db.execute(+ text(+ "SELECT * FROM aisoc_tenant_custom_fields "+ "WHERE tenant_id = :tenant_id AND (active OR CAST(:include_inactive AS boolean)) "+ "ORDER BY position, key"+ ).bindparams(tenant_id=current_user.tenant_id, include_inactive=include_inactive)+ )+ )+ .mappings()+ .all()+ )+ return [_field_out(row) for row in rows]++[email protected]("/custom-fields", response_model=CustomFieldOut, status_code=status.HTTP_201_CREATED)+async def create_custom_field(+ body: CustomFieldIn,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("settings:write"))],+) -> CustomFieldOut:+ if body.field_type not in FIELD_TYPES:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"field_type must be one of {list(FIELD_TYPES)}",+ )+ if body.field_type == "select" and not body.choices:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="a select field needs at least one choice; an empty dropdown is one a required field makes unsaveable",+ )+ existing = (+ await db.execute(+ text("SELECT id FROM aisoc_tenant_custom_fields WHERE tenant_id = :tenant_id AND key = :key").bindparams(+ tenant_id=current_user.tenant_id, key=body.key+ )+ )+ ).scalar_one_or_none()+ if existing is not None:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=f"{body.key} already exists. Keys are immutable by convention: a rename in place "+ "silently changes the meaning of every value already written against it.",+ )++ row = (+ (+ await db.execute(+ text(+ "INSERT INTO aisoc_tenant_custom_fields "+ "(tenant_id, key, label, help_text, field_type, choices, required, position) "+ "VALUES (:tenant_id, :key, :label, :help_text, :field_type, CAST(:choices AS text[]), :required, :position) "+ "RETURNING *"+ ).bindparams(+ tenant_id=current_user.tenant_id,+ key=body.key,+ label=body.label,+ help_text=body.help_text,+ field_type=body.field_type,+ choices=body.choices,+ required=body.required,+ position=body.position,+ )+ )+ )+ .mappings()+ .one()+ )++ 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="case_custom_field:create",+ resource="case_custom_field",+ resource_id=body.key,+ changes={"field_type": body.field_type, "required": body.required},+ request=request,+ )+ await db.commit()+ return _field_out(row)++[email protected]("/custom-fields/{field_id}", response_model=CustomFieldOut)+async def update_custom_field(+ field_id: uuid.UUID,+ body: CustomFieldPatch,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("settings:write"))],+) -> CustomFieldOut:+ # One static statement with COALESCE per column, rather than a SET list+ # assembled in Python. The assembled form was correct -- every fragment+ # came from the literal tuple above -- and it still read as dynamic SQL+ # to every scanner and every reviewer, forever.+ row = (+ (+ await db.execute(+ text(_UPDATE_FIELD_SQL).bindparams(+ id=field_id,+ tenant_id=current_user.tenant_id,+ label=body.label,+ help_text=body.help_text,+ required=body.required,+ position=body.position,+ active=body.active,+ choices=body.choices,+ )+ )+ )+ .mappings()+ .one_or_none()+ )+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such custom field")++ 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="case_custom_field:update",+ resource="case_custom_field",+ resource_id=row["key"],+ changes=body.model_dump(exclude_none=True),+ request=request,+ )+ await db.commit()+ return _field_out(row)++[email protected]("/custom-fields/{field_id}", response_model=CustomFieldOut)+async def retire_custom_field(+ field_id: uuid.UUID,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("settings:write"))],+) -> CustomFieldOut:+ """Retire, never delete: values already written stay readable and attributable."""+ row = (+ (+ await db.execute(+ text(+ "UPDATE aisoc_tenant_custom_fields SET active = FALSE, updated_at = NOW() "+ "WHERE id = :id AND tenant_id = :tenant_id RETURNING *"+ ).bindparams(id=field_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 custom field")+ 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="case_custom_field:retire",+ resource="case_custom_field",+ resource_id=row["key"],+ changes={"active": False},+ request=request,+ )+ await db.commit()+ return _field_out(row)++[email protected]("/cases/{case_id}/custom-values", response_model=list[CustomValueOut])+async def get_custom_values(+ case_id: uuid.UUID,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("cases:read"))],+) -> list[CustomValueOut]:+ """Every active field, with this case's value or an empty one.++ Returns the *fields*, not the stored rows, so a field defined after the+ case was created still renders — the alternative is a form that silently+ omits whatever was added last week.+ """+ rows = (+ (+ await db.execute(+ text(+ "SELECT f.key, f.label, f.field_type, f.required, "+ " COALESCE(v.value, '') AS value, "+ " COALESCE(v.updated_by, '') AS updated_by, v.updated_at "+ "FROM aisoc_tenant_custom_fields f "+ "LEFT JOIN aisoc_case_custom_values v "+ " ON v.field_id = f.id AND v.case_id = :case_id AND v.tenant_id = f.tenant_id "+ "WHERE f.tenant_id = :tenant_id AND f.active "+ "ORDER BY f.position, f.key"+ ).bindparams(case_id=case_id, tenant_id=current_user.tenant_id)+ )+ )+ .mappings()+ .all()+ )+ return [+ CustomValueOut(+ key=row["key"],+ label=row["label"],+ field_type=row["field_type"],+ value=row["value"],+ required=row["required"],+ updated_by=row["updated_by"],+ updated_at=row["updated_at"],+ )+ for row in rows+ ]++[email protected]("/cases/{case_id}/custom-values", response_model=list[CustomValueOut])+async def set_custom_values(+ case_id: uuid.UUID,+ body: CustomValuesIn,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("cases:write"))],+) -> list[CustomValueOut]:+ case_exists = (+ await db.execute(+ text("SELECT 1 FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ id=case_id, tenant_id=current_user.tenant_id+ )+ )+ ).scalar_one_or_none()+ if case_exists is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such case")++ fields = {+ row["key"]: row+ for row in (+ await db.execute(+ text("SELECT * FROM aisoc_tenant_custom_fields WHERE tenant_id = :tenant_id AND active").bindparams(+ tenant_id=current_user.tenant_id+ )+ )+ )+ .mappings()+ .all()+ }+ unknown = sorted(set(body.values) - set(fields))+ if unknown:+ # An unvalidated value under an unknown key is precisely the+ # JSONB-blob failure the two-table schema exists to avoid.+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"no such custom field(s): {unknown}. Define them first at POST /case-depth/custom-fields.",+ )++ actor = current_user.api_key_prefix or current_user.email+ try:+ canonical = {key: validate_custom_value(dict(fields[key]), raw) for key, raw in body.values.items()}+ except CaseDepthError as exc:+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc++ for key, value in canonical.items():+ await db.execute(+ text(+ "INSERT INTO aisoc_case_custom_values (tenant_id, case_id, field_id, value, updated_by, updated_at) "+ "VALUES (:tenant_id, :case_id, :field_id, :value, :actor, NOW()) "+ "ON CONFLICT (case_id, field_id) DO UPDATE SET "+ " value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, updated_at = EXCLUDED.updated_at"+ ).bindparams(+ tenant_id=current_user.tenant_id,+ case_id=case_id,+ field_id=fields[key]["id"],+ value=value,+ actor=actor,+ )+ )++ 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="case_custom_values:set",+ resource="case",+ resource_id=str(case_id),+ changes={"keys": sorted(canonical)},+ request=request,+ )+ await db.commit()+ return await get_custom_values(case_id, db, current_user, None) # type: ignore[arg-type]+++# ---------------------------------------------------------------------------+# Workload+# ---------------------------------------------------------------------------++[email protected]("/workload")+async def workload(+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("cases:read"))],+ days: int = Query(default=30, ge=1, le=365),+) -> dict[str, Any]:+ """Per-analyst open, closed, overdue and mean time to close.++ Every number is counted by this request over rows it selected. An analyst+ who has closed nothing gets ``mean_hours_to_close: null`` and the console+ renders that as "no data" — never ``0.0``, which reads as "instant".+ """+ since = datetime.now(UTC) - timedelta(days=days)+ return await analyst_workload(db, tenant_id=current_user.tenant_id, since=since)+++#: Exported so a test can assert the route module and the service agree about+#: what a bulk triage may do, rather than each carrying its own list.+ALLOWED_BULK_STATUSES = BULK_TRIAGE_STATUSES+ALLOWED_SEVERITIES = SEVERITIESdiff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex b1a0c26c3..9bbf001cc 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -20,6 +20,7 @@ from app.api.v1.endpoints import (autonomy_policy,branding,business_context,+ case_depth,cases,community,compliance,@@ -118,6 +119,12 @@ api_router.include_router(alert_explain.router)# Dry-run by default; AISOC_SIEM_WRITEBACK_EXECUTE opts in to the vendor call.api_router.include_router(alert_writeback.router)api_router.include_router(cases.router)+# Depth 9.3 (parity 5.6 remainder): alert and case merge, bulk triage,+# tenant custom fields and per-analyst workload. Its own prefix rather+# than hanging off /alerts and /cases, because a path parameter compiles+# to `[^/]+` and `/alerts/merge` beside `/alerts/{alert_id}` is the exact+# shape that had `GET /{hunt_id}` swallowing its sibling `/runs`.+api_router.include_router(case_depth.router)# Attack-chain timeline (T3.3 — v8.0 parallel team plan).# Backs the attack-chain view in apps/web/src/components/cases/CaseWorkspace.tsx with a# ranked timeline (graph-distance + temporal proximity + risk overlap)diff --git a/services/api/app/services/case_depth.py b/services/api/app/services/case_depth.pynew file mode 100644index 000000000..fb91e5f47--- /dev/null+++ b/services/api/app/services/case_depth.py@@ -0,0 +1,543 @@+"""Alert and case merge, bulk triage, tenant custom fields, analyst workload.++Depth plan 9.3 — the open half of parity 5.6.++Four capabilities, one module, because they share the same two tables and the+same rule: **nothing here deletes anything.** A merged alert keeps its row+and gains a pointer; a merged case keeps its row, its audit chain, its+custody entries and whatever vendor ticket already names its id; a retired+custom field keeps the values written against it.++What already existed, so that "new" means something+---------------------------------------------------+``alerts.is_merged``, ``alerts.parent_alert_id`` and+``alerts.child_alert_ids`` have been in the schema since migration 001 and+had **no writer anywhere** — the only mention outside the ORM model was the+ORM model. The alert half of merge therefore needed no schema change, only+this. That is the repository's most common defect and it is worth naming+rather than quietly filling in.++``POST /alerts/bulk-close`` existed and is good: a preflight count, a+snapshot table, one audit row for the batch. It closes, and closing is one+triage decision out of several — an analyst clearing a morning queue also+assigns, re-severities and moves things to in-progress. :func:`bulk_triage`+is the rest of that verb set, and it deliberately reuses bulk-close's two+safety properties (a count the caller must acknowledge, one audit row for+the batch) rather than inventing weaker ones.++Workload is counted, not estimated+----------------------------------+:func:`analyst_workload` returns, per analyst, counts this query computed+over rows it selected — never a stored aggregate. Every mean travels with+the number of rows it averaged, and an analyst with no closed cases gets+``None`` for their mean time to close rather than ``0.0``. A zero there+reads as "instant", which is the opposite of "no data", and that exact+confusion is why two console figures were wrong for months.+"""++from __future__ import annotations++import uuid+from dataclasses import dataclass+from datetime import UTC, datetime+from typing import Any++from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession++#: Alert statuses a bulk triage may move rows *to*. ``closed`` is absent on+#: purpose: it already has a route with a snapshot table and a restore+#: target, and a second path to the same destination with weaker guarantees+#: is how one of the two quietly becomes the one everybody uses.+BULK_TRIAGE_STATUSES: frozenset[str] = frozenset({"new", "open", "in_progress", "resolved", "dismissed"})++#: Severities a bulk triage may set.+SEVERITIES: tuple[str, ...] = ("info", "low", "medium", "high", "critical")++#: Custom field types, mirroring the CHECK in migration 106. One validator+#: and one input control each.+FIELD_TYPES: tuple[str, ...] = ("text", "number", "boolean", "date", "select")+++class CaseDepthError(ValueError):+ """A refusal the caller can act on. Routes render it as 4xx with the text."""+++# ---------------------------------------------------------------------------+# Alert merge+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class MergeResult:+ primary_id: uuid.UUID+ merged_ids: list[uuid.UUID]+ case_id: uuid.UUID | None+++async def merge_alerts(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ primary_id: uuid.UUID,+ duplicate_ids: list[uuid.UUID],+ actor: str,+) -> MergeResult:+ """Fold ``duplicate_ids`` into ``primary_id``. Keeps every row.++ Refusals, each because the alternative loses information silently:++ * a duplicate that is already merged — re-merging would rewrite its+ parent and orphan the chain it is part of;+ * the primary being itself a duplicate — that makes a cycle, and a+ console walking ``parent_alert_id`` would not terminate;+ * an id belonging to another tenant, which simply does not resolve here+ because every statement is tenant-predicated.++ The surviving alert inherits the duplicates' ``case_id`` when it has+ none, so merging two alerts one of which is already on a case leaves the+ survivor on that case rather than detached — which is what the phase's+ "two alerts merge into one case with their history kept" asks for.+ """+ unique = [i for i in dict.fromkeys(duplicate_ids) if i != primary_id]+ if not unique:+ raise CaseDepthError("Nothing to merge: the duplicate list is empty once the primary is removed from it.")++ rows = (+ (+ await db.execute(+ text(+ "SELECT id, is_merged, parent_alert_id, case_id FROM alerts "+ "WHERE tenant_id = :tenant_id AND id = ANY(CAST(:ids AS uuid[]))"+ ).bindparams(tenant_id=tenant_id, ids=[str(i) for i in [primary_id, *unique]])+ )+ )+ .mappings()+ .all()+ )+ found = {row["id"]: row for row in rows}++ missing = [str(i) for i in [primary_id, *unique] if i not in found]+ if missing:+ raise CaseDepthError(f"No such alert(s) in this tenant: {', '.join(missing)}")+ if found[primary_id]["is_merged"]:+ raise CaseDepthError(+ f"{primary_id} is itself merged into {found[primary_id]['parent_alert_id']}. "+ "Merge into the surviving alert instead, or a walk of the chain would not terminate."+ )+ already = [str(i) for i in unique if found[i]["is_merged"]]+ if already:+ raise CaseDepthError(+ f"Already merged: {', '.join(already)}. Re-merging would rewrite the parent and orphan the chain those alerts are part of."+ )++ now = datetime.now(UTC)+ await db.execute(+ text(+ "UPDATE alerts SET is_merged = TRUE, parent_alert_id = :primary, "+ "status = CASE WHEN status IN ('closed', 'dismissed') THEN status ELSE 'dismissed' END, "+ "updated_at = :now "+ "WHERE tenant_id = :tenant_id AND id = ANY(CAST(:ids AS uuid[]))"+ ).bindparams(primary=primary_id, now=now, tenant_id=tenant_id, ids=[str(i) for i in unique])+ )++ # `child_alert_ids` is appended to rather than replaced: a second merge+ # into the same primary must not drop the first merge's children.+ await db.execute(+ text(+ "UPDATE alerts SET child_alert_ids = ("+ " SELECT CAST(jsonb_agg(DISTINCT e) AS jsonb) FROM ("+ " SELECT jsonb_array_elements_text(child_alert_ids) AS e"+ " UNION SELECT unnest(CAST(:ids AS text[]))"+ " ) AS merged"+ "), updated_at = :now "+ "WHERE tenant_id = :tenant_id AND id = :primary"+ ).bindparams(ids=[str(i) for i in unique], now=now, tenant_id=tenant_id, primary=primary_id)+ )++ case_id = found[primary_id]["case_id"]+ if case_id is None:+ inherited = next((found[i]["case_id"] for i in unique if found[i]["case_id"] is not None), None)+ if inherited is not None:+ await db.execute(+ text("UPDATE alerts SET case_id = :case_id, updated_at = :now WHERE tenant_id = :tenant_id AND id = :primary").bindparams(+ case_id=inherited, now=now, tenant_id=tenant_id, primary=primary_id+ )+ )+ case_id = inherited++ del actor # recorded by the caller's audit row, which owns the request context+ return MergeResult(primary_id=primary_id, merged_ids=list(unique), case_id=case_id)+++# ---------------------------------------------------------------------------+# Case merge+# ---------------------------------------------------------------------------+++async def merge_cases(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ primary_id: uuid.UUID,+ duplicate_ids: list[uuid.UUID],+ actor: str,+ reason: str,+) -> MergeResult:+ """Fold cases into one. Alerts follow; both rows survive.++ The absorbed case keeps its row, its audit chain, its custody entries and+ any vendor ticket that already names its id. Its alerts are repointed at+ the survivor, and its ``alert_ids`` array is unioned into the survivor's+ so a reader of either column sees the same set.+ """+ unique = [i for i in dict.fromkeys(duplicate_ids) if i != primary_id]+ if not unique:+ raise CaseDepthError("Nothing to merge: the duplicate list is empty once the primary is removed from it.")++ rows = (+ (+ await db.execute(+ text(+ "SELECT id, status, merged_into_id FROM aisoc_cases WHERE tenant_id = :tenant_id AND id = ANY(CAST(:ids AS uuid[]))"+ ).bindparams(tenant_id=tenant_id, ids=[str(i) for i in [primary_id, *unique]])+ )+ )+ .mappings()+ .all()+ )+ found = {row["id"]: row for row in rows}++ missing = [str(i) for i in [primary_id, *unique] if i not in found]+ if missing:+ raise CaseDepthError(f"No such case(s) in this tenant: {', '.join(missing)}")+ if found[primary_id]["merged_into_id"] is not None:+ raise CaseDepthError(+ f"{primary_id} was itself merged into {found[primary_id]['merged_into_id']}. Merge into the surviving case instead."+ )+ already = [str(i) for i in unique if found[i]["merged_into_id"] is not None]+ if already:+ raise CaseDepthError(f"Already merged: {', '.join(already)}.")++ now = datetime.now(UTC)+ ids = [str(i) for i in unique]++ # Alerts follow the merge. Done before the case rows change so a failure+ # leaves the alerts pointing at a case that is still open rather than at+ # one already marked merged.+ await db.execute(+ text(+ "UPDATE alerts SET case_id = :primary, updated_at = :now WHERE tenant_id = :tenant_id AND case_id = ANY(CAST(:ids AS uuid[]))"+ ).bindparams(primary=primary_id, now=now, tenant_id=tenant_id, ids=ids)+ )++ # `aisoc_cases.alert_ids` is `uuid[]`, not JSONB -- unlike `ioc_ids` and+ # `artifact_ids` beside it, and unlike `alerts.child_alert_ids` above.+ # The first version of this statement assumed JSONB and raised+ # `jsonb_array_elements_text(uuid[]) does not exist` against the real+ # schema. A SQLite stand-in would have accepted either and shipped it.+ await db.execute(+ text(+ "UPDATE aisoc_cases SET alert_ids = ("+ " SELECT COALESCE(array_agg(DISTINCT e), '{}'::uuid[]) FROM ("+ " SELECT unnest(p.alert_ids) AS e FROM aisoc_cases p"+ " WHERE p.id = :primary AND p.tenant_id = :tenant_id"+ " UNION"+ " SELECT unnest(d.alert_ids) AS e FROM aisoc_cases d"+ " WHERE d.tenant_id = :tenant_id AND d.id = ANY(CAST(:ids AS uuid[]))"+ " ) AS combined"+ "), updated_at = :now "+ "WHERE tenant_id = :tenant_id AND id = :primary"+ ).bindparams(primary=primary_id, tenant_id=tenant_id, ids=ids, now=now)+ )++ await db.execute(+ text(+ "UPDATE aisoc_cases SET merged_into_id = :primary, merged_at = :now, merged_by = :actor, "+ "status = 'closed', closed_at = COALESCE(closed_at, :now), "+ "resolution = COALESCE(NULLIF(resolution, ''), :reason), updated_at = :now "+ "WHERE tenant_id = :tenant_id AND id = ANY(CAST(:ids AS uuid[]))"+ ).bindparams(+ primary=primary_id,+ now=now,+ actor=actor,+ reason=reason or f"merged into {primary_id}",+ tenant_id=tenant_id,+ ids=ids,+ )+ )++ return MergeResult(primary_id=primary_id, merged_ids=list(unique), case_id=primary_id)+++# ---------------------------------------------------------------------------+# Bulk triage+# ---------------------------------------------------------------------------+++#: One static statement rather than a SET list assembled in Python.+#:+#: The assembled form was correct — every fragment came from a literal in+#: this module and nothing from a caller — and it still read as dynamic SQL+#: to every scanner that looks at it, which is a cost paid forever by every+#: reviewer. `COALESCE(:p, column)` says "leave it alone when the parameter+#: is NULL" in the database instead, and the assignment pair needs a CASE+#: because "set it to NULL" and "do not touch it" are different intentions+#: that COALESCE alone cannot tell apart.+#:+#: Every parameter carries an explicit cast: inside a COALESCE or a CASE a+#: bare parameter has no inferable type and asyncpg refuses the whole+#: statement with `could not determine data type of parameter $n`.+_BULK_TRIAGE_SQL = """+UPDATE alerts SET+ status = COALESCE(CAST(:status AS text), status),+ severity = COALESCE(CAST(:severity AS text), severity),+ assigned_to_id = CASE+ WHEN CAST(:unassign AS boolean) THEN NULL+ WHEN CAST(:assignee AS uuid) IS NOT NULL THEN CAST(:assignee AS uuid)+ ELSE assigned_to_id+ END,+ assigned_at = CASE+ WHEN CAST(:unassign AS boolean) THEN NULL+ WHEN CAST(:assignee AS uuid) IS NOT NULL THEN :now+ ELSE assigned_at+ END,+ updated_at = :now+WHERE tenant_id = :tenant_id AND id = ANY(CAST(:ids AS uuid[]))+"""+++@dataclass(frozen=True)+class BulkTriageResult:+ matched_count: int+ updated_count: int+ changes: dict[str, Any]+++async def bulk_triage(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ alert_ids: list[uuid.UUID],+ set_status: str | None,+ set_severity: str | None,+ assign_to: uuid.UUID | None,+ unassign: bool,+ max_count: int,+) -> BulkTriageResult:+ """Apply one triage decision to many alerts.++ Two safety properties, taken from ``bulk_close_alerts`` rather than+ reinvented, because a second bulk path with weaker guarantees is how the+ weaker one becomes the one everybody uses:++ * the caller states ``max_count`` and a larger match is **refused** with+ the real count, so the first call is a free dry run;+ * the caller's audit row covers the batch, written by the route.++ ``closed`` is deliberately not reachable here: it has its own route with+ a snapshot table and a named restore target.+ """+ if set_status is None and set_severity is None and assign_to is None and not unassign:+ raise CaseDepthError("Nothing to do: name at least one of status, severity, assign_to or unassign.")+ if set_status is not None and set_status not in BULK_TRIAGE_STATUSES:+ raise CaseDepthError(+ f"status must be one of {sorted(BULK_TRIAGE_STATUSES)}. "+ "Closing in bulk is POST /alerts/bulk-close, which snapshots every row first."+ )+ if set_severity is not None and set_severity not in SEVERITIES:+ raise CaseDepthError(f"severity must be one of {list(SEVERITIES)}")+ if assign_to is not None and unassign:+ raise CaseDepthError("assign_to and unassign contradict each other.")++ unique = list(dict.fromkeys(alert_ids))+ if not unique:+ raise CaseDepthError("No alert ids supplied.")++ matched = (+ await db.execute(+ text("SELECT count(*) AS n FROM alerts WHERE tenant_id = :tenant_id AND id = ANY(CAST(:ids AS uuid[]))").bindparams(+ tenant_id=tenant_id, ids=[str(i) for i in unique]+ )+ )+ ).scalar_one()++ if matched > max_count:+ # Nothing written. The caller raises max_count past the real figure+ # to execute, which makes the first call a dry run they did not have+ # to ask for.+ raise CaseDepthError(+ f"{matched} alert(s) match and max_count is {max_count}. Nothing was changed. "+ f"Re-send with max_count at least {matched} to apply."+ )++ now = datetime.now(UTC)+ changes: dict[str, Any] = {}+ if set_status is not None:+ changes["status"] = set_status+ if set_severity is not None:+ changes["severity"] = set_severity+ if assign_to is not None:+ changes["assigned_to_id"] = str(assign_to)+ if unassign:+ changes["assigned_to_id"] = None++ result = await db.execute(+ text(_BULK_TRIAGE_SQL).bindparams(+ status=set_status,+ severity=set_severity,+ assignee=str(assign_to) if assign_to is not None else None,+ unassign=unassign,+ now=now,+ tenant_id=tenant_id,+ ids=[str(i) for i in unique],+ )+ )+ return BulkTriageResult(matched_count=int(matched), updated_count=int(result.rowcount or 0), changes=changes)+++# ---------------------------------------------------------------------------+# Tenant custom fields+# ---------------------------------------------------------------------------+++def validate_custom_value(field: dict[str, Any], raw: str) -> str:+ """Canonicalise a value against its definition, or refuse with the reason.++ Canonicalising on write is what makes one TEXT column safe: a reader that+ ignores the definition gets a string rather than a wrong number, and a+ date is always ISO-8601 whatever the analyst typed.+ """+ field_type = field["field_type"]+ value = (raw or "").strip()+ if value == "":+ if field["required"]:+ raise CaseDepthError(f"{field['key']} is required.")+ return ""+ if field_type == "number":+ try:+ float(value)+ except ValueError as exc:+ raise CaseDepthError(f"{field['key']} must be a number, got {value!r}.") from exc+ return value+ if field_type == "boolean":+ lowered = value.lower()+ if lowered in ("true", "1", "yes"):+ return "true"+ if lowered in ("false", "0", "no"):+ return "false"+ raise CaseDepthError(f"{field['key']} must be true or false, got {value!r}.")+ if field_type == "date":+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError as exc:+ raise CaseDepthError(f"{field['key']} must be an ISO-8601 date, got {value!r}.") from exc+ return parsed.isoformat()+ if field_type == "select":+ if value not in (field["choices"] or []):+ raise CaseDepthError(f"{field['key']} must be one of {list(field['choices'] or [])}, got {value!r}.")+ return value+ return value+++# ---------------------------------------------------------------------------+# Per-analyst workload+# ---------------------------------------------------------------------------++#: One statement, so the open counts and the throughput counts cannot drift+#: apart by being computed in two places over two windows -- which is exactly+#: how `cases_closed_7d` and `mttr_hours` came to disagree about the same+#: rows. `assignee` is the column `aisoc_cases` actually carries for a human;+#: `assigned_to_id` exists beside it and is written by the orchestration+#: path, so both are coalesced into one identity.+_WORKLOAD_SQL = """+WITH scoped AS (+ SELECT+ COALESCE(NULLIF(assignee, ''), assigned_to_id::text) AS analyst,+ status,+ severity,+ created_at,+ closed_at,+ sla_due_at,+ merged_into_id+ FROM aisoc_cases+ WHERE tenant_id = :tenant_id+ AND created_at >= :since+ -- A case absorbed by a merge is not work anybody still has to do, and+ -- counting it would make a merge look like it created throughput.+ AND merged_into_id IS NULL+)+SELECT+ analyst,+ count(*) AS total,+ count(*) FILTER (WHERE status NOT IN ('closed', 'cancelled')) AS open_cases,+ count(*) FILTER (WHERE status = 'closed') AS closed_cases,+ count(*) FILTER (WHERE status NOT IN ('closed', 'cancelled')+ AND severity IN ('high', 'critical')) AS open_high,+ count(*) FILTER (WHERE status NOT IN ('closed', 'cancelled')+ AND sla_due_at IS NOT NULL+ AND sla_due_at < :now) AS overdue,+ -- The mean travels with the count of rows it averaged, which is the+ -- `closed_cases` column above. NULL when nothing closed; the caller+ -- renders that as "no data", never as 0.0.+ avg(EXTRACT(EPOCH FROM (closed_at - created_at)) / 3600.0)+ FILTER (WHERE status = 'closed' AND closed_at IS NOT NULL) AS mean_hours_to_close+FROM scoped+WHERE analyst IS NOT NULL+GROUP BY analyst+ORDER BY open_cases DESC, analyst+"""++#: Unassigned work is a real queue and the thing a lead looks at first, but+#: it is not an analyst, so it is counted separately rather than appearing as+#: a row named "null".+_UNASSIGNED_SQL = """+SELECT+ count(*) FILTER (WHERE status NOT IN ('closed', 'cancelled')) AS open_cases,+ count(*) FILTER (WHERE status NOT IN ('closed', 'cancelled')+ AND severity IN ('high', 'critical')) AS open_high+FROM aisoc_cases+WHERE tenant_id = :tenant_id+ AND created_at >= :since+ AND merged_into_id IS NULL+ AND COALESCE(NULLIF(assignee, ''), assigned_to_id::text) IS NULL+"""+++async def analyst_workload(db: AsyncSession, *, tenant_id: uuid.UUID, since: datetime) -> dict[str, Any]:+ """Per-analyst open, closed, overdue and mean-time-to-close, counted now.++ Nothing here reads a stored aggregate. Every number is computed from the+ rows this query selected, and ``mean_hours_to_close`` is ``None`` for an+ analyst who has closed nothing — a zero there reads as "instant", which+ is the opposite of "no data" and is the exact confusion that left two+ console figures wrong for months.+ """+ now = datetime.now(UTC)+ rows = (await db.execute(text(_WORKLOAD_SQL).bindparams(tenant_id=tenant_id, since=since, now=now))).mappings().all()+ unassigned = (await db.execute(text(_UNASSIGNED_SQL).bindparams(tenant_id=tenant_id, since=since))).mappings().one()++ analysts = [+ {+ "analyst": row["analyst"],+ "total": int(row["total"]),+ "open_cases": int(row["open_cases"]),+ "closed_cases": int(row["closed_cases"]),+ "open_high_or_critical": int(row["open_high"]),+ "overdue": int(row["overdue"]),+ "mean_hours_to_close": float(row["mean_hours_to_close"]) if row["mean_hours_to_close"] is not None else None,+ # The denominator travels with the mean. A mean over three cases+ # and a mean over three hundred are different claims.+ "mean_over_cases": int(row["closed_cases"]),+ }+ for row in rows+ ]+ return {+ "since": since.isoformat(),+ "computed_at": now.isoformat(),+ "analysts": analysts,+ "unassigned": {+ "open_cases": int(unassigned["open_cases"] or 0),+ "open_high_or_critical": int(unassigned["open_high"] or 0),+ },+ }diff --git a/services/api/migrations/106_case_depth.sql b/services/api/migrations/106_case_depth.sqlnew file mode 100644index 000000000..b3aed67e9--- /dev/null+++ b/services/api/migrations/106_case_depth.sql@@ -0,0 +1,169 @@+-- 106_case_depth.sql — case merge, tenant custom fields, and the columns a+-- merge needs to keep history.+--+-- Depth plan 9.3 (parity 5.6 remainder).+--+-- What was already there and what was not+-- ---------------------------------------+-- `alerts` has carried `is_merged`, `parent_alert_id` and `child_alert_ids`+-- since migration 001 and **nothing has ever written any of them** — the+-- parity plan says so and a grep across `services/api/app` confirms it: the+-- only mention outside the ORM model is the ORM model. So the alert half of+-- merge needs no schema change at all, only a writer. That is the recurring+-- defect in this tree and it is worth being explicit that this migration is+-- deliberately *not* adding what already exists.+--+-- `aisoc_cases` has no merge columns, so the case half does need them.+--+-- Why a merge keeps both rows+-- ---------------------------+-- The absorbed case is not deleted. `merged_into_id` points at the survivor+-- and the status moves to `closed` with a reason. Deleting would lose the+-- audit chain, the evidence custody entries and the external references+-- (`case_external_refs`) that a vendor system already holds a ticket id for+-- — and a ticket pointing at a case id that no longer resolves is worse for+-- the analyst than one pointing at a case marked merged.+--+-- `merged_at` and `merged_by` are separate from `closed_at`/`updated_at` for+-- the reason the console-number work found the hard way: a timestamp that+-- moves whenever anybody edits the row cannot answer "when was this merged".+--+-- Tenant custom fields: two tables, because they answer different questions+-- ------------------------------------------------------------------------+-- `aisoc_tenant_custom_fields` is the tenant's schema — what fields exist,+-- what type each is, whether it is required, and what the permitted choices+-- are for a select. `aisoc_case_custom_values` is the data.+--+-- The obvious alternative is one JSONB column on `aisoc_cases`. It is wrong+-- here for a specific reason rather than on principle: a definition nobody+-- can enumerate cannot be rendered as a form, cannot be validated at write+-- time, and cannot be removed cleanly — "which cases still carry the field+-- we retired" is a question a JSONB blob answers only by scanning every row+-- and guessing at key spellings. A tenant that renames a field in a blob has+-- silently created a second field.+--+-- `field_type` is a closed set because each value maps to exactly one+-- validator and one input control. An open type is one the console cannot+-- render and the API cannot check.+--+-- Reversible: DROP TABLE IF EXISTS the two tables (values first), then the+-- three ALTER TABLE ... DROP COLUMN on aisoc_cases.++-- ── Case merge ─────────────────────────────────────────────────────────────++ALTER TABLE aisoc_cases ADD COLUMN IF NOT EXISTS merged_into_id UUID+ REFERENCES aisoc_cases(id) ON DELETE SET NULL;+ALTER TABLE aisoc_cases ADD COLUMN IF NOT EXISTS merged_at TIMESTAMPTZ;+ALTER TABLE aisoc_cases ADD COLUMN IF NOT EXISTS merged_by TEXT;++-- "What was folded into this case" — the query the case view runs. Partial,+-- because the overwhelming majority of cases were never merged into+-- anything and an index over those rows is dead weight.+CREATE INDEX IF NOT EXISTS aisoc_cases_merged_into_idx+ ON aisoc_cases (merged_into_id)+ WHERE merged_into_id IS NOT NULL;++COMMENT ON COLUMN aisoc_cases.merged_into_id IS+ 'The surviving case this one was folded into. The absorbed row is kept, not deleted: '+ 'deleting loses the audit chain, the custody entries and any vendor ticket that already '+ 'points at this id.';++-- ── Tenant custom fields ───────────────────────────────────────────────────++CREATE TABLE IF NOT EXISTS aisoc_tenant_custom_fields (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,++ -- Stable machine name. Immutable by convention: renaming is a new field+ -- plus a migration of the values, because a rename in place silently+ -- changes the meaning of every historical value.+ key TEXT NOT NULL,+ label TEXT NOT NULL,+ help_text TEXT NOT NULL DEFAULT '',++ -- Closed set: each value maps to exactly one validator and one input+ -- control. An open type is one the console cannot render and the API+ -- cannot check.+ field_type TEXT NOT NULL+ CHECK (field_type IN ('text', 'number', 'boolean', 'date', 'select')),+ -- Permitted values for `select`. Empty for every other type, and the+ -- service refuses a select with none rather than storing a field whose+ -- form has no options.+ choices TEXT[] NOT NULL DEFAULT '{}',++ required BOOLEAN NOT NULL DEFAULT FALSE,+ -- Where it appears in the form. Ties broken by `key` so the order is+ -- total and a render is reproducible.+ position INTEGER NOT NULL DEFAULT 0,++ -- Retired rather than deleted, for the same reason a merged case is:+ -- values already written against it stay readable and attributable.+ active BOOLEAN NOT NULL DEFAULT TRUE,++ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT aisoc_tenant_custom_fields_key_unique UNIQUE (tenant_id, key),+ -- A select with no choices renders an empty dropdown an analyst cannot+ -- satisfy, which for a required field makes the case unsaveable.+ CONSTRAINT aisoc_tenant_custom_fields_select_has_choices+ CHECK (field_type <> 'select' OR cardinality(choices) > 0)+);++CREATE INDEX IF NOT EXISTS aisoc_tenant_custom_fields_tenant_idx+ ON aisoc_tenant_custom_fields (tenant_id, position, key)+ WHERE active;++CREATE TABLE IF NOT EXISTS aisoc_case_custom_values (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ case_id UUID NOT NULL REFERENCES aisoc_cases(id) ON DELETE CASCADE,+ field_id UUID NOT NULL REFERENCES aisoc_tenant_custom_fields(id) ON DELETE CASCADE,++ -- One text column rather than one per type. The definition says how to+ -- read it, the service validates and canonicalises on write (ISO-8601+ -- for a date, "true"/"false" for a boolean), and a reader that ignores+ -- the definition gets a string rather than a wrong number.+ value TEXT NOT NULL DEFAULT '',++ updated_by TEXT NOT NULL DEFAULT '',+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT aisoc_case_custom_values_unique UNIQUE (case_id, field_id)+);++CREATE INDEX IF NOT EXISTS aisoc_case_custom_values_case_idx+ ON aisoc_case_custom_values (case_id);++COMMENT ON TABLE aisoc_tenant_custom_fields IS+ 'A tenant''s own case schema. Separate from the values so a field can be enumerated, '+ 'rendered as a form, validated at write time and retired cleanly -- none of which a '+ 'JSONB blob on aisoc_cases supports.';++-- Written out per table rather than looped with format(): a loop makes the+-- policy invisible to grep and to scripts/check_tenant_query_predicates.py,+-- which reads migrations to learn which tables carry one.+DO $$+BEGIN+ EXECUTE 'ALTER TABLE aisoc_tenant_custom_fields ENABLE ROW LEVEL SECURITY';+ EXECUTE 'ALTER TABLE aisoc_tenant_custom_fields FORCE ROW LEVEL SECURITY';+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON aisoc_tenant_custom_fields';+ EXECUTE+ 'CREATE POLICY tenant_isolation ON aisoc_tenant_custom_fields '+ 'USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '+ 'WITH CHECK (tenant_id = current_tenant_id())';++ EXECUTE 'ALTER TABLE aisoc_case_custom_values ENABLE ROW LEVEL SECURITY';+ EXECUTE 'ALTER TABLE aisoc_case_custom_values FORCE ROW LEVEL SECURITY';+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON aisoc_case_custom_values';+ EXECUTE+ 'CREATE POLICY tenant_isolation ON aisoc_case_custom_values '+ '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_tenant_custom_fields TO aisoc_app';+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_case_custom_values TO aisoc_app';+ END IF;+END+$$;diff --git a/services/api/tests/test_case_depth.py b/services/api/tests/test_case_depth.pynew file mode 100644index 000000000..ca73efd7d--- /dev/null+++ b/services/api/tests/test_case_depth.py@@ -0,0 +1,582 @@+"""Case depth: merge keeps history, bulk triage has a preflight, fields validate.++Depth plan 9.3 (parity 5.6 remainder).++Two halves, and the split is deliberate rather than a convenience.++**Always run.** The validators and the refusals that happen before any SQL.+Those are pure functions and a database would prove nothing about them.++**Live PostgreSQL.** Everything else, through the shipped ASGI app with its+real auth dependencies. The statements here are Postgres-only by necessity —+``uuid[]`` parameters, ``jsonb_agg(DISTINCT …)``, ``count(*) FILTER``,+``EXTRACT(EPOCH FROM …)`` — so a SQLite stand-in would be a different query+than the one that runs in production, which is the "test double more capable+than the real thing" failure this repository keeps finding. Gated on the DSN+being present *and* something answering on it, with+``CASE_DEPTH_PROOF_REQUIRED`` turning the skip into a failure for the job+that is meant to run it.++Asserted by name below:++* a merge keeps every row and leaves a walkable chain;+* a merged alert cannot be re-merged, and a merge into a merged alert is+ refused — both would orphan or cycle the chain;+* merging alerts leaves the survivor on the case one of them was already on,+ which is the phase's "two alerts merge into one case with their history+ kept";+* merging cases repoints the alerts and keeps both case rows;+* bulk triage refuses a match larger than ``max_count`` **and writes+ nothing**;+* ``closed`` is unreachable through bulk triage, because the route that+ snapshots every row first owns that destination;+* workload counts what this query selected, and a mean over nothing is+ ``None`` rather than ``0.0``.+"""++from __future__ import annotations++import os+import socket+import uuid+from datetime import UTC, datetime, timedelta+from typing import Any+from urllib.parse import urlparse++import pytest+import pytest_asyncio+from app.services.case_depth import CaseDepthError, validate_custom_value+from httpx import ASGITransport, AsyncClient+from sqlalchemy import text+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++_DSN = os.environ.get("DATABASE_MIGRATION_URL", "").strip() or os.environ.get("DATABASE_URL", "")+_REQUIRED = os.environ.get("CASE_DEPTH_PROOF_REQUIRED", "").strip() not in ("", "0", "false")++_UNUSABLE_PASSWORD_HASH = "x" # noqa: S105 - not a credential; no plaintext maps to it+++def _postgres_is_listening() -> bool:+ """A DSN is a statement of intent, not a running server.++ The unit-test job exports a ``postgres://…localhost:5432`` URL with+ nothing behind it, so a string check alone decides these should run and+ they die on ``Connect call failed`` rather than skipping.+ """+ parsed = urlparse(_DSN.replace("postgresql+asyncpg://", "postgresql://"))+ if not parsed.hostname:+ return False+ try:+ with socket.create_connection((parsed.hostname, parsed.port or 5432), timeout=2):+ return True+ except OSError:+ return False+++_LIVE = ("postgres" in _DSN and _postgres_is_listening()) or _REQUIRED++live_only = pytest.mark.skipif(+ not _LIVE,+ reason=(+ "needs a live PostgreSQL with the migration chain applied — uuid[] parameters, "+ "jsonb_agg(DISTINCT …), count(*) FILTER and EXTRACT(EPOCH …) have no SQLite "+ "equivalent, and a stand-in would be a different query than the one that ships"+ ),+)+++# ---------------------------------------------------------------------------+# Always run: validators and pre-SQL refusals+# ---------------------------------------------------------------------------+++class TestCustomFieldValidation:+ """Canonicalising on write is what makes one TEXT column safe."""++ def test_a_number_field_refuses_prose(self) -> None:+ field = {"key": "ticket_cost", "field_type": "number", "required": False, "choices": []}+ assert validate_custom_value(field, " 42.5 ") == "42.5"+ with pytest.raises(CaseDepthError, match="must be a number"):+ validate_custom_value(field, "about forty")++ def test_a_boolean_canonicalises_rather_than_storing_what_was_typed(self) -> None:+ field = {"key": "reportable", "field_type": "boolean", "required": False, "choices": []}+ assert validate_custom_value(field, "YES") == "true"+ assert validate_custom_value(field, "0") == "false"+ with pytest.raises(CaseDepthError, match="must be true or false"):+ validate_custom_value(field, "maybe")++ def test_a_date_is_stored_iso_whatever_was_typed(self) -> None:+ field = {"key": "notified_on", "field_type": "date", "required": False, "choices": []}+ assert validate_custom_value(field, "2026-03-01T09:00:00Z").startswith("2026-03-01T09:00:00")+ with pytest.raises(CaseDepthError, match="ISO-8601"):+ validate_custom_value(field, "first of March")++ def test_a_select_refuses_a_value_outside_its_choices(self) -> None:+ field = {"key": "business_unit", "field_type": "select", "required": False, "choices": ["payments", "retail"]}+ assert validate_custom_value(field, "payments") == "payments"+ with pytest.raises(CaseDepthError, match="must be one of"):+ validate_custom_value(field, "legal")++ def test_a_required_field_refuses_empty_and_an_optional_one_allows_it(self) -> None:+ required = {"key": "owner", "field_type": "text", "required": True, "choices": []}+ optional = {"key": "notes", "field_type": "text", "required": False, "choices": []}+ with pytest.raises(CaseDepthError, match="is required"):+ validate_custom_value(required, " ")+ assert validate_custom_value(optional, "") == ""+++# ---------------------------------------------------------------------------+# Live PostgreSQL+# ---------------------------------------------------------------------------+++@pytest_asyncio.fixture(autouse=True)+async def _release_the_app_pool():+ """Dispose the application's global pool between tests.++ ``app.db.database.engine`` is module-level and pytest-asyncio gives every+ test its own loop; a connection checked out under the first is unusable+ under the second, and the resulting asyncpg error reads like a defect in+ the code under test.+ """+ yield+ if _LIVE:+ from app.db.database import engine++ await engine.dispose()+++@pytest_asyncio.fixture+async def world():+ """A scratch tenant with an admin, two alerts and two cases, on the real schema."""+ from app.core.security import create_access_token++ engine = create_async_engine(_DSN)+ maker = async_sessionmaker(engine, expire_on_commit=False)++ tenant_id = uuid.uuid4()+ user_id = uuid.uuid4()+ suffix = tenant_id.hex[:8]++ async with maker() as db:+ await db.execute(+ text("INSERT INTO tenants (id, name, slug) VALUES (:i, :n, :s)"),+ {"i": tenant_id, "n": f"case-depth-{suffix}", "s": f"case-depth-{suffix}"},+ )+ await db.execute(+ text(+ "INSERT INTO users (id, tenant_id, email, username, hashed_password, role, is_active, is_verified) "+ "VALUES (:i, :t, :e, :u, :h, 'admin', TRUE, TRUE)"+ ),+ {+ "i": user_id,+ "t": tenant_id,+ "e": f"lead-{suffix}@example.com",+ "u": f"lead-{suffix}",+ "h": _UNUSABLE_PASSWORD_HASH,+ },+ )+ await db.commit()++ token = create_access_token({"sub": str(user_id)})+ yield maker, tenant_id, user_id, token+ await engine.dispose()+++async def _alert(maker, tenant_id: uuid.UUID, *, case_id: uuid.UUID | None = None) -> uuid.UUID:+ alert_id = uuid.uuid4()+ async with maker() as db:+ await db.execute(+ text(+ "INSERT INTO alerts (id, tenant_id, title, severity, status, priority, case_id, created_at, updated_at) "+ "VALUES (:i, :t, 'Repeated sign-in failures', 'high', 'new', 40, :c, NOW(), NOW())"+ ),+ {"i": alert_id, "t": tenant_id, "c": case_id},+ )+ await db.commit()+ return alert_id+++async def _case(+ maker,+ tenant_id: uuid.UUID,+ *,+ assignee: str | None = None,+ status: str = "new",+ created_days_ago: int = 1,+ closed: bool = False,+) -> uuid.UUID:+ case_id = uuid.uuid4()+ created = datetime.now(UTC) - timedelta(days=created_days_ago)+ async with maker() as db:+ await db.execute(+ text(+ "INSERT INTO aisoc_cases (id, tenant_id, title, severity, status, assignee, "+ "created_at, updated_at, closed_at) "+ "VALUES (:i, :t, 'Suspected intrusion', 'high', :s, :a, :created, :created, :closed)"+ ),+ {+ "i": case_id,+ "t": tenant_id,+ "s": status,+ "a": assignee,+ "created": created,+ "closed": (created + timedelta(hours=4)) if closed else None,+ },+ )+ await db.commit()+ return case_id+++async def _post(token: str, path: str, body: dict) -> tuple[int, dict]:+ from app.main import app++ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:+ res = await client.post(path, json=body, headers={"Authorization": f"Bearer {token}"})+ try:+ return res.status_code, res.json()+ except ValueError:+ return res.status_code, {"raw": res.text}+++async def _get(token: str, path: str) -> tuple[int, Any]:+ """``Any`` rather than ``object``: this returns a decoded JSON document,+ which is a list for the list routes and a mapping for the rest, and+ every caller below indexes into it. Typing it ``object`` made eight+ honest assertions type errors."""+ from app.main import app++ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:+ res = await client.get(path, headers={"Authorization": f"Bearer {token}"})+ try:+ return res.status_code, res.json()+ except ValueError:+ return res.status_code, {"raw": res.text}+++@live_only+class TestAlertMerge:+ async def test_a_merge_keeps_every_row_and_leaves_a_walkable_chain(self, world) -> None:+ maker, tenant_id, _user, token = world+ primary = await _alert(maker, tenant_id)+ dup_a = await _alert(maker, tenant_id)+ dup_b = await _alert(maker, tenant_id)++ code, body = await _post(+ token,+ "/api/v1/case-depth/alerts/merge",+ {"primary_id": str(primary), "duplicate_ids": [str(dup_a), str(dup_b)], "reason": "same brute force"},+ )+ assert code == 200, body+ assert sorted(body["merged_ids"]) == sorted([str(dup_a), str(dup_b)])++ async with maker() as db:+ rows = (+ (+ await db.execute(+ text("SELECT id, is_merged, parent_alert_id, child_alert_ids, status FROM alerts WHERE tenant_id = :t ORDER BY id"),+ {"t": tenant_id},+ )+ )+ .mappings()+ .all()+ )+ by_id = {row["id"]: row for row in rows}+ # Nothing was deleted.+ assert len(rows) == 3+ assert by_id[dup_a]["is_merged"] and by_id[dup_a]["parent_alert_id"] == primary+ assert by_id[dup_b]["is_merged"] and by_id[dup_b]["parent_alert_id"] == primary+ assert not by_id[primary]["is_merged"]+ children = by_id[primary]["child_alert_ids"]+ assert set(children) == {str(dup_a), str(dup_b)}++ async def test_a_second_merge_appends_rather_than_replacing_the_children(self, world) -> None:+ maker, tenant_id, _user, token = world+ primary = await _alert(maker, tenant_id)+ first = await _alert(maker, tenant_id)+ second = await _alert(maker, tenant_id)++ await _post(token, "/api/v1/case-depth/alerts/merge", {"primary_id": str(primary), "duplicate_ids": [str(first)]})+ await _post(token, "/api/v1/case-depth/alerts/merge", {"primary_id": str(primary), "duplicate_ids": [str(second)]})++ async with maker() as db:+ children = (await db.execute(text("SELECT child_alert_ids FROM alerts WHERE id = :i"), {"i": primary})).scalar_one()+ # Replacing rather than appending would silently drop the first merge.+ assert set(children) == {str(first), str(second)}++ async def test_re_merging_is_refused_because_it_would_orphan_the_chain(self, world) -> None:+ maker, tenant_id, _user, token = world+ primary = await _alert(maker, tenant_id)+ other = await _alert(maker, tenant_id)+ dup = await _alert(maker, tenant_id)++ await _post(token, "/api/v1/case-depth/alerts/merge", {"primary_id": str(primary), "duplicate_ids": [str(dup)]})+ code, body = await _post(token, "/api/v1/case-depth/alerts/merge", {"primary_id": str(other), "duplicate_ids": [str(dup)]})+ assert code == 422+ assert "Already merged" in body["detail"]++ async def test_merging_into_a_merged_alert_is_refused_because_it_would_cycle(self, world) -> None:+ maker, tenant_id, _user, token = world+ primary = await _alert(maker, tenant_id)+ dup = await _alert(maker, tenant_id)+ third = await _alert(maker, tenant_id)++ await _post(token, "/api/v1/case-depth/alerts/merge", {"primary_id": str(primary), "duplicate_ids": [str(dup)]})+ code, body = await _post(token, "/api/v1/case-depth/alerts/merge", {"primary_id": str(dup), "duplicate_ids": [str(third)]})+ assert code == 422+ assert "itself merged" in body["detail"]++ async def test_two_alerts_merge_into_one_case_with_their_history_kept(self, world) -> None:+ """The phase's own "Done when", literally."""+ maker, tenant_id, _user, token = world+ case_id = await _case(maker, tenant_id)+ on_case = await _alert(maker, tenant_id, case_id=case_id)+ loose = await _alert(maker, tenant_id)++ code, body = await _post(+ token,+ "/api/v1/case-depth/alerts/merge",+ {"primary_id": str(loose), "duplicate_ids": [str(on_case)]},+ )+ assert code == 200, body+ # The survivor inherits the case rather than being left detached.+ assert body["case_id"] == str(case_id)++ async with maker() as db:+ rows = (+ (await db.execute(text("SELECT id, case_id, is_merged FROM alerts WHERE tenant_id = :t"), {"t": tenant_id}))+ .mappings()+ .all()+ )+ by_id = {row["id"]: row for row in rows}+ assert by_id[loose]["case_id"] == case_id+ # And the absorbed alert still exists, still on the case, marked merged.+ assert by_id[on_case]["is_merged"] is True+ assert by_id[on_case]["case_id"] == case_id+++@live_only+class TestCaseMerge:+ async def test_merging_cases_repoints_alerts_and_keeps_both_rows(self, world) -> None:+ maker, tenant_id, _user, token = world+ primary = await _case(maker, tenant_id)+ duplicate = await _case(maker, tenant_id)+ alert_id = await _alert(maker, tenant_id, case_id=duplicate)++ code, body = await _post(+ token,+ "/api/v1/case-depth/cases/merge",+ {"primary_id": str(primary), "duplicate_ids": [str(duplicate)], "reason": "same incident"},+ )+ assert code == 200, body++ async with maker() as db:+ case_rows = (+ (+ await db.execute(+ text("SELECT id, status, merged_into_id, merged_by, resolution FROM aisoc_cases WHERE tenant_id = :t"),+ {"t": tenant_id},+ )+ )+ .mappings()+ .all()+ )+ moved = (await db.execute(text("SELECT case_id FROM alerts WHERE id = :i"), {"i": alert_id})).scalar_one()++ by_id = {row["id"]: row for row in case_rows}+ assert len(case_rows) == 2, "a merge must not delete the absorbed case"+ assert by_id[duplicate]["merged_into_id"] == primary+ assert by_id[duplicate]["status"] == "closed"+ assert by_id[duplicate]["merged_by"]+ assert by_id[primary]["merged_into_id"] is None+ assert moved == primary+++@live_only+class TestBulkTriage:+ async def test_a_larger_match_than_max_count_writes_nothing(self, world) -> None:+ maker, tenant_id, _user, token = world+ ids = [await _alert(maker, tenant_id) for _ in range(3)]++ code, body = await _post(+ token,+ "/api/v1/case-depth/alerts/bulk-triage",+ {"alert_ids": [str(i) for i in ids], "set_status": "in_progress", "max_count": 2},+ )+ assert code == 409+ assert "3 alert(s) match" in body["detail"]++ async with maker() as db:+ statuses = (await db.execute(text("SELECT DISTINCT status FROM alerts WHERE tenant_id = :t"), {"t": tenant_id})).scalars().all()+ # The point of the preflight: nothing moved.+ assert set(statuses) == {"new"}++ async def test_raising_max_count_applies_it(self, world) -> None:+ maker, tenant_id, _user, token = world+ ids = [await _alert(maker, tenant_id) for _ in range(3)]++ code, body = await _post(+ token,+ "/api/v1/case-depth/alerts/bulk-triage",+ {"alert_ids": [str(i) for i in ids], "set_status": "in_progress", "set_severity": "low", "max_count": 3},+ )+ assert code == 200, body+ assert body["updated_count"] == 3++ async with maker() as db:+ rows = (await db.execute(text("SELECT status, severity FROM alerts WHERE tenant_id = :t"), {"t": tenant_id})).mappings().all()+ assert {(r["status"], r["severity"]) for r in rows} == {("in_progress", "low")}++ async def test_closed_is_not_reachable_here(self, world) -> None:+ """`bulk-close` snapshots every row first; a weaker second path to the+ same destination is how the weaker one becomes the one people use."""+ maker, tenant_id, _user, token = world+ alert_id = await _alert(maker, tenant_id)+ code, body = await _post(+ token,+ "/api/v1/case-depth/alerts/bulk-triage",+ {"alert_ids": [str(alert_id)], "set_status": "closed", "max_count": 1},+ )+ assert code == 422+ assert "bulk-close" in body["detail"]++ async def test_naming_no_change_is_refused(self, world) -> None:+ maker, tenant_id, _user, token = world+ alert_id = await _alert(maker, tenant_id)+ code, body = await _post(token, "/api/v1/case-depth/alerts/bulk-triage", {"alert_ids": [str(alert_id)], "max_count": 1})+ assert code == 422+ assert "at least one of" in body["detail"]+++@live_only+class TestWorkload:+ async def test_counts_come_from_rows_this_query_selected(self, world) -> None:+ maker, tenant_id, _user, token = world+ await _case(maker, tenant_id, assignee="[email protected]", status="investigating")+ await _case(maker, tenant_id, assignee="[email protected]", status="new")+ await _case(maker, tenant_id, assignee="[email protected]", status="closed", closed=True)+ await _case(maker, tenant_id, assignee=None, status="new")++ code, body = await _get(token, "/api/v1/case-depth/workload?days=30")+ assert code == 200, body+ rows = {row["analyst"]: row for row in body["analysts"]}++ # Counted independently here rather than by calling the thing under+ # test a second time, which is how four usage meters came to agree+ # with themselves and not with the database.+ assert rows["[email protected]"]["open_cases"] == 2+ assert rows["[email protected]"]["closed_cases"] == 0+ assert rows["[email protected]"]["closed_cases"] == 1+ assert body["unassigned"]["open_cases"] == 1++ async def test_a_mean_over_nothing_is_null_not_zero(self, world) -> None:+ maker, tenant_id, _user, token = world+ await _case(maker, tenant_id, assignee="[email protected]", status="investigating")++ _code, body = await _get(token, "/api/v1/case-depth/workload?days=30")+ row = next(r for r in body["analysts"] if r["analyst"] == "[email protected]")+ # 0.0 reads as "closed instantly", which is the opposite of "no data".+ assert row["mean_hours_to_close"] is None+ assert row["mean_over_cases"] == 0++ async def test_a_mean_travels_with_the_count_it_was_taken_over(self, world) -> None:+ maker, tenant_id, _user, token = world+ await _case(maker, tenant_id, assignee="[email protected]", status="closed", closed=True, created_days_ago=2)+ await _case(maker, tenant_id, assignee="[email protected]", status="closed", closed=True, created_days_ago=3)++ _code, body = await _get(token, "/api/v1/case-depth/workload?days=30")+ row = next(r for r in body["analysts"] if r["analyst"] == "[email protected]")+ assert row["mean_over_cases"] == 2+ # Each fixture case closes four hours after it opens.+ assert row["mean_hours_to_close"] == pytest.approx(4.0, abs=0.1)++ async def test_a_case_absorbed_by_a_merge_is_not_counted_as_work(self, world) -> None:+ maker, tenant_id, _user, token = world+ primary = await _case(maker, tenant_id, assignee="[email protected]", status="investigating")+ duplicate = await _case(maker, tenant_id, assignee="[email protected]", status="investigating")++ before = (await _get(token, "/api/v1/case-depth/workload?days=30"))[1]+ assert next(r for r in before["analysts"] if r["analyst"] == "[email protected]")["open_cases"] == 2++ await _post(token, "/api/v1/case-depth/cases/merge", {"primary_id": str(primary), "duplicate_ids": [str(duplicate)]})++ after = (await _get(token, "/api/v1/case-depth/workload?days=30"))[1]+ row = next(r for r in after["analysts"] if r["analyst"] == "[email protected]")+ # Counting the absorbed case would make a merge look like throughput.+ assert row["open_cases"] == 1+ assert row["total"] == 1+++@live_only+class TestCustomFields:+ async def test_a_value_under_an_undefined_key_is_refused(self, world) -> None:+ maker, tenant_id, _user, token = world+ case_id = await _case(maker, tenant_id)+ from app.main import app++ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:+ res = await client.put(+ f"/api/v1/case-depth/cases/{case_id}/custom-values",+ json={"values": {"business_unit": "payments"}},+ headers={"Authorization": f"Bearer {token}"},+ )+ assert res.status_code == 422+ assert "no such custom field" in res.text++ async def test_a_field_defined_after_the_case_still_renders_on_it(self, world) -> None:+ maker, tenant_id, _user, token = world+ case_id = await _case(maker, tenant_id)+ code, field = await _post(+ token,+ "/api/v1/case-depth/custom-fields",+ {"key": "business_unit", "label": "Business unit", "field_type": "select", "choices": ["payments", "retail"]},+ )+ assert code == 201, field++ code, values = await _get(token, f"/api/v1/case-depth/cases/{case_id}/custom-values")+ assert code == 200+ # The form returns the *fields*, not the stored rows, so a field added+ # after the case was created is not silently omitted.+ assert [v["key"] for v in values] == ["business_unit"]+ assert values[0]["value"] == ""++ async def test_retiring_a_field_keeps_the_values_written_against_it(self, world) -> None:+ maker, tenant_id, _user, token = world+ case_id = await _case(maker, tenant_id)+ _code, field = await _post(+ token,+ "/api/v1/case-depth/custom-fields",+ {"key": "owner_team", "label": "Owning team", "field_type": "text"},+ )+ from app.main import app++ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:+ await client.put(+ f"/api/v1/case-depth/cases/{case_id}/custom-values",+ json={"values": {"owner_team": "payments-oncall"}},+ headers={"Authorization": f"Bearer {token}"},+ )+ await client.delete(+ f"/api/v1/case-depth/custom-fields/{field['id']}",+ headers={"Authorization": f"Bearer {token}"},+ )++ async with maker() as db:+ stored = (await db.execute(text("SELECT value FROM aisoc_case_custom_values WHERE case_id = :c"), {"c": case_id})).scalar_one()+ assert stored == "payments-oncall"++ async def test_a_select_with_no_choices_is_refused(self, world) -> None:+ _maker, _tenant_id, _user, token = world+ code, body = await _post(+ token,+ "/api/v1/case-depth/custom-fields",+ {"key": "empty_select", "label": "Empty", "field_type": "select", "choices": []},+ )+ assert code == 422+ assert "at least one choice" in body["detail"]