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(web): MITRE ATT&CK coverage view + vitest infrastructure + honesty refresh
Beenu Arora06982c3a52d6
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 974c6049d..9b301525f 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -9,7 +9,9 @@"build": "next build","start": "next start -p 3000","lint": "next lint",- "type-check": "tsc --noEmit"+ "type-check": "tsc --noEmit",+ "test": "vitest run",+ "test:watch": "vitest"},"dependencies": {"@aisoc/types": "workspace:*",@@ -32,15 +34,21 @@"zustand": "^4.4.7"},"devDependencies": {+ "@testing-library/jest-dom": "^6.4.2",+ "@testing-library/react": "^14.2.0",+ "@testing-library/user-event": "^14.5.2","@types/cytoscape": "^3.21.0","@types/node": "^20.10.0","@types/react": "^18.2.0","@types/react-dom": "^18.2.0",+ "@vitejs/plugin-react": "^4.2.1","autoprefixer": "^10.4.17","eslint": "^8.56.0","eslint-config-next": "14.1.0",+ "jsdom": "^24.0.0","postcss": "^8.4.33","tailwindcss": "^3.4.1",- "typescript": "^5.3.3"+ "typescript": "^5.3.3",+ "vitest": "^2.0.0"}}diff --git a/apps/web/src/app/(app)/detection/coverage/page.tsx b/apps/web/src/app/(app)/detection/coverage/page.tsxnew file mode 100644index 000000000..734c1ffc9--- /dev/null+++ b/apps/web/src/app/(app)/detection/coverage/page.tsx@@ -0,0 +1,11 @@+import { CoverageView } from '@/components/detections/CoverageView';++export const metadata = {+ title: 'MITRE ATT&CK Coverage | AiSOC',+ description:+ "MITRE ATT&CK coverage matrix derived from AiSOC's shipped detections, broken down by tier (native, imported, community).",+};++export default function CoveragePage() {+ return <CoverageView />;+}diff --git a/apps/web/src/app/benchmark/page.tsx b/apps/web/src/app/benchmark/page.tsxindex e4c95e4fd..f819ec0f6 100644--- a/apps/web/src/app/benchmark/page.tsx+++ b/apps/web/src/app/benchmark/page.tsx@@ -8,7 +8,7 @@ import { ComparisonTable } from '@/components/benchmark/ComparisonTable';export const metadata: Metadata = {title: 'Public eval harness — AiSOC',description:- 'A reproducible regression harness over the AiSOC substrate. 200 deterministic synthetic incidents and four CI gates: one real measurement (alert reduction) and three substrate self-consistency checks. The page documents what each metric measures and what it does not.',+ 'A reproducible regression harness over the AiSOC substrate. Four CI gates over a 200-incident synthetic dataset (MITRE / completeness / response quality) plus a 1,000-alert noisy stream (alert reduction). One real measurement (alert reduction) and three substrate self-consistency checks. The page documents what each metric measures and what it does not.',alternates: { canonical: '/benchmark' },openGraph: {title: 'AiSOC public eval harness',@@ -43,17 +43,20 @@ export default function BenchmarkPage() {<span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />Reproducible</span>- <span className="text-xs text-gray-500">Runs on every commit to main</span>+ <span className="text-xs text-gray-500">Runs on every PR targeting main / develop</span></div><h1 className="text-4xl font-bold tracking-tight md:text-5xl">Public eval harness</h1><p className="mt-4 max-w-3xl text-lg text-gray-400">A deterministic regression harness over the AiSOC substrate —- the keyword extractors, the fusion pipeline, the report and- response templates, and the offline judges that grade them. The- dataset, the harness, and the CI gate are in the repo. The numbers- on this page reproduce in roughly 25 milliseconds on a laptop.+ the keyword extractors, the in-harness fusion grouping (a faithful+ re-implementation of the production Tier 1/2/3 logic in{' '}+ <code className="text-gray-300">services/fusion</code>, minus the+ DB-backed dedup and ML scoring), the report and response+ templates, and the offline judges that grade them. The dataset,+ the harness, and the CI gate are in the repo. The numbers on this+ page reproduce in roughly 25 ms on a laptop.</p><div className="mt-5 max-w-3xl rounded-lg border border-amber-500/20 bg-amber-500/[0.04] p-4 text-sm text-amber-100/80">@@ -151,10 +154,15 @@ export default function BenchmarkPage() {<p className="mt-2 text-gray-300">A 1,000-alert noisy stream with duplicates, near-duplicates,rule-storms, and benign chatter is fabricated deterministically,- then passed through the actual fusion pipeline (Tier 1 / 2 / 3- merge windows, score floor). The reduction ratio is whatever- the real code emits. This is a legitimate measurement of the- fusion logic, and a fusion regression will move the number.+ then passed through{' '}+ <code className="text-gray-300">fuse_alerts</code> — an+ in-harness re-implementation of the same Tier 1 / 2 / 3 merge+ windows and score floor that the production fusion service+ runs. The grouping logic is identical; the harness skips the+ DB-backed deduplicator and ML scorer that ride on top in+ production. The reduction ratio is whatever the harness code+ emits. This is a legitimate measurement of the grouping logic,+ and a regression in those rules will move the number.</p></div>diff --git a/apps/web/src/app/why-open-source/page.tsx b/apps/web/src/app/why-open-source/page.tsxindex f34132398..3a92f2a6b 100644--- a/apps/web/src/app/why-open-source/page.tsx+++ b/apps/web/src/app/why-open-source/page.tsx@@ -25,7 +25,7 @@ const PILLARS = [{label: 'Public eval harness',href: '/benchmark',- body: 'A 200-incident eval suite runs on every commit. Four CI gates: one real measurement (alert reduction) and three substrate self-consistency checks (MITRE tactic, completeness, response quality). The harness, the dataset, the rubric, and historical results are in the repo. The benchmark page documents what each metric measures and what it does not.',+ body: 'A 200-incident eval suite runs on every PR targeting main / develop. Four CI gates: one real measurement (alert reduction, against a separately generated 1,000-alert noisy stream) and three substrate self-consistency checks (MITRE tactic, completeness, response quality, against the 200-incident dataset). The harness, the dataset, the rubric, and historical results are in the repo. The benchmark page documents what each metric measures and what it does not.',},{label: 'MIT, end-to-end',@@ -79,7 +79,7 @@ const CONTRASTS: readonly Contrast[] = [points: ['Agent runs on the buyer infrastructure. Incident data, by default, does not leave the buyer network.','Every prompt, response, tool call, and decision is written to the Investigation Ledger and replayable per case.',- 'Substrate behaviour is gated in CI on every commit. The dataset, harness, rubric, and historical numbers are in the repo and reproducible. The benchmark page is explicit about which metrics measure the substrate and which would need an online LLM-as-judge run to be called agent accuracy.',+ 'Substrate behaviour is gated in CI on every PR targeting main / develop. The dataset, harness, rubric, and historical numbers are in the repo and reproducible. The benchmark page is explicit about which metrics measure the substrate and which would need an online LLM-as-judge run to be called agent accuracy.','MIT, no CLA. Forks are permanent.',],accent: true,diff --git a/apps/web/src/components/benchmark/BenchmarkResults.tsx b/apps/web/src/components/benchmark/BenchmarkResults.tsxindex ba5f10585..4b6329f28 100644--- a/apps/web/src/components/benchmark/BenchmarkResults.tsx+++ b/apps/web/src/components/benchmark/BenchmarkResults.tsx@@ -23,8 +23,17 @@ interface SuiteRow {}/**- * Snapshot of the latest run on `main`. Keep these aligned with- * `eval_report.json` produced by `scripts/run_evals.py`.+ * Manual snapshot of a recent run on `main`. The numbers are hand-copied+ * from `eval_report.json` produced by `scripts/run_evals.py --out+ * eval_report.json` against the deterministic dataset. The audit trail —+ * one report per main-branch commit — lives on the `eval-results` branch+ * at `eval/results/<sha>.json` and `eval/results/latest.json`, published+ * automatically by the `p1-eval` job in `.github/workflows/ci.yml`. There+ * is no build-time fetch wired up here, though, so this file can drift+ * between a substrate change and a marketing-page edit. The pass/fail+ * gates in `services/agents/tests/test_*.py` are the source of truth: if+ * the gates pass, the headline "≥ target" claim still holds even if these+ * exact percentages lag a commit or two.** The blurbs deliberately avoid "agent accuracy" framing. The harness is* deterministic substrate code (no LLM calls), and three of the four metrics@@ -43,7 +52,7 @@ const SUITES: SuiteRow[] = [targetDisplay: '≥70%',kind: 'measurement',blurb:- "A 1,000-alert noisy stream (duplicates, near-duplicates, rule storms, low-score chatter) is fed into the real fusion pipeline (Tier 1 / 2 / 3). The number is whatever the code produces — a fusion regression will move it.",+ "A 1,000-alert noisy stream (duplicates, near-duplicates, rule storms, low-score chatter) is fed into an in-harness re-implementation of the production Tier 1 / 2 / 3 grouping rules — same logic, no DB-backed dedup or ML scorer. The number is whatever the code produces; a regression in the grouping rules moves it.",details: [{ label: 'Alerts in', value: '1,000' },{ label: 'Incidents out', value: '247' },@@ -64,7 +73,7 @@ const SUITES: SuiteRow[] = [details: [{ label: 'Incidents', value: '200' },{ label: 'Correct', value: '194' },- { label: 'Macro F1', value: '0.78' },+ { label: 'F1 (per-case)', value: '0.78' },],},{diff --git a/apps/web/src/components/benchmark/ComparisonTable.test.tsx b/apps/web/src/components/benchmark/ComparisonTable.test.tsxnew file mode 100644index 000000000..e24bc9c94--- /dev/null+++ b/apps/web/src/components/benchmark/ComparisonTable.test.tsx@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';+import { render, screen } from '@testing-library/react';+import { ComparisonTable } from './ComparisonTable';++// Smoke test for the landing-page comparison table. The point isn't to pin+// every cell value — those can change as the harness evolves — but to catch+// regressions where the table fails to render at all (broken import, missing+// VENDORS, etc.) and to guard the honesty claims we deliberately rolled back+// from gimmick land in P1.+describe('ComparisonTable', () => {+ it('renders the AiSOC row plus both competitor categories', () => {+ render(<ComparisonTable />);++ expect(screen.getByText('AiSOC')).toBeInTheDocument();+ expect(screen.getByText('Closed-source AI SOC')).toBeInTheDocument();+ expect(screen.getByText('Closed-source SOAR')).toBeInTheDocument();+ });++ it('declares the reproducibility claim as PR-gated, not "every commit"', () => {+ // P1 honesty fix — the AiSOC reduction cell must say "main / develop",+ // never "every commit". If someone sneaks the old wording back in, this+ // test fails.+ render(<ComparisonTable />);++ const cell = screen.getByText(/every PR to main \/ develop/i);+ expect(cell).toBeInTheDocument();+ expect(screen.queryByText(/every commit/i)).toBeNull();+ });++ it('tags the alert-reduction number as a measurement, not a marketing claim', () => {+ render(<ComparisonTable />);++ // Substring match — the cell reads "75.3% (measured on fixed noisy stream)".+ expect(screen.getByText(/75\.3% \(measured/)).toBeInTheDocument();+ });+});diff --git a/apps/web/src/components/benchmark/ComparisonTable.tsx b/apps/web/src/components/benchmark/ComparisonTable.tsxindex b11c8b352..00021c704 100644--- a/apps/web/src/components/benchmark/ComparisonTable.tsx+++ b/apps/web/src/components/benchmark/ComparisonTable.tsx@@ -28,37 +28,19 @@ const VENDORS: Vendor[] = [mitre: '97% (substrate regression gate)',audit: 'Per-step ledger',selfHost: 'Yes (MIT)',- reproducible: 'Yes — every commit',+ reproducible: 'Yes — every PR to main / develop',},{- name: 'Anvilogic',+ name: 'Closed-source AI SOC',type: 'closed',- reduction: '~90% (vendor claim)',+ reduction: 'Vendor claim, no harness',mitre: 'Not published',audit: 'Vendor portal',selfHost: 'No (cloud only)',reproducible: 'No',},{- name: 'Prophet',- type: 'closed',- reduction: '"10x throughput" (no method)',- mitre: 'Not published',- audit: 'Vendor portal',- selfHost: 'No (cloud only)',- reproducible: 'No',- },- {- name: 'Dropzone',- type: 'closed',- reduction: 'Not published',- mitre: 'Not published',- audit: 'Vendor portal',- selfHost: 'No (cloud only)',- reproducible: 'No',- },- {- name: 'Tines',+ name: 'Closed-source SOAR',type: 'closed',reduction: 'N/A (SOAR)',mitre: 'Not applicable',diff --git a/apps/web/src/components/cases/CaseWorkspace.test.tsx b/apps/web/src/components/cases/CaseWorkspace.test.tsxnew file mode 100644index 000000000..1b381824b--- /dev/null+++ b/apps/web/src/components/cases/CaseWorkspace.test.tsx@@ -0,0 +1,127 @@+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';+import { render, screen } from '@testing-library/react';+import type { Case } from '@/lib/api';++// We mock SWR rather than the real network layer so the test stays+// hermetic and so we can exercise both the loaded and fallback paths.+const swrState = vi.hoisted(() => ({+ data: undefined as Case | undefined,+ error: undefined as Error | undefined,+}));++vi.mock('swr', () => ({+ __esModule: true,+ default: () => ({+ data: swrState.data,+ error: swrState.error,+ isLoading: !swrState.data && !swrState.error,+ mutate: vi.fn(async () => undefined),+ }),+}));++vi.mock('next/link', () => ({+ __esModule: true,+ default: ({ children, href, ...rest }: { children: React.ReactNode; href: string }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));++vi.mock('next/navigation', () => ({+ useSearchParams: () => new URLSearchParams(),+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),+ usePathname: () => '/cases/INC-001',+}));++vi.mock('react-hot-toast', () => {+ const fn = vi.fn();+ // react-hot-toast exports both `toast()` and `toast.success/error`; mirror that.+ return {+ __esModule: true,+ default: Object.assign(fn, {+ success: vi.fn(),+ error: vi.fn(),+ loading: vi.fn(),+ }),+ toast: Object.assign(fn, {+ success: vi.fn(),+ error: vi.fn(),+ loading: vi.fn(),+ }),+ Toaster: () => null,+ };+});++// Stub the heavy children — they have their own SWR + WS deps and are+// not what we're smoke-testing here.+vi.mock('./InvestigationLedger', () => ({+ InvestigationLedger: () => <div data-testid="investigation-ledger" />,+}));++vi.mock('@/components/copilot/ContextualActions', () => ({+ ContextualActions: () => <div data-testid="contextual-actions" />,+}));++import { CaseWorkspace } from './CaseWorkspace';++const fakeCase: Case = {+ id: 'INC-001',+ title: 'Suspected lateral movement from finance subnet',+ description: 'Multiple high-severity alerts indicate a pivot via SMB.',+ status: 'in_progress',+ severity: 'critical',+ assignee: '[email protected]',+ tags: ['lateral-movement'],+ mitre: ['T1021.002', 'T1078'],+ alertIds: ['alert-1'],+ alertCount: 1,+ createdBy: 'system',+ createdAt: new Date(Date.now() - 60_000).toISOString(),+ updatedAt: new Date(Date.now() - 30_000).toISOString(),+ timeline: [],+ tasks: [],+};++describe('CaseWorkspace', () => {+ beforeEach(() => {+ swrState.data = fakeCase;+ swrState.error = undefined;+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it('renders the case header with title, severity, and MITRE chips', () => {+ render(<CaseWorkspace caseId="INC-001" />);++ expect(+ screen.getByRole('heading', { level: 1, name: /lateral movement from finance subnet/i }),+ ).toBeInTheDocument();+ expect(screen.getByText('critical')).toBeInTheDocument();++ // MITRE techniques should render as outbound links to attack.mitre.org.+ const t1021 = screen.getByRole('link', { name: /T1021\.002/ });+ expect(t1021).toHaveAttribute('href', 'https://attack.mitre.org/techniques/T1021/002/');+ expect(screen.getByRole('link', { name: /T1078/ })).toHaveAttribute(+ 'href',+ 'https://attack.mitre.org/techniques/T1078/',+ );+ });++ it('shows the demo banner when the backend errors out', () => {+ swrState.data = undefined;+ swrState.error = new Error('fetch failed');++ render(<CaseWorkspace caseId="INC-001" />);++ // Falls back to buildDemoCase, so the demo title renders…+ expect(+ screen.getByRole('heading', { level: 1, name: /lateral movement from finance subnet/i }),+ ).toBeInTheDocument();++ // …and the demo-mode banner is visible so the analyst knows it's not live data.+ expect(screen.getByText(/demo data — backend offline/i)).toBeInTheDocument();+ });+});diff --git a/apps/web/src/components/detections/CoverageView.tsx b/apps/web/src/components/detections/CoverageView.tsxnew file mode 100644index 000000000..22f3c7c98--- /dev/null+++ b/apps/web/src/components/detections/CoverageView.tsx@@ -0,0 +1,460 @@+'use client';++import { useMemo, useState } from 'react';+import useSWR from 'swr';+import clsx from 'clsx';++import {+ OTHER_TACTIC,+ TACTICS,+ type Tactic,+ tacticsFor,+} from '@/lib/mitreTactics';++// ── Types ────────────────────────────────────────────────────────────────────++interface MitreCoverage {+ techniques: Record<string, number>;+ unique_techniques: number;+ total_with_mitre: number;+ by_tier?: Record<string, Record<string, number>>;+}++interface MarketplaceStats {+ total: number;+ detections: number;+ detections_by_tier?: Record<string, number>;+ quarantined?: number;+}++interface MarketplaceIndex {+ version: string;+ generated: string;+ stats?: MarketplaceStats;+ mitre_coverage?: MitreCoverage;+}++type TierFilter = 'all' | 'stable' | 'imported' | 'community';++const TIER_LABEL: Record<Exclude<TierFilter, 'all'>, string> = {+ stable: 'Native',+ imported: 'Imported',+ community: 'Community',+};++const TIER_COLOR: Record<Exclude<TierFilter, 'all'>, string> = {+ stable: 'bg-emerald-500',+ imported: 'bg-sky-500',+ community: 'bg-amber-500',+};++// ── Data fetching ───────────────────────────────────────────────────────────++const fetcher = (url: string) =>+ fetch(url, { cache: 'no-store' }).then((r) => {+ if (!r.ok) throw new Error(`Failed to load ${url}: ${r.status}`);+ return r.json();+ });++// ── Component ───────────────────────────────────────────────────────────────++export function CoverageView() {+ const { data, error, isLoading } = useSWR<MarketplaceIndex>(+ '/marketplace/index.json',+ fetcher,+ { revalidateOnFocus: false },+ );++ const [tierFilter, setTierFilter] = useState<TierFilter>('all');++ const matrix = useMemo(() => {+ if (!data?.mitre_coverage) return null;+ return buildMatrix(data.mitre_coverage, tierFilter);+ }, [data, tierFilter]);++ if (isLoading) {+ return (+ <div className="p-8 text-sm text-gray-400">Loading coverage…</div>+ );+ }++ if (error || !data?.mitre_coverage || !matrix) {+ return (+ <div className="p-8">+ <h1 className="text-2xl font-bold text-white">MITRE ATT&CK coverage</h1>+ <p className="mt-3 text-sm text-rose-300">+ Could not load <code>marketplace/index.json</code>. Run{' '}+ <code className="rounded bg-black/40 px-1.5 py-0.5">+ python3 scripts/build_marketplace.py+ </code>{' '}+ to generate it.+ </p>+ </div>+ );+ }++ const { stats } = data;++ return (+ <div className="p-6 lg:p-8">+ <header className="mb-6">+ <h1 className="text-2xl font-bold text-white">MITRE ATT&CK coverage</h1>+ <p className="mt-2 max-w-3xl text-sm text-gray-400">+ Live coverage matrix derived from <code>marketplace/index.json</code>.+ Counts reflect detection rules and playbooks with at least one+ mapped MITRE technique. Sub-techniques inherit their parent tactic.+ </p>+ </header>++ <Summary+ coverage={data.mitre_coverage}+ stats={stats}+ matrix={matrix}+ tierFilter={tierFilter}+ />++ <TierFilterBar value={tierFilter} onChange={setTierFilter} />++ <Legend />++ <Matrix matrix={matrix} />+ </div>+ );+}++// ── Summary cards ───────────────────────────────────────────────────────────++function Summary({+ coverage,+ stats,+ matrix,+ tierFilter,+}: {+ coverage: MitreCoverage;+ stats?: MarketplaceStats;+ matrix: BuiltMatrix;+ tierFilter: TierFilter;+}) {+ const detTotal = stats?.detections ?? 0;+ const detByTier = stats?.detections_by_tier ?? {};+ const quarantined = stats?.quarantined ?? 0;++ const techShown = matrix.tactics.reduce(+ (acc, col) => acc + col.techniques.length,+ 0,+ );++ return (+ <div className="mb-6 grid grid-cols-2 gap-3 lg:grid-cols-4">+ <Card label="Techniques covered" value={coverage.unique_techniques}>+ {tierFilter === 'all'+ ? 'across all tiers'+ : `in ${TIER_LABEL[tierFilter]} tier (${techShown} shown)`}+ </Card>++ <Card label="Rules with MITRE" value={coverage.total_with_mitre}>+ of {detTotal} detection rules+ </Card>++ <Card+ label="Detection rules"+ value={detTotal}+ breakdown={+ <div className="mt-2 space-y-0.5 text-[11px] text-gray-400">+ {Object.entries(detByTier).map(([tier, count]) => (+ <div key={tier} className="flex items-center gap-1.5">+ <span+ className={clsx(+ 'h-1.5 w-1.5 rounded-full',+ tierColorFor(tier),+ )}+ />+ <span className="capitalize">{tier}</span>+ <span className="font-mono">{count}</span>+ </div>+ ))}+ </div>+ }+ />++ <Card label="Quarantined" value={quarantined}>+ imported rules disabled until translated+ </Card>+ </div>+ );+}++function Card({+ label,+ value,+ children,+ breakdown,+}: {+ label: string;+ value: number;+ children?: React.ReactNode;+ breakdown?: React.ReactNode;+}) {+ return (+ <div className="rounded-lg border border-white/10 bg-surface-card/40 p-4">+ <div className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">+ {label}+ </div>+ <div className="mt-1 font-mono text-3xl font-bold text-white">{value}</div>+ {children ? (+ <div className="mt-1 text-xs text-gray-500">{children}</div>+ ) : null}+ {breakdown}+ </div>+ );+}++// ── Filter bar ──────────────────────────────────────────────────────────────++function TierFilterBar({+ value,+ onChange,+}: {+ value: TierFilter;+ onChange: (next: TierFilter) => void;+}) {+ const opts: { id: TierFilter; label: string }[] = [+ { id: 'all', label: 'All tiers' },+ { id: 'stable', label: 'Native (stable)' },+ { id: 'imported', label: 'Imported' },+ { id: 'community', label: 'Community' },+ ];+ return (+ <div className="mb-4 flex flex-wrap gap-2">+ {opts.map((opt) => (+ <button+ key={opt.id}+ type="button"+ onClick={() => onChange(opt.id)}+ className={clsx(+ 'rounded-full border px-3 py-1 text-xs font-medium transition-colors',+ value === opt.id+ ? 'border-brand-300/60 bg-brand-500/20 text-white'+ : 'border-white/10 bg-surface-card/40 text-gray-300 hover:bg-white/5',+ )}+ >+ {opt.label}+ </button>+ ))}+ </div>+ );+}++// ── Legend ──────────────────────────────────────────────────────────────────++function Legend() {+ return (+ <div className="mb-4 flex flex-wrap items-center gap-4 text-[11px] text-gray-400">+ <span>Heatmap intensity = number of rules covering the technique:</span>+ <span className="inline-flex items-center gap-1.5">+ <span className="h-3 w-3 rounded border border-white/10 bg-emerald-500/15" />+ 1 rule+ </span>+ <span className="inline-flex items-center gap-1.5">+ <span className="h-3 w-3 rounded border border-white/10 bg-emerald-500/35" />+ 2-4+ </span>+ <span className="inline-flex items-center gap-1.5">+ <span className="h-3 w-3 rounded border border-white/10 bg-emerald-500/55" />+ 5-9+ </span>+ <span className="inline-flex items-center gap-1.5">+ <span className="h-3 w-3 rounded border border-white/10 bg-emerald-500/80" />+ 10++ </span>+ </div>+ );+}++// ── Matrix ──────────────────────────────────────────────────────────────────++function Matrix({ matrix }: { matrix: BuiltMatrix }) {+ if (matrix.tactics.length === 0) {+ return (+ <div className="rounded-lg border border-white/10 bg-surface-card/40 p-6 text-sm text-gray-400">+ No techniques covered for this tier yet.+ </div>+ );+ }++ return (+ <div className="overflow-x-auto">+ <div+ className="grid auto-cols-[minmax(180px,1fr)] grid-flow-col gap-2"+ style={{ gridAutoColumns: 'minmax(180px, 1fr)' }}+ >+ {matrix.tactics.map((col) => (+ <TacticColumn key={col.tactic.id} column={col} />+ ))}+ </div>+ </div>+ );+}++function TacticColumn({ column }: { column: BuiltTactic }) {+ return (+ <div className="flex flex-col gap-1.5 rounded-lg border border-white/10 bg-surface-card/30 p-2.5">+ <div className="px-1 pb-1.5">+ <div className="font-mono text-[10px] uppercase tracking-wider text-gray-500">+ {column.tactic.id}+ </div>+ <div className="text-xs font-semibold text-white">+ {column.tactic.name}+ </div>+ <div className="mt-0.5 text-[10px] text-gray-500">+ {column.techniques.length} technique+ {column.techniques.length === 1 ? '' : 's'}+ </div>+ </div>+ <div className="flex flex-col gap-1">+ {column.techniques.map((tech) => (+ <TechniqueCell key={tech.id} technique={tech} />+ ))}+ </div>+ </div>+ );+}++function TechniqueCell({ technique }: { technique: BuiltTechnique }) {+ const intensity = intensityClass(technique.total);+ return (+ <a+ href={`https://attack.mitre.org/techniques/${technique.id.replace('.', '/')}/`}+ target="_blank"+ rel="noopener noreferrer"+ className={clsx(+ 'block rounded border px-2 py-1.5 transition-colors hover:border-brand-300/60',+ 'border-white/10',+ intensity,+ )}+ title={`${technique.id} — ${technique.total} rule${+ technique.total === 1 ? '' : 's'+ }`}+ >+ <div className="flex items-baseline justify-between gap-2">+ <span className="font-mono text-[11px] font-medium text-white/90">+ {technique.id}+ </span>+ <span className="font-mono text-[11px] text-white">+ {technique.total}+ </span>+ </div>+ {technique.byTier.length > 0 ? (+ <div className="mt-1 flex h-1 overflow-hidden rounded-full bg-white/5">+ {technique.byTier.map(({ tier, count }) => {+ const pct = (count / technique.total) * 100;+ return (+ <span+ key={tier}+ className={clsx('h-full', tierColorFor(tier))}+ style={{ width: `${pct}%` }}+ />+ );+ })}+ </div>+ ) : null}+ </a>+ );+}++// ── Matrix building ─────────────────────────────────────────────────────────++interface BuiltTechnique {+ id: string;+ total: number;+ byTier: { tier: string; count: number }[];+}++interface BuiltTactic {+ tactic: Tactic;+ techniques: BuiltTechnique[];+}++interface BuiltMatrix {+ tactics: BuiltTactic[];+}++function buildMatrix(+ coverage: MitreCoverage,+ tierFilter: TierFilter,+): BuiltMatrix {+ // Collect technique → counts (filtered by tier).+ const techniqueTotals: Record<string, number> = {};+ const techniqueByTier: Record<string, Record<string, number>> = {};++ if (tierFilter === 'all') {+ for (const [tech, count] of Object.entries(coverage.techniques)) {+ techniqueTotals[tech] = count;+ }+ for (const [tier, perTechnique] of Object.entries(+ coverage.by_tier ?? {},+ )) {+ for (const [tech, count] of Object.entries(perTechnique)) {+ techniqueByTier[tech] = techniqueByTier[tech] ?? {};+ techniqueByTier[tech][tier] = (techniqueByTier[tech][tier] ?? 0) + count;+ }+ }+ } else {+ const slice = coverage.by_tier?.[tierFilter] ?? {};+ for (const [tech, count] of Object.entries(slice)) {+ techniqueTotals[tech] = count;+ techniqueByTier[tech] = { [tierFilter]: count };+ }+ }++ // Group by tactic.+ const byTactic = new Map<string, BuiltTechnique[]>();+ for (const [tech, total] of Object.entries(techniqueTotals)) {+ const tactics = tacticsFor(tech);+ const built: BuiltTechnique = {+ id: tech,+ total,+ byTier: Object.entries(techniqueByTier[tech] ?? {})+ .map(([tier, count]) => ({ tier, count }))+ .sort((a, b) => b.count - a.count),+ };+ for (const tacticId of tactics) {+ const list = byTactic.get(tacticId) ?? [];+ list.push(built);+ byTactic.set(tacticId, list);+ }+ }++ // Order tactics in standard kill-chain order; append "Other" if present.+ const orderedTactics: BuiltTactic[] = [];+ for (const tactic of TACTICS) {+ const techniques = byTactic.get(tactic.id);+ if (!techniques || techniques.length === 0) continue;+ techniques.sort((a, b) => b.total - a.total || a.id.localeCompare(b.id));+ orderedTactics.push({ tactic, techniques });+ }+ const other = byTactic.get(OTHER_TACTIC.id);+ if (other && other.length > 0) {+ other.sort((a, b) => b.total - a.total || a.id.localeCompare(b.id));+ orderedTactics.push({ tactic: OTHER_TACTIC, techniques: other });+ }++ return { tactics: orderedTactics };+}++// ── Helpers ─────────────────────────────────────────────────────────────────++function intensityClass(count: number): string {+ if (count >= 10) return 'bg-emerald-500/80';+ if (count >= 5) return 'bg-emerald-500/55';+ if (count >= 2) return 'bg-emerald-500/35';+ return 'bg-emerald-500/15';+}++function tierColorFor(tier: string): string {+ if (tier === 'stable') return TIER_COLOR.stable;+ if (tier === 'imported') return TIER_COLOR.imported;+ if (tier === 'community') return TIER_COLOR.community;+ // beta, unknown+ return 'bg-violet-500';+}diff --git a/apps/web/src/components/landing/Hero.test.tsx b/apps/web/src/components/landing/Hero.test.tsxnew file mode 100644index 000000000..d3aaee78b--- /dev/null+++ b/apps/web/src/components/landing/Hero.test.tsx@@ -0,0 +1,55 @@+import { describe, expect, it, vi } from 'vitest';+import { render, screen } from '@testing-library/react';++// next/link wants a Next.js router context; for a smoke test we mock it.+vi.mock('next/link', () => ({+ default: ({ children, href }: { children: React.ReactNode; href: string }) => (+ <a href={href}>{children}</a>+ ),+}));++// framer-motion's runtime needs window APIs we don't bother spinning up+// in a unit test. The "motion." factory is just a thin wrapper here — render+// the underlying tag.+vi.mock('framer-motion', () => {+ const factory = (Tag: keyof JSX.IntrinsicElements) =>+ function MotionStub(props: Record<string, unknown>) {+ const { children, ...rest } = props as {+ children?: React.ReactNode;+ } & Record<string, unknown>;+ // Strip framer-motion-only props before they leak onto a DOM element.+ delete (rest as Record<string, unknown>).initial;+ delete (rest as Record<string, unknown>).animate;+ delete (rest as Record<string, unknown>).transition;+ delete (rest as Record<string, unknown>).whileHover;+ delete (rest as Record<string, unknown>).whileTap;+ return <Tag {...(rest as Record<string, unknown>)}>{children}</Tag>;+ };+ return {+ motion: new Proxy({}, { get: (_t, key: string) => factory(key as keyof JSX.IntrinsicElements) }),+ };+});++import { Hero } from './Hero';++describe('Hero', () => {+ it('renders the headline and primary CTAs', () => {+ render(<Hero />);++ expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(/auditable AI SOC/i);+ expect(screen.getByRole('link', { name: /open the demo/i })).toHaveAttribute(+ 'href',+ 'https://demo.aisoc.dev/cases/INC-001?tab=ledger',+ );+ expect(screen.getByRole('link', { name: /open console/i })).toHaveAttribute('href', '/dashboard');+ });++ it('describes the eval harness as PR-gated, never "every commit"', () => {+ // P1 honesty fix: the body copy must mention "every PR" / "main / develop"+ // rather than the older "every commit" wording.+ render(<Hero />);++ expect(screen.getByText(/every PR targeting/i)).toBeInTheDocument();+ expect(screen.queryByText(/every commit/i)).toBeNull();+ });+});diff --git a/apps/web/src/components/landing/Hero.tsx b/apps/web/src/components/landing/Hero.tsxindex 09355c640..f23f0b5e8 100644--- a/apps/web/src/components/landing/Hero.tsx+++ b/apps/web/src/components/landing/Hero.tsx@@ -31,8 +31,11 @@ export function Hero() {<p className="mt-6 max-w-xl text-lg leading-relaxed text-gray-300 md:text-xl">Agent prompts, tool calls, and decisions are recorded in an investigationledger and replayable per case. The substrate underneath is gated by a- 200-incident eval harness that runs on every commit. MIT-licensed and- self-hostable.+ 200-incident eval harness that runs on every PR targeting{' '}+ <code className="rounded bg-white/[0.06] px-1 py-0.5 font-mono text-base">main</code>{' '}+ /{' '}+ <code className="rounded bg-white/[0.06] px-1 py-0.5 font-mono text-base">develop</code>.+ MIT-licensed and self-hostable.</p><div className="mt-8 flex flex-wrap items-center gap-3">@@ -74,7 +77,7 @@ export function Hero() {eval harness, and the license. */}<dl className="mt-10 grid grid-cols-3 gap-6 border-t border-white/5 pt-8"><Stat label="Agent decisions" value="Ledger" caption="prompt + tool + rationale per step" />- <Stat label="Eval harness" value="200 cases" caption="runs in CI on every commit" />+ <Stat label="Eval harness" value="200 cases" caption="runs in CI on every PR to main / develop" /><Stat label="License" value="MIT" caption="audit, fork, self-host" /></dl></motion.div>diff --git a/apps/web/src/components/layout/TopBar.test.tsx b/apps/web/src/components/layout/TopBar.test.tsxnew file mode 100644index 000000000..65690f86c--- /dev/null+++ b/apps/web/src/components/layout/TopBar.test.tsx@@ -0,0 +1,54 @@+import { describe, expect, it, vi } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++const pathnameMock = vi.fn(() => '/cases');++vi.mock('next/navigation', () => ({+ usePathname: () => pathnameMock(),+}));++import { TopBar } from './TopBar';++describe('TopBar', () => {+ it('shows the per-route title and description for known paths', () => {+ pathnameMock.mockReturnValue('/cases');+ render(<TopBar />);++ expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Cases');+ expect(screen.getByText('Incident case management')).toBeInTheDocument();+ });++ it('matches the most specific nested route first', () => {+ // /detection/catalog must win over /detection.+ pathnameMock.mockReturnValue('/detection/catalog');+ render(<TopBar />);++ expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Detection Catalog');+ });++ it('derives a sensible title for unknown routes from the path itself', () => {+ // Regression: previously fell back to "Alerts" for everything unmapped.+ pathnameMock.mockReturnValue('/some-new-page');+ render(<TopBar />);++ expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Some New Page');+ });++ it('dispatches a Cmd-K keyboard event when the palette button is clicked', async () => {+ pathnameMock.mockReturnValue('/dashboard');+ render(<TopBar />);++ const listener = vi.fn();+ window.addEventListener('keydown', listener);++ await userEvent.click(screen.getByRole('button', { name: /open command palette/i }));++ expect(listener).toHaveBeenCalled();+ const event = listener.mock.calls[0][0] as KeyboardEvent;+ expect(event.key).toBe('k');+ expect(event.metaKey).toBe(true);++ window.removeEventListener('keydown', listener);+ });+});diff --git a/apps/web/src/lib/mitreTactics.ts b/apps/web/src/lib/mitreTactics.tsnew file mode 100644index 000000000..54ccd468d--- /dev/null+++ b/apps/web/src/lib/mitreTactics.ts@@ -0,0 +1,184 @@+/**+ * MITRE ATT&CK tactic mapping for technique IDs.+ *+ * The full ATT&CK Enterprise corpus is large; this file maintains a curated+ * map covering the techniques AiSOC ships rules for today, plus the parent+ * technique for every sub-technique we know about. Anything outside the map+ * falls back to the "Other" bucket so the coverage view still degrades+ * gracefully if upstream importers introduce a technique we haven't mapped+ * yet.+ *+ * Source of truth: https://attack.mitre.org/matrices/enterprise/ (Apr 2026+ * snapshot). When new techniques land, add them here so they show up in the+ * right tactic column.+ */++export interface Tactic {+ id: string;+ name: string;+ shortName: string;+}++/** ATT&CK Enterprise tactics, in standard kill-chain order. */+export const TACTICS: Tactic[] = [+ { id: 'TA0043', name: 'Reconnaissance', shortName: 'Recon' },+ { id: 'TA0042', name: 'Resource Development', shortName: 'Resource Dev' },+ { id: 'TA0001', name: 'Initial Access', shortName: 'Init Access' },+ { id: 'TA0002', name: 'Execution', shortName: 'Execution' },+ { id: 'TA0003', name: 'Persistence', shortName: 'Persistence' },+ { id: 'TA0004', name: 'Privilege Escalation', shortName: 'Priv Esc' },+ { id: 'TA0005', name: 'Defense Evasion', shortName: 'Defense Evasion' },+ { id: 'TA0006', name: 'Credential Access', shortName: 'Cred Access' },+ { id: 'TA0007', name: 'Discovery', shortName: 'Discovery' },+ { id: 'TA0008', name: 'Lateral Movement', shortName: 'Lateral' },+ { id: 'TA0009', name: 'Collection', shortName: 'Collection' },+ { id: 'TA0011', name: 'Command and Control', shortName: 'C&C' },+ { id: 'TA0010', name: 'Exfiltration', shortName: 'Exfil' },+ { id: 'TA0040', name: 'Impact', shortName: 'Impact' },+];++export const TACTIC_BY_ID = new Map<string, Tactic>(+ TACTICS.map((t) => [t.id, t]),+);++const OTHER_TACTIC_ID = 'OTHER';++export const OTHER_TACTIC: Tactic = {+ id: OTHER_TACTIC_ID,+ name: 'Other / Unmapped',+ shortName: 'Other',+};++/**+ * Parent-technique → tactic IDs.+ *+ * Sub-techniques (e.g. T1078.001) inherit the parent's tactics unless they+ * appear here explicitly. This keeps the table small while still routing the+ * 120+ technique IDs we ship today into the right columns.+ */+const PARENT_TACTIC_MAP: Record<string, string[]> = {+ // Reconnaissance+ T1592: ['TA0043'],+ T1595: ['TA0043'],++ // Initial Access+ T1133: ['TA0001', 'TA0003'],+ T1190: ['TA0001'],+ T1195: ['TA0001'],+ T1199: ['TA0001'],+ T1566: ['TA0001'],+ T1656: ['TA0001'],++ // Execution+ T1047: ['TA0002'],+ T1059: ['TA0002'],+ T1204: ['TA0002'],+ T1609: ['TA0002'],++ // Persistence+ T1098: ['TA0003', 'TA0004'],+ T1136: ['TA0003'],+ T1176: ['TA0003'],+ T1505: ['TA0003'],+ T1525: ['TA0003'],++ // Privilege Escalation+ T1068: ['TA0004'],+ T1611: ['TA0004'],++ // Multi-tactic+ T1053: ['TA0002', 'TA0003', 'TA0004'],+ T1055: ['TA0004', 'TA0005'],+ T1078: ['TA0001', 'TA0003', 'TA0004', 'TA0005'],+ T1543: ['TA0003', 'TA0004'],+ T1547: ['TA0003', 'TA0004'],+ T1548: ['TA0004', 'TA0005'],+ T1574: ['TA0003', 'TA0004', 'TA0005'],+ T1484: ['TA0004', 'TA0005'],++ // Defense Evasion+ T1027: ['TA0005'],+ T1070: ['TA0005'],+ T1218: ['TA0005'],+ T1550: ['TA0005', 'TA0008'],+ T1553: ['TA0005'],+ T1556: ['TA0003', 'TA0005', 'TA0006'],+ T1562: ['TA0005'],+ T1564: ['TA0005'],+ T1578: ['TA0005'],++ // Credential Access+ T1003: ['TA0006'],+ T1110: ['TA0006'],+ T1212: ['TA0006'],+ T1528: ['TA0006'],+ T1539: ['TA0006'],+ T1552: ['TA0006'],+ T1555: ['TA0006'],+ T1557: ['TA0006', 'TA0009'],+ T1558: ['TA0006'],+ T1606: ['TA0006'],+ T1621: ['TA0006'],++ // Discovery+ T1040: ['TA0006', 'TA0007'],+ T1046: ['TA0007'],+ T1069: ['TA0007'],+ T1083: ['TA0007'],+ T1087: ['TA0007'],+ T1135: ['TA0007'],++ // Lateral Movement+ T1021: ['TA0008'],++ // Collection+ T1113: ['TA0009'],+ T1114: ['TA0009'],+ T1530: ['TA0009'],+ T1560: ['TA0009'],++ // Command and Control+ T1071: ['TA0011'],+ T1090: ['TA0011'],+ T1095: ['TA0011'],+ T1219: ['TA0011'],+ T1568: ['TA0011'],+ T1572: ['TA0011'],+ T1573: ['TA0011'],++ // Exfiltration+ T1041: ['TA0010'],+ T1048: ['TA0010'],+ T1052: ['TA0010'],+ T1567: ['TA0010'],++ // Impact+ T1485: ['TA0040'],+ T1486: ['TA0040'],+ T1490: ['TA0040'],+ T1498: ['TA0040'],+ T1531: ['TA0040'],+ T1565: ['TA0040'],+};++/**+ * Resolve the tactics this technique covers.+ *+ * Sub-techniques (T1078.004) inherit from their parent (T1078) unless they+ * override the mapping. Returns ``[OTHER_TACTIC.id]`` if the technique is not+ * known so unmapped rules still get counted in the matrix instead of falling+ * off the bottom of the page.+ */+export function tacticsFor(techniqueId: string): string[] {+ const direct = PARENT_TACTIC_MAP[techniqueId];+ if (direct) return direct;+ const parent = techniqueId.split('.')[0];+ const fallback = PARENT_TACTIC_MAP[parent];+ if (fallback) return fallback;+ return [OTHER_TACTIC_ID];+}++/** Return the parent technique id for a sub-technique, or itself otherwise. */+export function parentTechnique(techniqueId: string): string {+ return techniqueId.split('.')[0];+}diff --git a/apps/web/src/test/setup.ts b/apps/web/src/test/setup.tsnew file mode 100644index 000000000..792780c64--- /dev/null+++ b/apps/web/src/test/setup.ts@@ -0,0 +1,53 @@+// Vitest setup — runs once before any test file.+//+// Adds @testing-library/jest-dom matchers (toBeInTheDocument, etc.) and+// stubs the browser APIs that Next.js components reach for at import time+// but that jsdom doesn't ship.++import '@testing-library/jest-dom/vitest';+import { afterEach, vi } from 'vitest';+import { cleanup } from '@testing-library/react';++afterEach(() => {+ cleanup();+});++// matchMedia is touched by some recharts/framer-motion code paths.+if (typeof window !== 'undefined' && !window.matchMedia) {+ window.matchMedia = (query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addListener: vi.fn(),+ removeListener: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ dispatchEvent: vi.fn(() => false),+ });+}++// IntersectionObserver is used by some charting/cmdk code at module load.+if (typeof window !== 'undefined' && !('IntersectionObserver' in window)) {+ class IntersectionObserverStub {+ observe = vi.fn();+ unobserve = vi.fn();+ disconnect = vi.fn();+ takeRecords = vi.fn(() => []);+ root = null;+ rootMargin = '';+ thresholds = [];+ }+ // @ts-expect-error — assigning a stub to satisfy code that just checks for existence.+ window.IntersectionObserver = IntersectionObserverStub;+}++// ResizeObserver — same story for responsive recharts containers.+if (typeof window !== 'undefined' && !('ResizeObserver' in window)) {+ class ResizeObserverStub {+ observe = vi.fn();+ unobserve = vi.fn();+ disconnect = vi.fn();+ }+ // @ts-expect-error — assigning a stub for the same reason as above.+ window.ResizeObserver = ResizeObserverStub;+}diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.tsnew file mode 100644index 000000000..f53a479b6--- /dev/null+++ b/apps/web/vitest.config.ts@@ -0,0 +1,22 @@+import { defineConfig } from 'vitest/config';+import react from '@vitejs/plugin-react';+import path from 'node:path';++// Smoke-test config for `apps/web`. We only need component-level rendering+// (jsdom) — no SSR, no Next.js server runtime. Anything that requires the+// full Next.js stack should live in an e2e suite (Playwright) instead.+export default defineConfig({+ plugins: [react()],+ test: {+ environment: 'jsdom',+ globals: true,+ setupFiles: ['./src/test/setup.ts'],+ include: ['src/**/*.{test,spec}.{ts,tsx}'],+ css: false,+ },+ resolve: {+ alias: {+ '@': path.resolve(__dirname, './src'),+ },+ },+});diff --git a/services/agents/app/tools/mitre.py b/services/agents/app/tools/mitre.pyindex 59c4fb1cb..576f447f6 100644--- a/services/agents/app/tools/mitre.py+++ b/services/agents/app/tools/mitre.py@@ -2,6 +2,7 @@Tool: MITRE ATT&CK framework lookups.Provides context for tactics, techniques, and suggested mitigations."""+import structloglogger = structlog.get_logger()diff --git a/services/agents/app/tools/mitre_full.py b/services/agents/app/tools/mitre_full.pyindex 81f82ca15..95abd6343 100644--- a/services/agents/app/tools/mitre_full.py+++ b/services/agents/app/tools/mitre_full.py@@ -12,6 +12,7 @@ On startup, this module:AiSOC — open-source AI Security Operations Center (MIT License)"""+from __future__ import annotationsimport asyncio@@ -28,10 +29,7 @@ logger = structlog.get_logger(__name__)# ─── Constants ────────────────────────────────────────────────────────────────-ATTCK_CDN_URL = (- "https://raw.githubusercontent.com/mitre/cti/master/"- "enterprise-attack/enterprise-attack.json"-)+ATTCK_CDN_URL = "https://raw.githubusercontent.com/mitre/cti/master/enterprise-attack/enterprise-attack.json"ATTCK_DATA_PATH = os.getenv("ATTCK_DATA_PATH", "/data/enterprise-attack.json")_CACHE_TTL_HOURS = 24_EMBED_BATCH_SIZE = 50@@ -39,13 +37,24 @@ _EMBED_BATCH_SIZE = 50# ─── Data Model ───────────────────────────────────────────────────────────────+class MitreTechnique:"""Represents a single ATT&CK technique or sub-technique."""__slots__ = (- "id", "name", "description", "tactic_ids", "tactic_names",- "platforms", "data_sources", "mitigations", "detections",- "is_subtechnique", "parent_id", "url", "version",+ "id",+ "name",+ "description",+ "tactic_ids",+ "tactic_names",+ "platforms",+ "data_sources",+ "mitigations",+ "detections",+ "is_subtechnique",+ "parent_id",+ "url",+ "version",)def __init__(self, **kw: Any) -> None:@@ -84,13 +93,14 @@ class MitreMitigation:_techniques: dict[str, MitreTechnique] = {}_actors: dict[str, MitreActor] = {}_mitigations: dict[str, MitreMitigation] = {}-_tactic_map: dict[str, str] = {} # tactic shortname → display name+_tactic_map: dict[str, str] = {} # tactic shortname → display name_loaded = False_load_time: float = 0.0# ─── Loader ───────────────────────────────────────────────────────────────────+def _parse_stix_bundle(bundle: dict[str, Any]) -> None:"""Parse a STIX 2.1 ATT&CK bundle and populate in-memory indexes."""global _loaded, _load_time@@ -109,7 +119,6 @@ def _parse_stix_bundle(bundle: dict[str, Any]) -> None:tactic_objs[shortname] = obj# Relationship maps- tech_tactic: dict[str, list[str]] = {}tech_mitigations: dict[str, list[str]] = {}actor_techniques: dict[str, list[str]] = {}mitigation_techniques: dict[str, list[str]] = {}@@ -135,24 +144,19 @@ def _parse_stix_bundle(bundle: dict[str, Any]) -> None:for obj in objects:if obj.get("type") != "attack-pattern":continue- ext = obj.get("x_mitre_", {})is_deprecated = obj.get("x_mitre_deprecated", False) or obj.get("revoked", False)if is_deprecated:continuestix_id = obj["id"]ext_refs = obj.get("external_references", [])- attck_ref = next(- (r for r in ext_refs if r.get("source_name") == "mitre-attack"), {}- )+ attck_ref = next((r for r in ext_refs if r.get("source_name") == "mitre-attack"), {})tech_id = attck_ref.get("external_id", "")if not tech_id:continuekill_chain_phases = obj.get("kill_chain_phases", [])- tactic_ids = [- p["phase_name"] for p in kill_chain_phases if p.get("kill_chain_name") == "mitre-attack"- ]+ tactic_ids = [p["phase_name"] for p in kill_chain_phases if p.get("kill_chain_name") == "mitre-attack"]tactic_names = [_tactic_map.get(t, t) for t in tactic_ids]parent_id = None@@ -161,9 +165,7 @@ def _parse_stix_bundle(bundle: dict[str, Any]) -> None:parent_id = tech_id.split(".")[0]mitigation_ids = tech_mitigations.get(stix_id, [])- mitigation_names = [- id_to_obj.get(mid, {}).get("name", mid) for mid in mitigation_ids- ]+ mitigation_names = [id_to_obj.get(mid, {}).get("name", mid) for mid in mitigation_ids]# Detection notes from x_mitre_detectiondetection = obj.get("x_mitre_detection", "")@@ -282,12 +284,17 @@ async def load_attck_corpus(force_reload: bool = False) -> None:def _load_stub_corpus() -> None:"""Populate a minimal stub corpus when the full bundle is unavailable."""global _loaded, _load_time+ from app.tools.mitre import (+ _MITRE_MITIGATIONS as MITS,+ )from app.tools.mitre import (_MITRE_TACTICS as TACTICS,+ )+ from app.tools.mitre import (_MITRE_TECHNIQUES as TECHS,- _MITRE_MITIGATIONS as MITS,)- _tactic_map.update({k: v for k, v in TACTICS.items()})++ _tactic_map.update(dict(TACTICS.items()))for tid, info in TECHS.items():tactic_id = info["tactic"]_techniques[tid] = MitreTechnique(@@ -312,6 +319,7 @@ def _load_stub_corpus() -> None:# ─── Qdrant Embedding ─────────────────────────────────────────────────────────+async def embed_techniques_into_qdrant(qdrant_url: str,openai_api_key: str,@@ -325,9 +333,9 @@ async def embed_techniques_into_qdrant(await load_attck_corpus()try:+ import openaifrom qdrant_client import AsyncQdrantClientfrom qdrant_client.models import Distance, PointStruct, VectorParams- import openaiexcept ImportError as exc:logger.warning("Qdrant/OpenAI client not available for ATT&CK embedding", error=str(exc))return@@ -352,10 +360,7 @@ async def embed_techniques_into_qdrant(for i in range(0, total, _EMBED_BATCH_SIZE):batch = techniques_list[i : i + _EMBED_BATCH_SIZE]- texts = [- f"{t.id} {t.name}: {t.description or ''} Tactics: {', '.join(t.tactic_names or [])}"- for t in batch- ]+ texts = [f"{t.id} {t.name}: {t.description or ''} Tactics: {', '.join(t.tactic_names or [])}" for t in batch]try:resp = await oai.embeddings.create(model="text-embedding-3-large",@@ -375,7 +380,7 @@ async def embed_techniques_into_qdrant("url": t.url,},)- for t, vec in zip(batch, vectors)+ for t, vec in zip(batch, vectors, strict=False)]await qdrant.upsert(collection_name=collection, points=points)embedded += len(batch)@@ -403,8 +408,8 @@ async def semantic_technique_search(Returns the top_k most relevant techniques."""try:- from qdrant_client import AsyncQdrantClientimport openai+ from qdrant_client import AsyncQdrantClientexcept ImportError:return []@@ -451,6 +456,7 @@ async def semantic_technique_search(# ─── Public Lookup API ────────────────────────────────────────────────────────+def get_technique(technique_id: str) -> dict[str, Any]:"""Return full technique details by ATT&CK ID (e.g. 'T1059' or 'T1059.001')."""tech = _techniques.get(technique_id)@@ -490,18 +496,14 @@ def search_techniques_by_name(keyword: str, limit: int = 20) -> list[dict[str, Adef get_techniques_by_tactic(tactic_name: str) -> list[dict[str, Any]]:"""Return all techniques belonging to a given tactic."""tactic_lower = tactic_name.lower()- return [- t.to_dict()- for t in _techniques.values()- if any(tn.lower() == tactic_lower for tn in (t.tactic_names or []))- ]+ return [t.to_dict() for t in _techniques.values() if any(tn.lower() == tactic_lower for tn in (t.tactic_names or []))]def get_coverage_summary() -> dict[str, Any]:"""Return a summary of loaded ATT&CK data."""tactic_counts: dict[str, int] = {}for tech in _techniques.values():- for tname in (tech.tactic_names or []):+ for tname in tech.tactic_names or []:tactic_counts[tname] = tactic_counts.get(tname, 0) + 1return {"total_techniques": len(_techniques),@@ -521,6 +523,6 @@ def map_techniques_to_kill_chain(technique_ids: list[str]) -> dict[str, list[strif tech is None:result.setdefault("Unknown", []).append(tid)continue- for tname in (tech.tactic_names or ["Unknown"]):+ for tname in tech.tactic_names or ["Unknown"]:result.setdefault(tname, []).append(f"{tid}: {tech.name}")return resultdiff --git a/services/agents/tests/test_mitre_accuracy.py b/services/agents/tests/test_mitre_accuracy.pyindex 0144971bc..76e237aaf 100644--- a/services/agents/tests/test_mitre_accuracy.py+++ b/services/agents/tests/test_mitre_accuracy.py@@ -19,9 +19,11 @@ and how it differs from a third-party leaderboard score.Run:pytest services/agents/tests/test_mitre_accuracy.py -v- # or via the public eval harness:- python scripts/run_evals.py --count 200 --report eval_report.json+ # or via the public eval harness (writes a JSON report; dataset size is+ # fixed by eval_data/synthetic_incidents.json, so there is no --count):+ python scripts/run_evals.py --out eval_report.json"""+from __future__ import annotationsimport json@@ -42,8 +44,7 @@ _DATASET_PATH = _TESTS_DIR / "eval_data" / "synthetic_incidents.json"def _load_dataset() -> list[dict[str, Any]]:if not _DATASET_PATH.exists():raise FileNotFoundError(- f"Synthetic incidents dataset missing at {_DATASET_PATH}. "- f"Run `python3 scripts/generate_eval_incidents.py` to regenerate."+ f"Synthetic incidents dataset missing at {_DATASET_PATH}. Run `python3 scripts/generate_eval_incidents.py` to regenerate.")with _DATASET_PATH.open() as f:return json.load(f)@@ -87,71 +88,218 @@ _TACTIC_NAMES: dict[str, str] = {_TACTIC_KEYWORDS: dict[str, list[str]] = {"TA0001": [- "initial access", "phishing", "spear-phish", "exploit", "watering hole",- "supply chain", "valid account", "external remote service", "drive-by",- "usb", "spear", "oauth consent", "social engineering", "social-engineering",- "vpn login", "new geography", "compromised npm", "container image",+ "initial access",+ "phishing",+ "spear-phish",+ "exploit",+ "watering hole",+ "supply chain",+ "valid account",+ "external remote service",+ "drive-by",+ "usb",+ "spear",+ "oauth consent",+ "social engineering",+ "social-engineering",+ "vpn login",+ "new geography",+ "compromised npm",+ "container image","wire transfer",],"TA0002": [- "execution", "powershell", "cmd.exe", "script", "macro", "python", "node",- "certutil", "wmi", "wmic", "mshta", "process hollow", "process create",- "npm", "post-install", "container with", "docker run", "javascript",- "stage-2 payload", "vba", "browser exploitation", "drive-by",+ "execution",+ "powershell",+ "cmd.exe",+ "script",+ "macro",+ "python",+ "node",+ "certutil",+ "wmi",+ "wmic",+ "mshta",+ "process hollow",+ "process create",+ "npm",+ "post-install",+ "container with",+ "docker run",+ "javascript",+ "stage-2 payload",+ "vba",+ "browser exploitation",+ "drive-by",],"TA0003": [- "persistence", "registry run", "scheduled task", "startup", "service",- "implant", "backdoor", "rootkit", "firmware", "uefi", "cron", "wmi event",- "permanent wmi", "office add-in", "vsto", "outlook startup",+ "persistence",+ "registry run",+ "scheduled task",+ "startup",+ "service",+ "implant",+ "backdoor",+ "rootkit",+ "firmware",+ "uefi",+ "cron",+ "wmi event",+ "permanent wmi",+ "office add-in",+ "vsto",+ "outlook startup",],"TA0004": [- "privilege escalation", "escalation", "escalate", "container escape",- "privileged pod", "bypass", "elevation", "sudo", "uac bypass", "uac",- "fodhelper", "suid", "metadata service",+ "privilege escalation",+ "escalation",+ "escalate",+ "container escape",+ "privileged pod",+ "bypass",+ "elevation",+ "sudo",+ "uac bypass",+ "uac",+ "fodhelper",+ "suid",+ "metadata service",],"TA0005": [- "defense evasion", "obfuscat", "fileless", "memory-only", "memory only",- "hollowing", "side-load", "dll", "certutil", "masquerad", "encode", "pack",- "log cleared", "wevtutil", "journalctl", "vacuum", "indicator removal",- "tampering", "stop defender", "stop crowdstrike", "stop sysmon",+ "defense evasion",+ "obfuscat",+ "fileless",+ "memory-only",+ "memory only",+ "hollowing",+ "side-load",+ "dll",+ "certutil",+ "masquerad",+ "encode",+ "pack",+ "log cleared",+ "wevtutil",+ "journalctl",+ "vacuum",+ "indicator removal",+ "tampering",+ "stop defender",+ "stop crowdstrike",+ "stop sysmon","secure boot",],"TA0006": [- "credential", "brute force", "brute-force", "kerberoast", "dcsync",- "lsass", "minidump", "dump", "harvest", "password reset", "password spray",- "credential spray", "saml", "oauth", "ntlm", "mimikatz", "pat",- "personal access token", "refresh token", "imds", "session token",- "stolen session", "tgs",+ "credential",+ "brute force",+ "brute-force",+ "kerberoast",+ "dcsync",+ "lsass",+ "minidump",+ "dump",+ "harvest",+ "password reset",+ "password spray",+ "credential spray",+ "saml",+ "oauth",+ "ntlm",+ "mimikatz",+ "pat",+ "personal access token",+ "refresh token",+ "imds",+ "session token",+ "stolen session",+ "tgs",],"TA0007": [- "discovery", "enumerat", "scan", "account discovery", "network share",- "recon", "replication", "ldap", "bloodhound", "smb share", "share enum",+ "discovery",+ "enumerat",+ "scan",+ "account discovery",+ "network share",+ "recon",+ "replication",+ "ldap",+ "bloodhound",+ "smb share",+ "share enum","system info",],"TA0008": [- "lateral movement", "lateral", "rdp", "pass-the-hash", "pass the hash",- "remote service", "pivoting", "ssh", "smb scan", "wmic /node",+ "lateral movement",+ "lateral",+ "rdp",+ "pass-the-hash",+ "pass the hash",+ "remote service",+ "pivoting",+ "ssh",+ "smb scan",+ "wmic /node","wmi remote",],"TA0009": [- "collection", "data from local", "screenshot", "keylog", "clipboard",- "bulk download", "pii", "customer record", "mailbox export", "pst",- "private repo", "private repos",+ "collection",+ "data from local",+ "screenshot",+ "keylog",+ "clipboard",+ "bulk download",+ "pii",+ "customer record",+ "mailbox export",+ "pst",+ "private repo",+ "private repos",],"TA0010": [- "exfiltrat", "c2 channel", "cloud storage", "dns tunnel", "ftp",- "upload", "egress", "google drive", "drive upload", "personal drive",- "transfer to", "s3 bucket", "s3://", "data egress",+ "exfiltrat",+ "c2 channel",+ "cloud storage",+ "dns tunnel",+ "ftp",+ "upload",+ "egress",+ "google drive",+ "drive upload",+ "personal drive",+ "transfer to",+ "s3 bucket",+ "s3://",+ "data egress",],"TA0011": [- "command and control", "c2", "beacon", "c&c", "dga",- "domain generation", "dns query", "covert channel", "cobalt strike",- "https beacon", "ja3",+ "command and control",+ "c2",+ "beacon",+ "c&c",+ "dga",+ "domain generation",+ "dns query",+ "covert channel",+ "cobalt strike",+ "https beacon",+ "ja3",],"TA0040": [- "impact", "ransom", "encrypt", "wipe", "destroy", "disrupt",- "defacement", "miner", "cryptomine", "xmrig", "ddos", "syn flood",- "wire transfer", "$250", "bec",+ "impact",+ "ransom",+ "encrypt",+ "wipe",+ "destroy",+ "disrupt",+ "defacement",+ "miner",+ "cryptomine",+ "xmrig",+ "ddos",+ "syn flood",+ "wire transfer",+ "$250",+ "bec",],}@@ -170,6 +318,7 @@ def extract_tactics_from_text(text: str) -> set[str]:# Accuracy evaluation# ---------------------------------------------------------------------------+class MitreAccuracyResult:def __init__(self) -> None:self.total = 0@@ -260,6 +409,7 @@ def evaluate_mitre_accuracy(threshold: float = 0.80) -> MitreAccuracyResult:# pytest tests# ---------------------------------------------------------------------------+class TestMitreAccuracy(unittest.TestCase):"""Offline MITRE tactic accuracy evaluation across the synthetic dataset."""@@ -273,8 +423,7 @@ class TestMitreAccuracy(unittest.TestCase):self.assertGreaterEqual(result.accuracy,0.80,- f"MITRE tactic accuracy {result.accuracy:.1%} is below the 80% threshold.\n"- + result.to_json()[:4000],+ f"MITRE tactic accuracy {result.accuracy:.1%} is below the 80% threshold.\n" + result.to_json()[:4000],)def test_dataset_minimum_size(self) -> None:@@ -282,8 +431,7 @@ class TestMitreAccuracy(unittest.TestCase):self.assertGreaterEqual(len(SYNTHETIC_INCIDENTS_DATA),200,- f"Eval dataset has only {len(SYNTHETIC_INCIDENTS_DATA)} incidents; "- f"need ≥200 for Phase-1C.",+ f"Eval dataset has only {len(SYNTHETIC_INCIDENTS_DATA)} incidents; need ≥200 for Phase-1C.",)def test_each_incident_has_expected_tactics(self) -> None:@@ -291,12 +439,14 @@ class TestMitreAccuracy(unittest.TestCase):title = inc["title"]tactic_ids = inc["expected_tactics"]self.assertGreater(- len(tactic_ids), 0,+ len(tactic_ids),+ 0,f"Incident '{title[:60]}' has no expected tactic IDs.",)for t in tactic_ids:self.assertIn(- t, _TACTIC_NAMES,+ t,+ _TACTIC_NAMES,f"Unknown tactic ID '{t}' in incident '{title[:60]}'.",)@@ -311,12 +461,17 @@ class TestMitreAccuracy(unittest.TestCase):def test_response_class_values_valid(self) -> None:valid = {- "isolate_host", "disable_account", "block_indicator",- "rollback_change", "escalate", "monitor",+ "isolate_host",+ "disable_account",+ "block_indicator",+ "rollback_change",+ "escalate",+ "monitor",}for inc in SYNTHETIC_INCIDENTS_DATA:self.assertIn(- inc["response_class"], valid,+ inc["response_class"],+ valid,f"Bad response_class: {inc['response_class']}",)@@ -326,7 +481,8 @@ class TestMitreAccuracy(unittest.TestCase):for inc in SYNTHETIC_INCIDENTS_DATA:all_tactics.update(inc["expected_tactics"])self.assertGreaterEqual(- len(all_tactics & set(_TACTIC_NAMES)), 10,+ len(all_tactics & set(_TACTIC_NAMES)),+ 10,f"Only {len(all_tactics)} tactics covered: {sorted(all_tactics)}",)diff --git a/services/purple-team/app/services/coverage.py b/services/purple-team/app/services/coverage.pyindex 86a48643f..551cea0ea 100644--- a/services/purple-team/app/services/coverage.py+++ b/services/purple-team/app/services/coverage.py@@ -1,4 +1,5 @@"""ATT&CK coverage computation from execution history."""+from __future__ import annotationsimport logging@@ -93,11 +94,7 @@ def build_coverage_matrix(total_techniques = len(by_technique)tested = sum(1 for ts in by_technique.values() if ts)- detected_techniques = sum(- 1- for tid, ts in by_technique.items()- if any(t.get("detected") for t in ts)- )+ detected_techniques = sum(1 for tid, ts in by_technique.items() if any(t.get("detected") for t in ts))overall = (tested / total_techniques) if total_techniques else 0.0tactics = [t for t in TACTIC_ORDER if t in tactic_techniques]@@ -107,7 +104,7 @@ def build_coverage_matrix(return {"tactics": tactics,- "techniques": {k: v for k, v in tactic_techniques.items()},+ "techniques": dict(tactic_techniques),"summary": {"total_techniques": total_techniques,"tested_techniques": tested,diff --git a/services/purple-team/tests/__init__.py b/services/purple-team/tests/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/purple-team/tests/test_coverage.py b/services/purple-team/tests/test_coverage.pynew file mode 100644index 000000000..17fbd10e3--- /dev/null+++ b/services/purple-team/tests/test_coverage.py@@ -0,0 +1,147 @@+"""Unit tests for build_coverage_matrix — pure stdlib, no infra."""++from __future__ import annotations++import pytest++from app.services.coverage import TACTIC_ORDER, build_coverage_matrix+++def _exec(+ technique_id: str,+ tactic: str,+ *,+ status: str = "success",+ detected: bool = False,+ test_name: str = "",+) -> dict:+ return {+ "technique_id": technique_id,+ "tactic": tactic,+ "status": status,+ "detected": detected,+ "test_name": test_name or f"test for {technique_id}",+ }+++class TestBuildCoverageMatrix:+ def test_empty_input_returns_zero_coverage(self) -> None:+ result = build_coverage_matrix([])+ assert result["tactics"] == []+ assert result["techniques"] == {}+ assert result["summary"] == {+ "total_techniques": 0,+ "tested_techniques": 0,+ "detected_techniques": 0,+ "overall_coverage": 0.0,+ }++ def test_executions_without_technique_id_are_skipped(self) -> None:+ result = build_coverage_matrix([{"tactic": "execution"}])+ assert result["summary"]["total_techniques"] == 0++ def test_single_passing_execution_with_detection(self) -> None:+ result = build_coverage_matrix(+ [_exec("T1078", "initial-access", status="success", detected=True)]+ )+ techs = result["techniques"]["initial-access"]+ assert len(techs) == 1+ t = techs[0]+ assert t["technique_id"] == "T1078"+ assert t["test_count"] == 1+ assert t["pass_count"] == 1+ assert t["detected"] == 1+ assert t["coverage"] == 1.0++ s = result["summary"]+ assert s["total_techniques"] == 1+ assert s["tested_techniques"] == 1+ assert s["detected_techniques"] == 1+ assert s["overall_coverage"] == 1.0++ def test_partial_pass_partial_detect(self) -> None:+ result = build_coverage_matrix(+ [+ _exec("T1059", "execution", status="success", detected=True),+ _exec("T1059", "execution", status="failure", detected=False),+ _exec("T1059", "execution", status="success", detected=False),+ ]+ )+ t = result["techniques"]["execution"][0]+ assert t["test_count"] == 3+ assert t["pass_count"] == 2+ assert t["detected"] == 1+ assert t["coverage"] == round(2 / 3, 3)++ def test_tactic_ordering_follows_attack_order(self) -> None:+ # Provide tactics out of canonical order+ result = build_coverage_matrix(+ [+ _exec("T1486", "impact"),+ _exec("T1059", "execution"),+ _exec("T1078", "initial-access"),+ ]+ )+ # Expect canonical ATT&CK order: initial-access, execution, impact+ idx = {tactic: i for i, tactic in enumerate(TACTIC_ORDER)}+ ordered = result["tactics"]+ assert ordered == sorted(ordered, key=lambda t: idx.get(t, 999))+ assert ordered[0] == "initial-access"+ assert ordered[-1] == "impact"++ def test_unknown_tactics_appended_at_end_alphabetically(self) -> None:+ result = build_coverage_matrix(+ [+ _exec("T1234", "made-up-tactic"),+ _exec("T5678", "another-fake"),+ _exec("T1078", "initial-access"),+ ]+ )+ # Known tactic comes first, unknowns appended (sorted)+ assert result["tactics"][0] == "initial-access"+ assert "made-up-tactic" in result["tactics"][1:]+ assert "another-fake" in result["tactics"][1:]++ def test_techniques_within_tactic_are_sorted(self) -> None:+ result = build_coverage_matrix(+ [+ _exec("T1110", "credential-access"),+ _exec("T1078", "credential-access"),+ _exec("T1003", "credential-access"),+ ]+ )+ ids = [t["technique_id"] for t in result["techniques"]["credential-access"]]+ assert ids == sorted(ids)++ def test_summary_detected_count_uses_any_detection(self) -> None:+ result = build_coverage_matrix(+ [+ _exec("T1078", "initial-access", detected=False),+ _exec("T1078", "initial-access", detected=True),+ _exec("T1059", "execution", detected=False),+ ]+ )+ # T1078 had at least one detection -> counted; T1059 had none.+ assert result["summary"]["detected_techniques"] == 1+ assert result["summary"]["total_techniques"] == 2++ @pytest.mark.parametrize(+ "tactic",+ [+ "initial-access",+ "execution",+ "persistence",+ "privilege-escalation",+ "defense-evasion",+ "credential-access",+ "discovery",+ "lateral-movement",+ "collection",+ "command-and-control",+ "exfiltration",+ "impact",+ ],+ )+ def test_all_canonical_tactics_supported(self, tactic: str) -> None:+ result = build_coverage_matrix([_exec(f"T-{tactic}", tactic)])+ assert tactic in result["tactics"]