Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

Make the quick start run the real pipeline, and prove it (#726)

Beenu Arora60117ec0d5a1
diff --git a/.github/workflows/golden-pipeline.yml b/.github/workflows/golden-pipeline.yml
new file mode 100644
index 000000000..65cbf4500
--- /dev/null
+++ b/.github/workflows/golden-pipeline.yml
@@ -0,0 +1,117 @@
+name: Golden pipeline
+
+# The claim "AiSOC works end to end" is made by exactly one test, and this
+# workflow is what makes it true on every change.
+#
+# It boots the CORE profile exactly as `make up` does, then pushes one real
+# event through the real spine — ingest, Kafka, fusion, detection, promotion,
+# Postgres — and reads the alert back from the public API. Nothing is stubbed
+# and no stage is reached past, because a test that bypasses a component
+# cannot tell you that component works.
+#
+# Also runs the README's own quick-start commands, so documentation drift
+# fails the build rather than a user's first evening.
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: golden-pipeline-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ golden:
+ name: One real event through the real pipeline
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+
+ - name: Set up Python
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.12'
+
+ # Disk exhaustion inside the runner corrupts Kafka's log dir, and the
+ # broker then reports healthy while refusing every request — a failure
+ # that reads as "the pipeline is broken" and costs an afternoon. The
+ # runner ships with several GB of unused toolchains.
+ - name: Reclaim disk before starting the stack
+ run: |
+ set -euo pipefail
+ echo "before: $(df -h / | awk 'NR==2{print $4}') free"
+ sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc || true
+ echo "after: $(df -h / | awk 'NR==2{print $4}') free"
+
+ - name: Build the CORE images from this commit
+ run: |
+ set -euo pipefail
+ docker compose build ingest-worker fusion api
+
+ - name: Start the CORE stack (what `make up` does)
+ run: |
+ set -euo pipefail
+ docker compose up -d postgres redis zookeeper kafka
+ docker compose up -d api ingest-worker fusion
+
+ - name: Wait for the stack to be usable
+ run: |
+ set -euo pipefail
+ for i in $(seq 1 60); do
+ api=$(curl -s -o /dev/null -m 5 -w '%{http_code}' http://localhost:8000/health || echo 000)
+ ing=$(curl -s -o /dev/null -m 5 -w '%{http_code}' http://localhost:8081/health || echo 000)
+ fus=$(curl -s -o /dev/null -m 5 -w '%{http_code}' http://localhost:8003/health || echo 000)
+ echo "attempt $i: api=$api ingest=$ing fusion=$fus"
+ [ "$api$ing$fus" = "200200200" ] && exit 0
+ sleep 5
+ done
+ echo "::error::services did not become healthy"
+ docker compose ps
+ docker compose logs --tail=80
+ exit 1
+
+ # The doctor is a shipped user-facing command. If it cannot read its own
+ # healthy stack, it is worse than nothing — it teaches users to distrust
+ # it. So it runs here against a stack we know is good.
+ - name: make doctor reports a healthy stack
+ run: ./scripts/doctor.sh
+
+ - name: Golden pipeline — one real event end to end
+ run: python3 tests/e2e/golden_pipeline/run_golden_pipeline.py
+
+ # A green run proves the pipeline works. It does not prove the test
+ # would notice if it stopped working, which is the property that makes
+ # the gate worth having.
+ - name: The gate fails when the pipeline is broken
+ run: |
+ set -euo pipefail
+ docker compose stop fusion
+ if AISOC_GOLDEN_TIMEOUT=25 python3 tests/e2e/golden_pipeline/run_golden_pipeline.py; then
+ echo "::error::the golden pipeline passed with fusion stopped — the gate proves nothing"
+ exit 1
+ fi
+ echo "confirmed: the gate fails when the spine is broken"
+ docker compose start fusion
+
+ - name: Published figures still match the tree
+ run: python3 scripts/project_stats.py --check
+
+ - name: Diagnostics on failure
+ if: failure()
+ run: |
+ docker compose ps || true
+ for s in kafka ingest-worker fusion api; do
+ echo "── $s ──"; docker compose logs --tail=60 "$s" || true
+ done
+
+ - name: Tear down
+ if: always()
+ run: docker compose down -v || true
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index 54021008d..0890714f6 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -105,8 +105,19 @@ jobs:
- name: Build fusion + ingest from source
run: docker compose build fusion ingest-worker
- - name: Boot stack
- run: docker compose up -d
+ # This job verifies the FULL architecture — it asserts below that the
+ # ClickHouse event lake is populated — so it must boot the `full`
+ # profile. ClickHouse, Neo4j and the rest moved behind that profile so
+ # a plain `docker compose up` is the 10-service CORE pipeline.
+ #
+ # The two flags travel with the profile: the lake writer and the graph
+ # writer target stores that only exist in `full`, and in CORE they
+ # default off rather than retrying against a host that is not there.
+ - name: Boot stack (full profile — this job asserts on the lake)
+ env:
+ AISOC_LAKE_WRITER_ENABLED: "true"
+ AISOC_GRAPH_ENABLED: "true"
+ run: docker compose --profile full up -d
- name: Run spine test
run: python3 scripts/integration/spine_test.py
diff --git a/Makefile b/Makefile
index 240adf213..0147b9c0f 100644
--- a/Makefile
+++ b/Makefile
@@ -1,43 +1,147 @@
-# Top-level Makefile — convenience targets for the AiSOC repo.
+# AiSOC — one command per thing you actually want to do.
#
-# The bulk of the build / test / deploy surface still lives in the
-# per-service Dockerfiles and CI workflows. This Makefile only carries
-# the few targets that benefit from being a single command on a
-# developer laptop or in CI.
+# There is exactly one canonical answer to "how do I run this", and it lives
+# here. `docker compose` still works directly; these targets are the supported
+# spelling and are what the README and CI use, so they cannot drift from the
+# documentation without a red build.
#
-# Phase 4.3 (papers + demo) lands the `make papers` target the public
-# white-paper README has been promising since v8.0.
+# Profiles (see docs/architecture/README.md):
+# core — default. postgres, redis, kafka, ingest, fusion, api, web, agents.
+# The smallest deployment that can take an event and produce an
+# alert. ~6GB RAM.
+# full — core plus the event lake (ClickHouse), entity graph (Neo4j),
+# vector store (Qdrant), search (OpenSearch), enrichment, connectors
+# and the LLM gateway. ~12GB RAM.
+# demo — core plus clearly-labelled synthetic data.
.DEFAULT_GOAL := help
-PYTHON ?= python3
+PYTHON ?= python3
+COMPOSE ?= docker compose
+PROFILE ?=
-.PHONY: help papers papers-install demo-script
+# `--profile full` when PROFILE=full, nothing otherwise.
+PROFILE_ARG := $(if $(PROFILE),--profile $(PROFILE),)
+
+.PHONY: help install up up-full down restart status doctor smoke demo logs clean \
+ test test-unit test-integration test-e2e stats papers papers-install demo-script
help:
- @echo "Common targets:"
- @echo " make papers — render every public white paper to PDF"
- @echo " make papers-install — install the Python deps render_white_paper needs"
- @echo " make demo-script — emit the 90s demo screencast shot list"
@echo ""
- @echo "Service-level targets live under each service directory:"
- @echo " services/api, services/agents, apps/web, apps/docs, ..."
-
-# --- Public papers ---------------------------------------------------------
-# `make papers` rebuilds every PDF under apps/web/public/papers/ from the
-# matching markdown source under apps/web/content/papers/. The script is
-# idempotent — it overwrites existing PDFs in place — and the CI workflow
-# `.github/workflows/papers.yml` runs the same command on push to main.
+ @echo " Getting started"
+ @echo " make install Install prerequisites, configure, start, and verify"
+ @echo " make up Start the CORE stack (postgres, kafka, ingest, fusion, api, web)"
+ @echo " make up-full Start CORE plus lake, graph, vector, search and enrichment"
+ @echo " make smoke Push one real event through the pipeline and check it becomes an alert"
+ @echo " make doctor Diagnose the deployment and say what to fix"
+ @echo ""
+ @echo " Running it"
+ @echo " make status Show every service and its health"
+ @echo " make logs Follow logs (SERVICE=fusion to narrow)"
+ @echo " make restart Restart the stack"
+ @echo " make down Stop the stack, keep the data"
+ @echo " make clean Stop the stack and delete all volumes"
+ @echo " make demo Load clearly-labelled synthetic data"
+ @echo ""
+ @echo " Developing"
+ @echo " make test Unit tests for every service"
+ @echo " make test-e2e The golden pipeline against a running stack"
+ @echo " make stats Recount the figures the README publishes"
+ @echo ""
+
+# ── Getting started ────────────────────────────────────────────────────────
+
+install:
+ ./install.sh
+
+up:
+ $(COMPOSE) up -d
+ @echo ""
+ @echo "Waiting for services to become healthy…"
+ @$(MAKE) --no-print-directory _wait
+ @echo ""
+ @echo " Console: http://localhost:3000"
+ @echo " API: http://localhost:8000/docs"
+ @echo ""
+ @echo "Prove the pipeline works: make smoke"
+
+# The lake and graph writers target stores that exist only in `full`, so the
+# flags travel with the profile. In CORE they default off rather than
+# retrying forever against a host that is not there.
+up-full:
+ AISOC_LAKE_WRITER_ENABLED=true AISOC_GRAPH_ENABLED=true $(COMPOSE) --profile full up -d
+ @$(MAKE) --no-print-directory _wait
+ @echo "Full profile up. Prove the pipeline works: make smoke"
+
+# Waits on the services that declare a healthcheck. Silent on success.
+_wait:
+ @for i in $$(seq 1 60); do \
+ unhealthy=$$($(COMPOSE) ps --format '{{.Service}} {{.Health}}' 2>/dev/null | awk '$$2=="starting"||$$2=="unhealthy"{print $$1}'); \
+ [ -z "$$unhealthy" ] && exit 0; \
+ sleep 3; \
+ done; \
+ echo "Still not healthy after 3 minutes: $$unhealthy"; \
+ echo "Run 'make doctor' to find out why."; \
+ exit 1
+
+down:
+ $(COMPOSE) --profile full --profile monitoring --profile chatops --profile extras --profile osquery down
+
+restart: down up
+
+status:
+ @$(COMPOSE) ps --format 'table {{.Service}}\t{{.State}}\t{{.Status}}\t{{.Ports}}'
+
+doctor:
+ @./scripts/doctor.sh $(if $(filter full,$(PROFILE)),--full,)
+
+# The golden pipeline. One real event, through the real spine, observed from
+# outside. This is the only claim of "it works" the project makes.
+smoke:
+ @$(PYTHON) tests/e2e/golden_pipeline/run_golden_pipeline.py
+
+demo:
+ @echo "Loading synthetic demo data. Every row is tagged is_synthetic=true"
+ @echo "and the console labels it. See 'Real vs synthetic data' in README.md."
+ $(COMPOSE) run --rm -e AISOC_ALLOW_SEED=1 api python -m app.scripts.seed_demo
+
+logs:
+ $(COMPOSE) logs -f --tail=200 $(SERVICE)
+
+clean:
+ $(COMPOSE) --profile full --profile monitoring --profile chatops --profile extras --profile osquery down -v
+ @echo "Stack stopped and volumes deleted."
+
+# ── Tests ──────────────────────────────────────────────────────────────────
+
+test: test-unit
+
+test-unit:
+ @set -e; for svc in api agents fusion actions connectors; do \
+ if [ -d "services/$$svc/tests" ]; then \
+ echo "── services/$$svc"; \
+ (cd "services/$$svc" && $(PYTHON) -m pytest tests/ -q) || exit 1; \
+ fi; \
+ done
+
+test-integration:
+ @$(PYTHON) -m pytest tests/ -q --ignore=tests/e2e
+
+test-e2e: smoke
+
+# ── Project figures ────────────────────────────────────────────────────────
+# Every quantitative claim in the README is produced by this, so a figure
+# cannot be edited by hand into something the tree does not support.
+stats:
+ @$(PYTHON) scripts/project_stats.py
+
+# ── Papers + demo script (pre-existing) ────────────────────────────────────
+
papers:
$(PYTHON) scripts/render_white_paper.py --all
papers-install:
$(PYTHON) -m pip install --quiet 'markdown>=3.5' 'weasyprint>=60'
-# --- 90s demo screencast --------------------------------------------------
-# Emit (to stdout) the shot list / narration / timings that drive the
-# 90-second product walkthrough. The recorder uses this file as the
-# canonical script so the cut never drifts from what the engineering team
-# considers the on-message demo.
demo-script:
@cat docs/demo/SCREENCAST_SHOTLIST.md
diff --git a/README.md b/README.md
index 0496729b3..9c5bf8dcb 100644
--- a/README.md
+++ b/README.md
@@ -4,247 +4,228 @@
# AiSOC
-An open-source, self-hostable AI SOC. The agent's prompts, tool calls, and rationale are logged step-by-step and replayable. MIT-licensed.
+**An open-source, self-hostable AI Security Operations Center.** It ingests your security telemetry, detects and correlates threats, investigates them with AI agents whose reasoning is fully auditable, and proposes responses a human approves.
[![License: MIT](https://img.shields.io/badge/License-MIT-22c55e.svg?style=flat-square)](https://opensource.org/licenses/MIT)
[![Version](https://img.shields.io/badge/version-8.1.0-f59e0b?style=flat-square)](CHANGELOG.md)
[![CI](https://img.shields.io/github/actions/workflow/status/beenuar/AiSOC/ci.yml?branch=main&label=CI&style=flat-square)](https://github.com/beenuar/AiSOC/actions/workflows/ci.yml)
[![CodeQL](https://img.shields.io/github/actions/workflow/status/beenuar/AiSOC/codeql.yml?branch=main&label=CodeQL&style=flat-square)](https://github.com/beenuar/AiSOC/actions/workflows/codeql.yml)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/beenuar/AiSOC/badge)](https://securityscorecards.dev/viewer/?uri=github.com/beenuar/AiSOC)
-[![Discussions](https://img.shields.io/github/discussions/beenuar/AiSOC?style=flat-square&label=discussions&color=ec4899)](https://github.com/beenuar/AiSOC/discussions)
-[![Open in GitHub Codespaces](https://img.shields.io/badge/Open%20in-Codespaces-24292e?style=for-the-badge&logo=github)](https://codespaces.new/beenuar/AiSOC?quickstart=1)
-[![Docs](https://img.shields.io/badge/Docs-beenuar.github.io-7b2bbe?style=for-the-badge&logo=readthedocs&logoColor=white)](https://beenuar.github.io/AiSOC/)
-[![Render demo (one-click)](https://img.shields.io/badge/Render-one--click-46e3b7?style=for-the-badge&logo=render&logoColor=white)](https://render.com/deploy?repo=https://github.com/beenuar/AiSOC)
-
-<sub>Codespaces is the zero-install way to drive the real stack in a browser — nothing to install locally, nothing to clean up. Full documentation is published from this repo to <a href="https://beenuar.github.io/AiSOC/">beenuar.github.io/AiSOC</a>.</sub>
-
-<br />
-
-<a href="apps/web/public/demo/"><img src="apps/web/public/demo-thumbnail.svg" alt="90-second AiSOC product walkthrough — agent investigating the seeded LockBit 3.0 case" width="720" /></a>
-
-<sub><em>90-second walkthrough — agent investigates the seeded LockBit 3.0 case end-to-end. <strong>This is a placeholder diagram, not a recording.</strong> The shot list is in <a href="docs/demo/SCREENCAST_SHOTLIST.md">docs/demo/SCREENCAST_SHOTLIST.md</a> and the recorder is <a href=".github/workflows/screencast.yml">screencast.yml</a>; the cut ships in v8.2, because recording needs a running stack to point a browser at and the hosted OSS demo is down pending a billing action on the account. Run it yourself with <code>pnpm aisoc:demo</code> and you are looking at the same thing.</em></sub>
+[Docs](https://beenuar.github.io/AiSOC/) · [Architecture](docs/architecture/README.md) · [What actually works](docs/audit/REPOSITORY_REALITY.md) · [Discussions](https://github.com/beenuar/AiSOC/discussions)
</div>
---
-## Try AiSOC in 60 seconds
+## What AiSOC does
-No Docker, no keys, under five seconds:
-
-```bash
-git clone https://github.com/beenuar/AiSOC && cd AiSOC
-pip install -e packages/aisoc-sandbox && aisoc-sandbox demo
```
-
-One alert through the four-stage agent funnel — Detect → Triage → Hunt → Respond — with a deterministic offline reasoner, printing the Investigation Ledger. No API key, no network, nothing to tear down. Prefer not to clone? [Open in Codespaces](https://codespaces.new/beenuar/AiSOC?quickstart=1) and run the same command in the browser. Or pick whichever path matches what you already have:
-
-| If you have… | Run this | What you get |
-|---------------------------------------|----------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------|
-| **npm, and v8.2 has shipped** | `npx aisoc triage --demo` | Batch-scores 200 alerts to escalate / review / suppress with the deterministic triage engine. **Not yet published** — `aisoc` is not on npm today, so this 404s. Builds from [`packages/aisoc-lite/`](packages/aisoc-lite/) meanwhile. |
-| **A browser** (zero install) | [Open in Codespaces](https://codespaces.new/beenuar/AiSOC?quickstart=1) | Browser IDE → `pnpm aisoc:demo --no-open` → click forwarded port `3000`. ~5 min cold. |
-| **Docker + pnpm** | `git clone https://github.com/beenuar/AiSOC && cd AiSOC && pnpm aisoc:demo` | Local stack on Postgres + Redis + Kafka + api + agents + web. Browser opens at `INC-RT-001`. |
-| **Nothing** (clean Linux/macOS/Win) | `curl -fsSL https://raw.githubusercontent.com/beenuar/AiSOC/main/install.sh \| bash` | Bootstraps Docker, Node, pnpm, git for you; then runs `pnpm aisoc:demo`. |
-
-[`aisoc-sandbox`](packages/aisoc-sandbox/) is a zero-dependency, in-memory simulator of the agent funnel. Pick a [bundled scenario](packages/aisoc-sandbox/README.md#bundled-scenarios) (`lateral-movement`, `aws-credential-exfil`, `phishing-payload`, `kubernetes-privesc`, `github-token-theft`) or feed in your own JSON via `--file`. The remaining rows boot the real stack and land you on `/cases/INC-RT-001?tab=ledger` — a LockBit 3.0 ransomware case mid-investigation, with the AI agent's prompts, tool calls, and rationale streaming into the [Investigation Ledger](apps/docs/docs/console/investigation-rail.md). Stop the real stack with `pnpm aisoc:demo:down`.
-
-> **Does the demo still boot on `main`?** Every push runs [`compose-smoke`](https://github.com/beenuar/AiSOC/actions/workflows/compose-smoke.yml) (the same `pnpm aisoc:demo` path you'd run locally) and [`e2e`](https://github.com/beenuar/AiSOC/actions/workflows/e2e.yml) against the seeded console; nightly [`compose-smoke-nightly`](https://github.com/beenuar/AiSOC/actions/workflows/compose-smoke-nightly.yml) repeats it with cold caches. A red badge below is a release-blocker.
->
-> [![Compose Smoke](https://img.shields.io/github/actions/workflow/status/beenuar/AiSOC/compose-smoke.yml?branch=main&label=compose-smoke%20%28main%29&style=flat-square)](https://github.com/beenuar/AiSOC/actions/workflows/compose-smoke.yml)
-> [![Nightly cold cache](https://img.shields.io/github/actions/workflow/status/beenuar/AiSOC/compose-smoke-nightly.yml?branch=main&label=compose-smoke%20%28nightly%2C%20cold%29&style=flat-square)](https://github.com/beenuar/AiSOC/actions/workflows/compose-smoke-nightly.yml)
-> [![E2E](https://img.shields.io/github/actions/workflow/status/beenuar/AiSOC/e2e.yml?branch=main&label=e2e%20%28seeded%20console%29&style=flat-square)](https://github.com/beenuar/AiSOC/actions/workflows/e2e.yml)
-
-Full multi-platform deploy guide is in [`apps/docs/docs/installation.md`](apps/docs/docs/installation.md) (Render, Fly.io, Docker Compose, Kubernetes, Terraform). Production-grade install with full storage tier: [`infra/helm/`](infra/helm/) or [`infra/terraform/`](infra/terraform/).
-
----
-
-## What AiSOC is
-
-AiSOC is a single self-hostable stack that ingests security events, correlates them, runs AI-driven investigation, and surfaces the result in a SOC console. The agent and the substrate are MIT-licensed, so you can read, fork, or replace either of them.
-
-Three properties distinguish it from closed-source AI SOC vendors:
-
-1. **Agent decisions are logged.** The Investigation Ledger stores the LLM prompt, the response, the evidence cited, and the downstream tool calls for every step of every run. Replays are available later.
-2. **The substrate has a public eval harness in CI.** Five suites gate every PR targeting `main` / `develop` — alert reduction is a real measurement against a fixed 1 000-alert stream; three rubric-based suites are substrate self-consistency gates over a deterministic 200-incident dataset (55 templates) with per-template macros; a fifth gate validates the backing telemetry corpus. The [benchmark page](apps/docs/docs/benchmark.md) documents exactly what each suite measures and what it does not.
-3. **You control what leaves your perimeter.** No callbacks to a vendor cloud and no "model improvement" telemetry. With a hosted LLM, evidence is pseudonymized by default (internal IPs, hostnames, emails, paths, secrets, usernames become opaque tokens); run a local model (Ollama/vLLM) for a fully air-gapped path. Exactly what leaves under each mode: [`docs/trust/data-flows.md`](docs/trust/data-flows.md).
-
-The orchestrator is a ~600-line LangGraph in [`services/agents/`](services/agents/). It is small enough to read end-to-end, swap models in, and patch.
-
----
-
-## How AiSOC compares
-
-| Capability | AiSOC | Wazuh | Splunk ES | Closed-source AI SOC |
-|---|---|---|---|---|
-| Open-source license | MIT | GPL-2 | proprietary | proprietary |
-| Self-hostable | yes | yes | enterprise-only | cloud-only |
-| Autonomous AI investigation | LangGraph | no | partial (Splunk AI) | yes |
-| Agent decision audit trail | public Investigation Ledger | n/a | n/a | not published |
-| Public substrate eval harness | CI-gated, reproducible, with synthetic telemetry corpus + per-template macros | n/a | n/a | not published |
-| Detection content | 833 executable firing on the live stream + 6 000-rule provenance-tracked imported library ([truth table](docs/detections/truth-table.md)) | 1 200+ rules | 1 000+ apps | curated |
-| Plugin SDK | Python / TypeScript / Go | YAML rules only | apps | proprietary |
-| Data residency | your infra | your infra | partial | vendor cloud |
-| Pricing | $0 (self-host) | $0 (self-host) | per ingest GB | enterprise |
-
-Closed-source AI SOC vendors ship working products. AiSOC's contribution is making the agent itself open, the per-step decision trail readable, and the substrate gated by a public eval harness on every PR targeting `main` / `develop`.
-
----
-
-## What you'll see in the console
-
-<div align="center">
-
-| <a href="apps/docs/docs/console/queue.md"><img src="apps/web/public/screenshots/01-alerts-queue.svg" alt="Alerts queue with SLA countdowns" width="100%" /></a> | <a href="apps/docs/docs/console/investigation-rail.md"><img src="apps/web/public/screenshots/02-investigation-rail.svg" alt="Investigation Rail with deterministic correlation narrative" width="100%" /></a> |
-|:---:|:---:|
-| **Alerts queue** — server-anchored SLA countdowns, atomic claim, one-click triage. [Docs](apps/docs/docs/console/queue.md) | **Investigation Rail** — narrative, pivot-path entity chips, 6-event timeline, recommended actions. [Docs](apps/docs/docs/console/investigation-rail.md) |
-| <a href="apps/docs/docs/console/rule-tuning.md"><img src="apps/web/public/screenshots/03-hunt-workbench.svg" alt="Natural-language /hunt workbench" width="100%" /></a> | <a href="apps/docs/docs/plugins/overview.md"><img src="apps/web/public/screenshots/04-marketplace.svg" alt="Plugin and detection marketplace" width="100%" /></a> |
-| **`/hunt` workbench** — type a hypothesis in English, get ES&#124;QL / SPL / KQL back, save + schedule. [Docs](apps/docs/docs/console/rule-tuning.md) | **Marketplace** — plugins, playbooks, detections with one-click tenant install. [Docs](apps/docs/docs/plugins/overview.md) |
-
-<sub><em>The four tiles above are SVG placeholders. Real PNG screenshots ship with the next Phase 2 visuals rollup; the [walkthrough video](apps/web/public/demo/) at the top of this README is the canonical reference until then.</em></sub>
-
-</div>
-
----
-
-## Architecture
-
-```mermaid
-flowchart LR
- subgraph Sources["Sources"]
- EDR["EDR / XDR"]
- SIEM["SIEM"]
- Cloud["Cloud APIs"]
- IDP["Identity"]
- Net["Network"]
- end
-
- subgraph Ingest["Ingest & Normalize"]
- Connectors["Connectors\n(Python · 78 vendors)"]
- OsqueryTLS["osquery-tls\n(Python · host telemetry)"]
- IngestSvc["Ingest worker\n(Go · OCSF)"]
- Enrich["Enrichment\n(Go · IOC + Shodan)"]
- end
-
- subgraph Spine["Event Spine"]
- Kafka[("Apache Kafka")]
- end
-
- subgraph Detect["Detect & Reason"]
- Fusion["Fusion\n(Python · ML)"]
- UEBA["UEBA\n(Python · baseline)"]
- Rules["Rule engine\n(Sigma · YARA · KQL)"]
- Agents["AI Agents\n(LangGraph)"]
- end
-
- subgraph Storage["Storage Tier"]
- PG[("PostgreSQL")]
- CH[("ClickHouse")]
- OS[("OpenSearch")]
- QD[("Qdrant")]
- N4[("Neo4j")]
- RD[("Redis")]
- end
-
- subgraph Surface["Surface"]
- API["Core API\n(FastAPI)"]
- Web["Web Console + Responder PWA\n(Next.js)"]
- MCP["MCP Server\n(TS · stdio)"]
- end
-
- Sources --> Connectors --> IngestSvc --> Kafka
- OsqueryTLS --> IngestSvc
- IngestSvc --> Enrich --> Kafka
- Kafka --> Fusion --> Storage
- Kafka --> UEBA --> Kafka
- Kafka --> Rules --> Kafka
- Agents --> Storage
- API --> Storage
- Web --> API
- MCP --> API
+ Your security tools (EDR, cloud, identity, network, SIEM)
+ |
+ v
+ ┌──────────────────────────────────────────────────────┐
+ │ normalize -> detect -> correlate -> investigate -> respond │
+ └──────────────────────────────────────────────────────┘
+ |
+ v
+ SOC analyst: one incident, with the evidence and the reasoning
```
-Full architecture (every service, every storage role, the v1.5 console workbench, and the Investigation Ledger contract) is in [`apps/docs/docs/architecture.md`](apps/docs/docs/architecture.md). The deeper system-design write-up — including ML fusion, the Neo4j-at-ingest schema, and the threat-intel pipeline — lives at [`docs/architecture/SYSTEM_DESIGN.md`](docs/architecture/SYSTEM_DESIGN.md). The full monorepo layout is at [`apps/docs/docs/architecture/overview.md`](apps/docs/docs/architecture/overview.md).
-
----
-
-## What's in the box
-
-A handful of headline capabilities — the rest are catalogued in [`apps/docs/docs/features/`](apps/docs/docs/features/) and indexed at the top of [`apps/docs/docs/intro.md`](apps/docs/docs/intro.md):
+An alert arrives. AiSOC works out whether it matters, groups it with related
+signals, investigates it with an AI agent whose every prompt and tool call is
+recorded, and proposes an action. A human approves before anything executes.
-> **Maturity (v8.1.0 — Wave-2 features, and the gaps behind them).** Every wave-2 backlog item was audited against the tree before any code was written, and the backlog was wrong in both directions: two were already built, four had the capability present with the path that feeds it broken. One inverted what the feature appeared to do — a Slack or Teams **approval authorized nobody**: the bots verified who clicked, logged them, and called the actions service with no approver, so the permission tier and separation of duties were both skipped. The end-to-end spine is wired and CI-gated: ingest → ClickHouse lake → live detection → fused alert → auto-triage → governed response. v8.0 connected capabilities the codebase already contained but never called. Response actions are now **verified against the vendor** rather than assumed from a 200 — an action that reports success while the effect is absent is reported as failed, because that gap is how a SOC comes to believe a host is contained when it is not. Autonomy is governed by **each tenant's own** L0–L4 policy instead of one deployment-wide environment variable. Repeat-alert suppression, shipped in v7.7, **could never fire** — the evidence fingerprint included the alert id, so no repeat ever matched; it now does. Analysts can **hunt the events AiSOC itself ingested** instead of needing an external SIEM. A verdict citing indicators the evidence never contained is demoted to human review rather than auto-closed. Autonomous *response* still defaults to copilot/dry-run: an autonomy policy governs every real execution. The live-agent LLM benchmark is preview (the deterministic-tier scoreboard is CI-gated per PR); substrate eval suites are GA. Every product claim is backed by a failing test — [claim-to-gate matrix](docs/audit/CLAIM_TO_GATE_MATRIX.md): 99 GATED / 9 PARTIAL / 0 NO GATE. Full per-claim status: [`docs/audit/REALITY_REPORT.md`](docs/audit/REALITY_REPORT.md).
+## Quick start
-- **84 click-and-connect data connectors** (EDR/XDR, SIEM, NDR, cloud, CNAPP, identity, SaaS, VCS, K8s audit, network) with schema-driven config, live `Test connection`, and vault-encrypted secrets — recently adding Qualys, GreyNoise, JumpCloud, Darktrace, and Imperva alongside IBM QRadar, Netskope, Zeek/Suricata NDR, and more. One query runs SIEM-agnostic **federated search** across Splunk SPL / Sentinel KQL / Elastic ES&#124;QL / **QRadar AQL**. Walkthrough: [`apps/docs/docs/connectors/index.md`](apps/docs/docs/connectors/index.md).
-- **End-to-end SIEM spine** — a cold `docker compose up` ingests connector data → lands it in the ClickHouse event lake → the executable detection corpus (833 rules) fires on the live stream → a fused alert is created, all asserted by an extended integration gate. Fuse-time threat-intel + CISA-KEV enrichment now feeds the confidence score and exploit-in-wild boost, and **stateful/windowed detections** (brute-force, password-spray, port-scan) run alongside the corpus. [`apps/docs/docs/architecture.md`](apps/docs/docs/architecture.md).
-- **Autonomous triage + governed response** — every fused alert is auto-triaged by the agent (copilot/read-only by default) with a prompt-injection guard that demotes tampered evidence to manual review; a unified **confidence × blast-radius × reversibility** policy authorizes auto-execution only for reversible, low-blast actions at high confidence (everything else stays gated to a human), with real rollback + post-action verification. [`apps/docs/docs/concepts/automation-maturity.md`](apps/docs/docs/concepts/automation-maturity.md).
-- **Advanced Data Explorer** — one investigation surface (NL + SQL over the lake, plus pivots to identity/graph/intel), replacing the SIEM context-switch. `/explore`.
-- **Investigation Rail + replayable Investigation Ledger** — every prompt, tool call, evidence chip, and rationale stored against a case, replayable in the UI and shareable as a redacted public permalink. [`apps/docs/docs/console/investigation-rail.md`](apps/docs/docs/console/investigation-rail.md).
-- **Detection-as-Code lifecycle** — propose → review → eval-gate → promote; CI rejects any candidate that fails its own positive/negative fixtures (the non-circular gate) or regresses MITRE accuracy. Analyst false-positive feedback now feeds a **self-improving tuner** that proposes scoped rule exceptions / severity changes (human-approved, never auto-applied). [`apps/docs/docs/concepts/detections.md`](apps/docs/docs/concepts/detections.md) — and the native rules live in [`detections/`](detections/), of which the truth table records how many actually execute.
-- **Three-model AI + tool-using agents** — Semantic (graph-at-ingest), Behavioral (UEBA fused into alert scoring), and Knowledge (LLM), with fuse-time attack-chain grouping. The agent calls real tools (IOC enrichment, MITRE lookup, graph blast-radius) through an **LLM tool-calling loop**, and a **scored planner** routes each alert to the right specialist instead of fanning out to all four.
-- **Cost-governed LLM routing** — per-tenant budgets + circuit breaker, token/cost telemetry, a content-addressed response cache, a cheap-first cost cascade (escalate to the strong model only on low confidence), multi-model gateway fallbacks, and per-tenant BYOK keys. [`services/agents/app/routing/`](services/agents/app/routing/).
-- **Hunt-as-Code** — YAML hypotheses with MITRE tags, cron schedules, and natural-language `/hunt` workbench. [`hunts/`](hunts/) + [`apps/docs/docs/console/rule-tuning.md`](apps/docs/docs/console/rule-tuning.md).
-- **Public weekly benchmark scoreboard** — the same harness that gates PRs; the deterministic-tier row is CI-gated for freshness on every PR, and the funded weekly job appends live-LLM rows. A new **groundedness/hallucination axis** flags any indicator the agent asserts that isn't in the evidence it was given. [`apps/docs/docs/benchmark-scoreboard.mdx`](apps/docs/docs/benchmark-scoreboard.mdx).
-
----
+```bash
+git clone https://github.com/beenuar/AiSOC && cd AiSOC
+make up
+```
-## Use it from Claude, Cursor, or Cody
+Then **prove it actually works** — this is the part that matters:
-AiSOC ships an [MCP server](https://modelcontextprotocol.io) (`services/mcp/`) so analysts can query alerts, run agent investigations, and replay every step the agent took without leaving the IDE or chat. The server exposes 13 tools — discovery, deep-dive, governed lake query, and the action / replay set that walks the agent decision ledger step-by-step.
+```bash
+make smoke
+```
-> **Status — monorepo source build today; npm publish lands in v8.2.** Full setup is in [`apps/docs/docs/integrations/mcp.md`](apps/docs/docs/integrations/mcp.md), which shows the today-vs-published invocations side by side.
+That posts one real event to the ingest API and follows it through Kafka,
+detection, correlation and Postgres, then reads the resulting alert back out
+of the public API. Every stage reports PASS or FAIL:
----
+```
+[PASS] raw telemetry accepted by ingest
+[PASS] event traversed the spine and became an alert
+[PASS] alert is retrievable by id from the API
+```
-## Extend it
+Open **http://localhost:3000** (API docs at **http://localhost:8000/docs**).
-Three contribution surfaces; each is one file plus optional fixtures, and CI validates every PR.
+Something wrong? `make doctor` checks every dependency and tells you what to
+run next. Requires Docker with ~6 GB of RAM.
-- **Detection rule.** Drop a Sigma YAML under [`detections/`](detections/) with a positive / negative fixture in [`detections/fixtures/`](detections/fixtures/). The [validate-detections](https://github.com/beenuar/AiSOC/actions/workflows/validate-detections.yml) workflow tests it on every PR. Spec: [`docs/connectors/`](apps/docs/docs/connectors/).
-- **Connector.** Subclass `BaseConnector` in [`services/connectors/app/connectors/`](services/connectors/app/connectors/), register it in `_CONNECTOR_CLASSES`, and add a `plugins/<id>/plugin.yaml` manifest. The marketplace picks it up automatically. Walkthrough: [`apps/docs/docs/connectors/`](apps/docs/docs/connectors/).
-- **Playbook.** Drop a YAML under [`playbooks/`](playbooks/); [`validate-playbooks`](https://github.com/beenuar/AiSOC/actions/workflows/validate-playbooks.yml) gates the PR. Schema: [`playbook.schema.json`](playbook.schema.json).
+## Try it without connecting anything
-Plugin and detection SDK (Python · TypeScript · Go) — see [`apps/docs/docs/plugins/overview.md`](apps/docs/docs/plugins/overview.md). The CLI (`aisoc-cli`) is in [`packages/aisoc-cli/`](packages/aisoc-cli/); PyPI publish lands in v8.2.
+```bash
+make demo
+```
-**In your CI:** add `- uses: beenuar/AiSOC/packages/[email protected]` to triage your repo's Dependabot / CodeQL / secret-scanning alerts on every PR (deterministic, nothing leaves your runner). The short `beenuar/aisoc-action@v1` form needs a Marketplace listing, which lands with v8.2 — until then the subdirectory form above is the one that resolves. [Docs](apps/docs/docs/integrations/github-action.md).
+> **The demo dataset is synthetic.** It exists to show the pipeline shape, not
+> to represent real activity. Every row it writes is marked
+> `is_synthetic = true` in the database and labelled in the console. It is not
+> a benchmark, a customer, or a real incident.
----
+## Connect real data
-## Roadmap & releases
+Two ways in. Push, from anything that can make an HTTP request:
-- **Latest GitHub release with downloads:** <https://github.com/beenuar/AiSOC/releases/latest>
-- **Per-release narrative:** [`RELEASES.md`](RELEASES.md) (mirrors what used to live in this README)
-- **Machine-readable inventory with file paths, env-var diffs, test counts:** [`CHANGELOG.md`](CHANGELOG.md)
-- **v8.1 scope, and why packaging is named against v8.2:** [`docs/roadmap/v8-progress.md`](docs/roadmap/v8-progress.md)
-- **Bigger-picture roadmap (BYOC multi-cloud, MSSP rollups, federated search):** [`ROADMAP.md`](ROADMAP.md)
+```bash
+curl -X POST http://localhost:8081/v1/ingest/batch \
+ -H 'Content-Type: application/json' -H 'X-Tenant-ID: <tenant>' \
+ -d '{"connector_id":"edr-1","connector_type":"crowdstrike","source_format":"json",
+ "events":[{"severity":"high","title":"Encoded PowerShell from Office",
+ "host":"WIN-FIN-01","process_name":"powershell.exe"}]}'
+```
----
+Or pull, by configuring one of **84 click-and-connect data connectors** in
+**Settings → Connectors** (needs the `full` profile). Those with
+vendor-specific normalization and live setup docs include Splunk, Microsoft
+Sentinel, Elastic, CrowdStrike, Okta, AWS (GuardDuty / CloudTrail / Security
+Hub), Wiz, and Kubernetes audit logs. The full list is in the
+[connector docs](https://beenuar.github.io/AiSOC/docs/connectors/api-coverage).
-## Contributing
+A connector without a vendor profile still ingests through a generic mapping —
+events flow, but entity extraction is weaker.
-PRs of every size are welcome. Read [`CONTRIBUTING.md`](CONTRIBUTING.md) for the workflow and the [Code of Conduct](CODE_OF_CONDUCT.md) before opening a PR.
+## How it works
-First-time contributors: pick a [`good first issue`](https://github.com/beenuar/AiSOC/issues?q=is%3Aopen+label%3A%22good+first+issue%22). Need help? [Open a Q&A discussion](https://github.com/beenuar/AiSOC/discussions/new?category=q-a).
+See **[docs/architecture/README.md](docs/architecture/README.md)** — it walks
+one event through the whole system and every box in its diagrams links to the
+code that implements it.
----
+The short version: ingest normalizes to a common shape → Kafka carries it →
+fusion runs 833 executable detection rules and decides what becomes an alert →
+correlation groups related alerts into one incident → an agent investigates
+and writes its reasoning to the Investigation Ledger → a human approves any
+response.
-## Credits
+## Deployment profiles
-AiSOC is built and improved by a growing community of contributors, security researchers, and operators. The full attribution — including bug reporters and security researchers — lives in [`.github/CREDITS.md`](.github/CREDITS.md). The always-up-to-date code-contribution graph is on the [GitHub contributors page](https://github.com/beenuar/AiSOC/graphs/contributors).
+One architecture, three profiles of it.
----
+| Profile | Command | Services | RAM | What you get |
+|---|---|---|---|---|
+| **core** | `make up` | 10 | ~6 GB | The full alerting pipeline: ingest → detect → correlate → alert → triage → console |
+| **full** | `make up-full` | 30 | ~12 GB | Core plus event lake, entity graph, vector store, enrichment, scheduled connectors |
+| **demo** | `make up && make demo` | 10 | ~6 GB | Core plus labelled synthetic data |
+
+CORE is not a cut-down toy — it is the smallest deployment that takes a real
+event and produces a real alert.
+
+## Real vs synthetic data
+
+This matters more than any feature, so it is stated plainly.
+
+| Kind | Where | How you can tell |
+|---|---|---|
+| **Real** | Your connectors and the ingest API | `is_synthetic = false` (the default) |
+| **Demo** | `make demo` | `is_synthetic = true`, labelled in the console |
+| **Benchmark** | `services/agents/tests/eval_data/` | Every published row carries `substrate: true` |
+| **Test fixtures** | `tests/`, `**/tests/` | Never shipped in an image |
+
+**Production never silently falls back to synthetic data.** When a backend is
+unreachable the console shows an error, not an invented investigation. That
+was not always true — see [the reality audit](docs/audit/REPOSITORY_REALITY.md)
+for the five places it was wrong and how each was fixed.
+
+## AI agents
+
+Agents triage alerts and investigate incidents. What they can and cannot do:
+
+- **They read** the alert, its correlated siblings, entity context, and prior
+ verdicts for the same signature.
+- **They call typed tools** — lake queries, graph traversals, enrichment
+ lookups. The model chooses a tool and passes arguments; it never writes SQL.
+- **Everything is logged** to the Investigation Ledger: prompts, tool calls,
+ citations, the verdict, and token cost.
+- **Grounding is checked.** A verdict citing an indicator the evidence never
+ contained is demoted to human review rather than auto-closed.
+- **A prompt is validated before it is sent.** Raw logs, OCSF payloads and
+ secret-shaped values are refused, not redacted after the fact.
+- **Nothing executes without a human.** Response actions are proposed. An
+ approver must hold the required permission tier and must not be the person
+ who requested the action.
+
+Without a model provider key, agents run a deterministic offline path and say
+so. They do not fabricate a verdict.
+
+## Project maturity
+
+| Capability | Status | Tested | Production ready |
+|---|---|---|---|
+| Ingest → detect → correlate → alert | Stable | E2E + unit | Yes |
+| Detection engine (833 executable rules) | Stable | Fixture replay + unit | Yes |
+| Alert correlation into incidents | Stable | Unit | Yes |
+| REST API + web console | Stable | Unit + integration | Yes |
+| AI triage + Investigation Ledger | Beta | Unit + substrate eval | Yes, copilot mode |
+| Event lake + hunting (ClickHouse) | Beta | Unit | Yes, `full` profile |
+| Entity graph (Neo4j) | Beta | Unit | Yes, `full` profile |
+| Governed response actions | Beta | Unit | Human-approved only |
+| Scheduled connectors | Beta | Contract tests | `full` profile |
+| UEBA | **Broken** | — | No — [see why](docs/audit/REPOSITORY_REALITY.md) |
+| Package distribution (npm/PyPI) | Planned | — | v8.2 — blocked on registry credentials |
+
+## What AiSOC is not
+
+- **Not a drop-in SIEM replacement.** It correlates and investigates; it does
+ not replace long-term log retention and compliance search.
+- **Not able to see telemetry you have not connected.** There is no magic
+ discovery.
+- **Not autonomous by default.** Response requires explicit policy
+ authorization and a human approver.
+- **Demo incidents are not real incidents**, and benchmark corpora are not
+ customer telemetry.
+- **Benchmark numbers are substrate self-consistency measures**, not live
+ agent accuracy, and are labelled as such wherever published.
+
+## Troubleshooting
+
+`make doctor` diagnoses the deployment and prints the command to run next.
+The five most common failures:
+
+| Symptom | Cause | Fix |
+|---|---|---|
+| `port is already allocated` | Something else on 5432/6379/9092/3000 | `make doctor` names the port; stop it or edit the host port |
+| Kafka reports healthy but nothing flows | Docker VM out of disk — Kafka corrupts its log dir and still passes its healthcheck | `docker system prune -af`, then `make clean && make up` |
+| `make smoke` fails at "became an alert" | fusion is down or not consuming | `docker compose logs fusion \| tail -60` |
+| Console loads but is empty | No data yet — this is correct | `make smoke`, or `make demo` |
+| Services restart-loop on 8 GB machines | Not enough RAM for `full` | Use `make up` (core) |
## Security
-For security issues, please do not open a public issue. Use [GitHub's private vulnerability reporting](https://github.com/beenuar/AiSOC/security/advisories/new). Full policy in [`SECURITY.md`](SECURITY.md). AiSOC follows coordinated disclosure.
+Secrets live in `.env` and are never committed; connector credentials are
+encrypted at rest with a per-deployment key. Tenant isolation is enforced at
+the query layer in every store, not by convention. RBAC gates every mutating
+route. Prompts are validated before they leave the deployment, and you can
+bring your own model key or run entirely local models. Report vulnerabilities
+via [SECURITY.md](SECURITY.md).
----
+## Developing
-## License
+```bash
+make test # unit tests for every service
+make smoke # the golden pipeline, against a running stack
+make stats # recount every figure this README publishes
+```
-[MIT](LICENSE) — © 2024–present AiSOC contributors.
+Guides: [add a connector](https://beenuar.github.io/AiSOC/docs/plugins/hello-plugin) ·
+[add a detection](https://beenuar.github.io/AiSOC/docs/detections/hello-hunt) ·
+[plugin lifecycle](https://beenuar.github.io/AiSOC/docs/plugins/lifecycle) ·
+[contributing](CONTRIBUTING.md)
-<div align="center">
+Every number in this README is produced by `scripts/project_stats.py` and
+checked in CI, so a figure cannot drift from the tree without a red build.
-[Report a bug](https://github.com/beenuar/AiSOC/issues/new?template=bug_report.yml) · [Request a feature](https://github.com/beenuar/AiSOC/issues/new?template=feature_request.yml) · [Contribute](CONTRIBUTING.md) · [Read the docs](apps/docs/) · [Reproduce the benchmark](apps/docs/docs/benchmark.md)
+## Roadmap · Contributing · License
-</div>
+[ROADMAP.md](ROADMAP.md) · [CONTRIBUTING.md](CONTRIBUTING.md) · [SECURITY.md](SECURITY.md) · MIT
diff --git a/apps/web/src/components/copilot/CopilotView.tsx b/apps/web/src/components/copilot/CopilotView.tsx
index 7ebf63827..0fce139f4 100644
--- a/apps/web/src/components/copilot/CopilotView.tsx
+++ b/apps/web/src/components/copilot/CopilotView.tsx
@@ -22,6 +22,7 @@ import {
type CopilotMessage,
} from '@/lib/api';
import { Skeleton } from '@/components/ui/Skeleton';
+import { canUseDemoData } from '@/lib/demoFallback';
// ─── Suggested prompts ───────────────────────────────────────────────────────
@@ -406,10 +407,16 @@ export function CopilotView() {
: res.reply;
setMessages((prev) => [...prev, reply]);
} catch (err) {
- // Backend not reachable / not implemented yet — fall back to a demo
- // reply so the dock still feels alive in local dev.
- const demo = buildDemoReply(trimmed);
- setMessages((prev) => [...prev, demo]);
+ // This used to substitute `buildDemoReply(trimmed)` unconditionally, so
+ // a backend outage produced an invented investigation — a named host, a
+ // named user, ATT&CK techniques and three alert "citations" — rendered
+ // in the same style as a real answer. An analyst had no way to tell.
+ //
+ // Outside demo mode the error is now surfaced as an error. The dock
+ // feeling alive is not worth a fabricated verdict.
+ if (canUseDemoData()) {
+ setMessages((prev) => [...prev, buildDemoReply(trimmed)]);
+ }
setError(err);
} finally {
setSending(false);
diff --git a/apps/web/src/components/settings/SettingsView.tsx b/apps/web/src/components/settings/SettingsView.tsx
index 02551fb76..aaf6e5815 100644
--- a/apps/web/src/components/settings/SettingsView.tsx
+++ b/apps/web/src/components/settings/SettingsView.tsx
@@ -112,10 +112,13 @@ interface ProfileData {
timezone: string;
}
+// A user who had never saved a profile was shown 'Sasha Lin
+// <[email protected]>' as their own account. Empty fields are correct:
+// the form is asking the user to fill them in, not telling them who they are.
const DEFAULT_PROFILE: ProfileData = {
- displayName: 'Sasha Lin',
- email: '[email protected]',
- title: 'Senior SOC Analyst',
+ displayName: '',
+ email: '',
+ title: '',
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC',
};
diff --git a/docker-compose.yml b/docker-compose.yml
index 17afc41fc..644fbabd0 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -116,6 +116,8 @@ services:
retries: 5
kafka-ui:
+ # full profile — Kafka topic browser. A debugging convenience, not a pipeline component.
+ profiles: ["full"]
image: provectuslabs/kafka-ui:latest
container_name: aisoc-kafka-ui
depends_on:
@@ -130,6 +132,8 @@ services:
- aisoc
clickhouse:
+ # full profile — Event lake. Backs /lake/sql and the hunt surface; alerting does not read it.
+ profiles: ["full"]
image: clickhouse/clickhouse-server:23.8
container_name: aisoc-clickhouse
ports:
@@ -153,6 +157,8 @@ services:
mem_reservation: 768m
opensearch:
+ # full profile — Full-text search over archived events. No CORE code path queries it.
+ profiles: ["full"]
image: opensearchproject/opensearch:2.11.0
container_name: aisoc-opensearch
environment:
@@ -177,6 +183,8 @@ services:
mem_reservation: 768m
qdrant:
+ # full profile — Vector store for threat-intel embeddings (services/threatintel).
+ profiles: ["full"]
image: qdrant/qdrant:v1.7.0
container_name: aisoc-qdrant
ports:
@@ -187,6 +195,8 @@ services:
- aisoc
neo4j:
+ # full profile — Entity graph. Backs graph traversals and blast radius, not alert generation.
+ profiles: ["full"]
image: neo4j:5.15-community
container_name: aisoc-neo4j
ports:
@@ -274,8 +284,6 @@ services:
depends_on:
kafka:
condition: service_healthy
- neo4j:
- condition: service_healthy
ports:
- "127.0.0.1:8081:8080"
- "127.0.0.1:9090:9090"
@@ -288,10 +296,11 @@ services:
LOG_LEVEL: info
JWT_SECRET: dev_secret_key_change_in_production
ATTCK_DATA_PATH: /app/data/enterprise-attack.json
- # Phase A3 — graph-at-ingest is ON by default so a cold `up` builds the
- # entity graph out of the box. Soft-fails (writer disabled) if Neo4j is
- # unreachable, so this never blocks ingest.
- AISOC_GRAPH_ENABLED: "true"
+ # Graph-at-ingest needs Neo4j, which is a `full`-profile service. It is
+ # off in CORE and switched on by the `full` overlay. It used to be
+ # hardcoded "true" with a hard `depends_on: neo4j`, which is why the
+ # minimal stack could not start without the graph database.
+ AISOC_GRAPH_ENABLED: "${AISOC_GRAPH_ENABLED:-false}"
AISOC_NEO4J_URI: bolt://neo4j:7687
AISOC_NEO4J_USER: neo4j
AISOC_NEO4J_PASSWORD: neo4j_dev_secret
@@ -300,6 +309,8 @@ services:
restart: unless-stopped
enrichment:
+ # full profile — Fuse-time threat-intel and vulnerability enrichment. Alerts fire without it.
+ profiles: ["full"]
build:
context: ./services/enrichment
dockerfile: Dockerfile
@@ -332,24 +343,36 @@ services:
pull_policy: missing
container_name: aisoc-fusion
depends_on:
+ # Postgres was missing here, so during a cold boot fusion tried to write
+ # alerts before the database accepted connections and logged the failure
+ # exactly once.
+ postgres:
+ condition: service_healthy
redis:
condition: service_healthy
kafka:
condition: service_healthy
- clickhouse:
- condition: service_started
ports:
- "127.0.0.1:8003:8003"
environment:
KAFKA_BOOTSTRAP_SERVERS: kafka:29092
REDIS_URL: redis://:redis_dev_secret@redis:6379/3
DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc
- # Phase A1 — populate the ClickHouse event lake from the raw-events stream.
+ # The ClickHouse event lake is a `full`-profile capability: it backs
+ # /lake/sql and the hunt surface, not alerting. CORE runs without it and
+ # the writer disables itself.
+ AISOC_LAKE_WRITER_ENABLED: "${AISOC_LAKE_WRITER_ENABLED:-false}"
CLICKHOUSE_HOST: clickhouse
CLICKHOUSE_PORT: "9000"
CLICKHOUSE_DATABASE: aisoc
CLICKHOUSE_USER: aisoc
CLICKHOUSE_PASSWORD: clickhouse_dev_secret
+ # Fusion defaulted to http://localhost:8082, which inside its own
+ # container is fusion itself — so fuse-time enrichment always failed and
+ # the failure was swallowed at DEBUG. `enrichment` is a `full`-profile
+ # service; in CORE this resolves to nothing and enrichment is skipped,
+ # which is the same outcome as before but now deliberate.
+ ENRICHMENT_SERVICE_URL: ${ENRICHMENT_SERVICE_URL:-http://enrichment:8082}
networks:
- aisoc
restart: unless-stopped
@@ -406,6 +429,8 @@ services:
# unless a service is pointed at it via OPENAI_BASE_URL — see the note on the
# `agents` service above.
litellm:
+ # full profile — LLM gateway. Only needed when a provider key is configured.
+ profiles: ["full"]
image: ghcr.io/berriai/litellm:main-stable
container_name: aisoc-litellm
command: ["--config", "/etc/litellm/config.yaml", "--port", "4000"]
@@ -462,6 +487,11 @@ services:
restart: unless-stopped
actions:
+ # Response execution. Governed and copilot-default; nothing in CORE
+ # dispatches to it, so it is not part of the minimal pipeline. Carries the
+ # `chatops` profile too because slack-bot depends on it, and a profile
+ # whose dependency is not in the same profile fails to render at all.
+ profiles: ["full", "chatops"]
build:
context: ./services/actions
dockerfile: Dockerfile
@@ -485,6 +515,8 @@ services:
restart: unless-stopped
connectors:
+ # full profile — Scheduled vendor polling. CORE accepts events over the ingest HTTP API instead.
+ profiles: ["full"]
build:
context: ./services/connectors
dockerfile: Dockerfile
@@ -516,6 +548,8 @@ services:
restart: unless-stopped
threatintel:
+ # full profile — IOC harvesting and actor attribution. Needs Qdrant.
+ profiles: ["full"]
build:
context: ./services/threatintel
dockerfile: Dockerfile
@@ -548,6 +582,8 @@ services:
restart: unless-stopped
ueba:
+ # full profile — Behavioural baselining. Consumes its own topic; see docs/audit/REPOSITORY_REALITY.md.
+ profiles: ["full"]
build:
context: ./services/ueba
dockerfile: Dockerfile
diff --git a/docs/architecture/README.md b/docs/architecture/README.md
new file mode 100644
index 000000000..f916a4dd0
--- /dev/null
+++ b/docs/architecture/README.md
@@ -0,0 +1,270 @@
+# Architecture
+
+Every box in every diagram below corresponds to code in this repository, and
+links to it. Where a component exists but is not used, it says so rather than
+being quietly drawn in.
+
+---
+
+## What happens when AiSOC receives one security event
+
+Follow a single event. This is the whole system, in order.
+
+**1. Something sends telemetry.** Either a connector polls a vendor API on a
+schedule, or a tool pushes to the ingest HTTP API directly:
+
+```bash
+curl -X POST http://localhost:8081/v1/ingest/batch \
+ -H 'Content-Type: application/json' \
+ -H 'X-Tenant-ID: <your-tenant>' \
+ -d '{"connector_id":"edr-1","connector_type":"crowdstrike","source_format":"json",
+ "events":[{"severity":"high","title":"Encoded PowerShell from Office",
+ "host":"WIN-FIN-01","process_name":"powershell.exe",
+ "parent_process":"winword.exe"}]}'
+```
+
+**2. Ingest normalizes it.** [`services/ingest`](../../services/ingest) maps
+the vendor payload onto a common OCSF-shaped envelope using a per-connector
+profile. A connector with no profile falls through to a vendor-neutral
+generic profile — the event still flows, but entity extraction is weaker.
+
+**3. It enters the event spine.** Ingest publishes to the Kafka topic
+`aisoc.raw_events`. This is the boundary that makes everything downstream
+independent: anything can consume the spine without ingest knowing about it.
+
+**4. Fusion consumes it and evaluates detections.**
+[`services/fusion`](../../services/fusion) runs the 833 executable rules
+against the event. Separately it decides whether the event is *promotable* —
+a vendor finding (OCSF category 2) or anything at severity ≥ high becomes an
+alert; routine telemetry does not.
+
+**5. Fusion correlates.** A new alert is matched against open incidents using
+a correlation key of `{tenant}:{entity}:{tactic}`. It either joins an
+existing incident or opens a new one, so ten related alerts become one thing
+an analyst looks at.
+
+**6. The alert is written to Postgres** and published to
+`aisoc.alerts.fused`.
+
+**7. Two consumers pick it up.**
+[`services/realtime`](../../services/realtime) pushes it to the console over
+WebSocket. [`services/agents`](../../services/agents) auto-triages it with an
+LLM — a verdict, a confidence, and proposed actions.
+
+**8. The agent's work is written to the Investigation Ledger** — every
+prompt, tool call and citation, so a verdict can be audited rather than
+trusted.
+
+**9. Response stays governed.** Nothing executes automatically. An action is
+proposed; a human with the right permission approves it; the result is
+verified against the vendor rather than assumed from an HTTP 200.
+
+> **Where it stops.** Step 9 has no automatic trigger — there is no code path
+> that dispatches a response without a human. That is deliberate, and it is
+> the honest boundary of "autonomous" in this project.
+
+---
+
+## Diagram 1 — the shape of it
+
+```mermaid
+flowchart TD
+ sources["Security tools<br/>EDR · cloud · identity · network"]
+ ingest["Ingestion + normalization"]
+ spine["Event spine (Kafka)"]
+ detect["Detection · correlation"]
+ alerts["Alerts + incidents"]
+ ai["AI investigation"]
+ cases["Cases + Investigation Ledger"]
+ respond["Governed response"]
+ analyst["SOC analyst"]
+
+ sources --> ingest --> spine --> detect --> alerts --> ai --> cases --> respond
+ cases --> analyst
+ analyst -->|approves| respond
+```
+
+---
+
+## Diagram 2 — actual services
+
+Only services that exist and run. Dashed boxes are the `full` profile.
+
+```mermaid
+flowchart LR
+ subgraph core ["CORE profile — default"]
+ ing["services/ingest<br/>Go · :8080"]
+ kaf[("Kafka<br/>aisoc.raw_events")]
+ fus["services/fusion<br/>Python · :8003"]
+ pg[("PostgreSQL")]
+ rds[("Redis")]
+ api["services/api<br/>Python · :8000"]
+ rt["services/realtime<br/>TS · :8086"]
+ agt["services/agents<br/>Python · :8084"]
+ web["apps/web<br/>Next.js · :3000"]
+ end
+
+ subgraph full ["full profile — optional"]
+ ch[("ClickHouse<br/>event lake")]
+ neo[("Neo4j<br/>entity graph")]
+ qd[("Qdrant<br/>embeddings")]
+ enr["services/enrichment"]
+ conn["services/connectors"]
+ ti["services/threatintel"]
+ end
+
+ conn -.->|"polls vendors"| ing
+ ing --> kaf
+ kaf --> fus
+ fus --> pg
+ fus --> kafd[("Kafka<br/>aisoc.alerts.fused")]
+ fus --> rds
+ fus -.-> ch
+ fus -.-> enr
+ kafd --> rt
+ kafd --> agt
+ agt --> pg
+ api --> pg
+ api -.-> ch
+ api -.-> neo
+ ti -.-> qd
+ web --> api
+ web --> rt
+```
+
+---
+
+## Diagram 3 — who owns which data
+
+```mermaid
+flowchart TB
+ subgraph req ["Required"]
+ pg["PostgreSQL<br/><br/>alerts · incidents · cases<br/>users · tenants · detection rules<br/>audit log · investigation ledger"]
+ rds["Redis<br/><br/>correlation windows<br/>dedup keys<br/>investigation run state"]
+ kaf["Kafka<br/><br/>aisoc.raw_events<br/>aisoc.alerts.fused"]
+ end
+
+ subgraph opt ["Optional (full profile)"]
+ ch["ClickHouse<br/><br/>every normalized event<br/>backs /lake/sql and hunt"]
+ neo["Neo4j<br/><br/>entity graph<br/>blast radius"]
+ qd["Qdrant<br/><br/>IOC and actor embeddings"]
+ end
+```
+
+**Why each one, and what breaks without it:**
+
+| Store | Why it is not replaceable by Postgres | Without it |
+|---|---|---|
+| **PostgreSQL** | — | Nothing works. |
+| **Redis** | Correlation needs expiring keys at event rate; TTL semantics and throughput are the point. | No correlation; every alert becomes its own incident. |
+| **Kafka** | Decouples producers from consumers and lets a slow consumer fall behind without dropping events or blocking ingest. | No spine; fusion, realtime and agents would each need a direct call from ingest. |
+| **ClickHouse** | Columnar scans over hundreds of millions of events. Postgres cannot do this at cost. | No event lake, no hunting over raw telemetry. **Alerting is unaffected.** |
+| **Neo4j** | Multi-hop traversal ("what else did this identity touch") is a join explosion in SQL. | No graph context or blast radius. Alerting unaffected. |
+| **Qdrant** | Vector similarity for IOC and actor matching. | No semantic threat-intel matching. |
+
+**OpenSearch is started by the `full` profile and nothing reads from it.**
+It is recorded in [the reality audit](../audit/REPOSITORY_REALITY.md) as
+unused rather than drawn here as though it were part of the design.
+
+---
+
+## Diagram 4 — AI investigation
+
+```mermaid
+sequenceDiagram
+ participant K as Kafka aisoc.alerts.fused
+ participant A as services/agents
+ participant C as LLM input contract
+ participant M as Model
+ participant L as Investigation Ledger
+ participant H as Analyst
+
+ K->>A: fused alert
+ A->>A: gather evidence (alert, entities, prior verdicts)
+ A->>C: proposed prompt
+ C-->>A: refuse if it contains raw logs or secrets
+ C->>M: validated prompt
+ M-->>A: verdict + confidence + cited indicators
+ A->>A: groundedness check
+ Note over A: an indicator the evidence<br/>never contained demotes<br/>the verdict to human review
+ A->>L: prompt, tool calls, citations, verdict
+ A->>H: proposed actions (never executed)
+ H->>H: approve, with permission + separation of duties
+```
+
+Three properties worth naming, because each is enforced in code:
+
+- **The contract runs before the request.** A prompt about to carry raw OCSF,
+ vendor log lines or secret-shaped values is refused, not logged after the
+ fact.
+- **Citations are checked against the evidence.** A verdict citing an
+ indicator that was never in the evidence is demoted rather than auto-closed.
+- **Approval is authorized, not just recorded.** The approver must hold the
+ action's permission tier and must not be the requester.
+
+---
+
+## Diagram 5 — connector to alert
+
+```mermaid
+flowchart TD
+ A["Connector polls vendor API<br/>(or a tool pushes to /v1/ingest)"] --> B{"Profile for<br/>this connector?"}
+ B -->|yes| C["Vendor-specific mapping"]
+ B -->|no| D["Generic profile<br/>weaker entity extraction"]
+ C --> E["OCSF-shaped envelope"]
+ D --> E
+ E --> F[("Kafka aisoc.raw_events")]
+ F --> G["Detection engine<br/>833 executable rules"]
+ F --> H{"Promotable?<br/>category 2, or severity >= high"}
+ G -->|rule fires| I["Alert"]
+ H -->|yes| I
+ H -->|no| J["Lake only (full profile)<br/>hunted, not alerted"]
+ I --> K{"Matches an open<br/>incident?"}
+ K -->|yes| L["Joins that incident"]
+ K -->|no| M["Opens a new incident"]
+ L --> N[("PostgreSQL alerts")]
+ M --> N
+ N --> O[("Kafka aisoc.alerts.fused")]
+```
+
+---
+
+## Deployment profiles
+
+One architecture, three profiles of it — not three architectures.
+
+| Profile | Command | Services | RAM | What you get |
+|---|---|---|---|---|
+| **core** | `make up` | 10 | ~6 GB | Ingest → detect → correlate → alert → triage → console. The full alerting pipeline. |
+| **full** | `make up-full` | 30 | ~12 GB | Core plus event lake, entity graph, vector store, enrichment, connectors, LLM gateway. |
+| **demo** | `make up && make demo` | 10 | ~6 GB | Core plus clearly-labelled synthetic data. |
+
+CORE is not a toy. It is the smallest deployment that can take a real event
+and produce a real alert, which is the thing the product is for.
+
+**Two flags travel with the `full` profile.** The lake writer and the
+graph writer target stores that exist only there, so in CORE they default off
+rather than retrying against a host that is not running:
+
+```bash
+AISOC_LAKE_WRITER_ENABLED=true AISOC_GRAPH_ENABLED=true \
+ docker compose --profile full up -d
+```
+
+`make up-full` sets both for you, and the integration workflow sets the same
+pair — so the documented command and the tested command are the same command.
+
+---
+
+## Verifying any of this
+
+```bash
+make up && make smoke
+```
+
+`make smoke` posts one event to the ingest API and follows it through Kafka,
+fusion, detection, promotion and Postgres, then reads it back from the public
+API. It reaches past nothing. Each stage reports PASS or FAIL separately, so
+a break names the boundary that broke.
+
+Source: [`tests/e2e/golden_pipeline/`](../../tests/e2e/golden_pipeline/).
diff --git a/docs/audit/REPOSITORY_REALITY.md b/docs/audit/REPOSITORY_REALITY.md
new file mode 100644
index 000000000..b5100ef01
--- /dev/null
+++ b/docs/audit/REPOSITORY_REALITY.md
@@ -0,0 +1,199 @@
+# Repository reality
+
+**What actually works today**, established by reading the implementations and
+by running the stack — not by reading filenames or documentation.
+
+Audit date: 2026-09-23 · against `v8.1.0`
+
+Everything marked WORKING below was either exercised against a live stack or
+traced to a caller on a real path. Where a claim could not be verified, it
+says so. Nothing here is inferred from a file being present.
+
+---
+
+## How to read this
+
+| Status | Meaning |
+|---|---|
+| **WORKING** | Exercised end to end, or traced to a production caller with a passing gate. |
+| **PARTIAL** | Real implementation, but a named limitation stops it being the whole claim. |
+| **BROKEN** | Present and wired, but does not function. |
+| **DEMO-ONLY** | Runs only with synthetic data; produces nothing from real telemetry. |
+| **EXPERIMENTAL** | Works, but interface or results are not stable. |
+| **DEAD CODE** | No production caller. |
+| **DOCS-ONLY** | Described somewhere; no implementation behind the description. |
+
+---
+
+## The headline
+
+**The core pipeline works.** A single event posted to the ingest API traverses
+Kafka, fusion, detection and promotion, lands in Postgres, and is retrievable
+from the public API. Verified on 2026-09-23 against a clean `docker compose up`
+on arm64:
+
+```
+[PASS] raw telemetry accepted by ingest
+[PASS] event traversed the spine and became an alert
+[PASS] alert is retrievable by id from the API
+[PASS] severity survived normalization
+[PASS] source attribution is not duplicated
+[PASS] description is prose, not a serialized payload
+```
+
+That run is reproducible: `make up && make smoke`.
+
+**What was not true before this audit** is that the *documented* quick start
+exercised any of it. `./install.sh` handed off to a nine-service compose file
+with **no ingest service, no fusion service, and `AISOC_DISABLE_KAFKA: true`**,
+whose only content came from `seed_demo.py` writing 15 fabricated incidents
+directly into Postgres. A new user followed the README, saw a populated
+console, and concluded the platform worked — having never run the platform.
+That single fact accounts for most of the recurring feedback about fabricated
+data and unverifiable architecture.
+
+---
+
+## Component inventory
+
+### The event spine — WORKING
+
+| Component | Language | Entry point | Consumes | Produces | Status |
+|---|---|---|---|---|---|
+| `services/ingest` | Go | `main.go` → `:8080` | HTTP `POST /v1/ingest/batch` | Kafka `aisoc.raw_events` | **WORKING** |
+| `services/fusion` | Python | `app/main.py` → `:8003` | Kafka `aisoc.raw_events` | Postgres `alerts`, Kafka `aisoc.alerts.fused` | **WORKING** |
+| `services/api` | Python | `app/main.py` → `:8000` | Postgres | HTTP `GET /api/v1/alerts` | **WORKING** |
+| `services/agents` | Python | `app/main.py` → `:8084` | Kafka `aisoc.alerts.fused` | triage verdicts | **PARTIAL** — needs a provider key; deterministic offline otherwise |
+| `services/realtime` | TypeScript | `src/index.ts` → `:8086` | Kafka `aisoc.alerts.fused` | WebSocket | **WORKING** |
+| `apps/web` | Next.js | `:3000` | API | console | **WORKING** |
+
+Topic names match literally on both sides (`aisoc.raw_events`,
+`aisoc.alerts.fused`), and compose supplies the env vars each config module
+reads. This was checked rather than assumed, because a one-character topic
+mismatch is invisible until nothing arrives.
+
+### Storage — what each one is actually for
+
+| Store | Profile | What lives here | Status |
+|---|---|---|---|
+| PostgreSQL | core | alerts, incidents, cases, users, tenants, detection rules, audit log | **WORKING** |
+| Redis | core | correlation windows, dedup keys, investigation run state | **WORKING** |
+| Kafka | core | the event spine: `aisoc.raw_events`, `aisoc.alerts.fused` | **WORKING** |
+| ClickHouse | full | the event lake (`aisoc.raw_events` table) behind `/lake/sql` and hunt | **WORKING** when enabled |
+| Neo4j | full | entity graph, blast radius | **WORKING** when enabled |
+| Qdrant | full | IOC/actor embeddings for `services/threatintel` | **WORKING** when enabled |
+| OpenSearch | full | declared for archived-event search | **DEAD CODE** — no CORE or FULL code path queries it |
+
+OpenSearch is the honest casualty of this audit: it is started by the compose
+file and nothing reads from it. It stays in the `full` profile rather than
+being silently removed, and is recorded here as unused.
+
+### Broken or disconnected
+
+| Component | Status | What is wrong |
+|---|---|---|
+| `services/ueba` | **BROKEN** | Consumes the topic `security.events`. Nothing in the repository produces that topic — ingest writes `aisoc.raw_events`. So UEBA never scores, never emits `ueba.anomalies`, and fusion's UEBA confidence boost is permanently inert despite defaulting on. |
+| Ingest inbox webhooks | **BROKEN** | Routes mount only when `DATABASE_DSN` is set; compose never sets it. The templates directory is also not copied into the image, so even with a DSN every template resolves 503. |
+| Fuse-time enrichment | **FIXED in this audit** | Defaulted to `http://localhost:8082`, which inside the fusion container is fusion itself. Every enrichment call failed and the failure was swallowed at `DEBUG`. Now points at the `enrichment` service and is a declared `full`-profile capability. |
+| Investigation → response | **PARTIAL, by design** | Nothing automatically dispatches to `services/actions`. Response is copilot-default and human-initiated. This is intentional, but it means the pipeline terminates at triage. |
+| `aisoc.alerts.raw` | **DEAD** | Fusion subscribes to it; no producer exists anywhere. |
+| `aisoc.vulnerability_matches` | **DEAD** | Ingest produces it; no consumer exists. |
+
+### Detection
+
+| Item | Count | Status |
+|---|---|---|
+| Rules the engine loads | **833** | **WORKING** — these can fire |
+| YAML files under `detections/` | **7016** | mostly quarantined imports with **no evaluator**; the engine never reads them |
+
+The gap matters and has been published both ways in the past. `make stats`
+reports both numbers side by side so they cannot be conflated again.
+
+### Known defects found by running it
+
+These were not visible from the code alone:
+
+1. **`connector_type` read `"crowdstrike crowdstrike"`** on every alert —
+ vendor and product joined without dedup, in two separate copies of the
+ same helper. Fixed; both now share one implementation.
+2. **Alert `description` was the serialized event** — `str(raw_data)`, so the
+ console showed `{"command_line": "powershell.exe -nop ...` where a sentence
+ belonged, discarding the vendor's own description. Fixed.
+3. **The Kafka healthcheck passes on a broker that cannot serve.** When the
+ Docker VM ran out of disk, Kafka failed to write `meta.properties`, refused
+ every request, and compose still reported it `healthy`. `make doctor`
+ checks disk before anything else and probes the broker with an admin call
+ rather than trusting the healthcheck.
+4. **CrowdStrike has no normalizer profile** and falls through to the generic
+ one. Events still promote, but entity extraction is weak — the correlation
+ key came back `tenant:unknown:unknown`.
+
+---
+
+## Data integrity
+
+The project's rule is that fabricated security data must never render as a
+tenant's real state. The audit found the rule was enforced in 22 console
+components and violated in five places, three of them authenticated API
+endpoints.
+
+| Site | Was | Now |
+|---|---|---|
+| `GET /api/v1/mssp/{overview,tenants,incidents}` | Returned invented tenants ("Acme Corp, health 92.4") and incidents with named assignees to any authenticated caller | Demo-mode only; empty otherwise |
+| `CopilotView.tsx` catch block | Any backend error produced an invented investigation with a named host, a named user and three fake alert citations | Demo-mode only; otherwise the error is shown as an error |
+| `GET /api/v1/deployment/airgap/status` | Reported `passed: True` with invented detail ("487 rules loaded from offline bundle") for checks that measured nothing | Reports "not checked" with the reason |
+| `SettingsView.tsx` | Showed `Sasha Lin <[email protected]>` as the signed-in user's own profile | Empty fields |
+| `InvestigationTimeline.tsx` | Rendered a fabricated investigation when no run was selected | Demo-mode only (fixed in v8.1.0) |
+
+**Provenance is now a column, not a convention.** Migration
+`054_alert_provenance.sql` adds `is_synthetic`, `synthetic_source` and
+`synthetic_scenario` to `alerts`, defaulting to "not synthetic" so the real
+pipeline can never be mislabelled. Before this, the only marker was a `"demo"`
+string in a `tags` array that the most realistic-looking seed rows omitted.
+
+`seed_demo.py` also had no guard of any kind — it ran against whatever
+`DATABASE_URL` resolved to. It now refuses outside a development environment
+unless `AISOC_ALLOW_SEED=1`.
+
+---
+
+## What is demo-only
+
+| Component | Status |
+|---|---|
+| `services/demo-producer` | **DEMO-ONLY**. Emits randomised vendor events into the real ingest API. Not in any compose profile; invoked manually. |
+| `seed_demo.py` | **DEMO-ONLY**. 15 hand-written incidents plus randomised alerts. |
+| `services/agents/app/api/hunt_search.py` | **DEMO-ONLY** but honest — returns `source: "sample"` and a notice saying it does not query the lake. |
+| `services/agents/app/api/copilot.py` | **PARTIAL** — real LLM path with a key; returns `source: "template"` and a notice without one. |
+| `packages/aisoc-sandbox` | **WORKING** as an offline simulator. Deliberately not the production stack. |
+
+---
+
+## Unverified
+
+Stated rather than guessed:
+
+- **The live-agent LLM path** could not be exercised: no provider key was
+ available. The deterministic offline path was exercised. Every published
+ benchmark row is labelled `substrate: true` and must not be read as live
+ agent accuracy.
+- **Kubernetes/Helm deployment** was not exercised in this audit. The chart
+ renders; whether it runs was not tested here.
+- **Whether migrations 050–053 apply** on an existing volume was not traced.
+ Compose mounts `services/api/migrations` as `docker-entrypoint-initdb.d`,
+ which runs only on a *fresh* volume. On a clean install the schema is
+ correct (92 tables observed).
+
+---
+
+## Reproducing this audit
+
+```bash
+make up # CORE profile: 10 services
+make doctor # every dependency probed, not just "running"
+make smoke # one real event through the real pipeline
+make stats # recount every published figure from the tree
+```
+
+`make smoke` is the claim. If it fails, the pipeline is broken, and the
+failure names the boundary that broke.
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 5aa2f6820..1f8db3abf 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -9087,7 +9087,14 @@ paths:
tags:
- mssp
summary: Mssp Overview
- description: Cross-tenant KPI summary for the MSSP parent dashboard.
+ description: 'Cross-tenant KPI summary for the MSSP parent dashboard.
+
+
+ Not yet implemented against real data. Returns zeros outside demo mode
+
+ rather than the sample figures, because a dashboard reading 23.4 minutes
+
+ MTTR that nobody measured is worse than one reading nothing.'
operationId: mssp_overview_api_v1_mssp_overview_get
responses:
'200':
@@ -9103,7 +9110,12 @@ paths:
tags:
- mssp
summary: List Managed Tenants
- description: List managed tenants with health scores for the parent dashboard.
+ description: 'List managed tenants with health scores for the parent dashboard.
+
+
+ Empty outside demo mode. `GET /api/v1/mssp/children` is the route backed
+
+ by real rows.'
operationId: list_managed_tenants_api_v1_mssp_tenants_get
responses:
'200':
@@ -9122,7 +9134,8 @@ paths:
tags:
- mssp
summary: List Cross Tenant Incidents
- description: Critical incidents across all managed tenants.
+ description: Critical incidents across all managed tenants. Empty outside demo
+ mode.
operationId: list_cross_tenant_incidents_api_v1_mssp_incidents_get
security:
- HTTPBearer: []
diff --git a/docs/testing/CLEAN_INSTALL.md b/docs/testing/CLEAN_INSTALL.md
new file mode 100644
index 000000000..df6852928
--- /dev/null
+++ b/docs/testing/CLEAN_INSTALL.md
@@ -0,0 +1,150 @@
+# Clean-machine install test
+
+The acceptance question is narrow: **following only `README.md`, with no
+tribal knowledge, does a fresh clone reach a running system that processes a
+real event?**
+
+This records an actual run, including what went wrong, because an install
+document that only describes the happy path is the reason people say software
+is hard to install.
+
+---
+
+## What was run
+
+Date: 2026-09-23 · macOS 15 on Apple Silicon (arm64) · Docker 29.5.2 ·
+8 CPUs / 16 GB allocated to Docker.
+
+Only commands printed in `README.md` were used.
+
+```bash
+git clone https://github.com/beenuar/AiSOC && cd AiSOC
+make up
+make smoke
+```
+
+## Result
+
+| Stage | Result |
+|---|---|
+| Clone | pass |
+| `make up` — CORE profile, 10 services | pass |
+| Postgres accepting connections, 92 tables | pass |
+| Kafka broker answering admin requests | pass |
+| `api`, `ingest-worker`, `fusion` healthy | pass |
+| `make smoke` — 8 of 8 stages | pass |
+| Alert visible via `GET /api/v1/alerts` | pass |
+| `make doctor` — no failures | pass |
+
+Observed `make smoke` output:
+
+```
+[PASS] ingest service is reachable
+[PASS] api service is reachable
+[PASS] raw telemetry accepted by ingest
+[PASS] event traversed the spine and became an alert
+[PASS] alert is retrievable by id from the API
+[PASS] severity survived normalization
+[PASS] source attribution is not duplicated
+[PASS] description is prose, not a serialized payload
+
+PASS: 8/8 stages
+```
+
+---
+
+## What went wrong on the way, and what changed because of it
+
+Every one of these was hit during the real run. They are listed because each
+produced a fix, not to pad the document.
+
+### 1. Port 5432 was already taken
+
+Another project held Postgres. Compose failed with
+`Bind for 0.0.0.0:5432 failed: port is already allocated`, which does not say
+which service needs it or what to do.
+
+**Changed:** `make doctor` checks all six host ports first, distinguishes "in
+use by aisoc" from "held by something else", and prints the `lsof` command
+that identifies the holder.
+
+### 2. Docker ran out of disk, and Kafka reported healthy anyway
+
+The Docker VM filled up. Kafka failed to write `meta.properties`
+(`java.io.IOException: No space left on device`), then refused every request
+— while its compose healthcheck continued to report **healthy**. Fusion
+logged `Unable to update metadata` and ingest returned
+`failed to publish events`. Nothing pointed at disk.
+
+This is the most expensive failure in the list: three symptoms, none naming
+the cause.
+
+**Changed:**
+- `make doctor` checks Docker's free disk **before anything else** and fails
+ below 5 GB with the exact reason.
+- The doctor probes Kafka with a real admin call (`kafka-topics --list`)
+ rather than trusting the container healthcheck.
+- The troubleshooting table in `README.md` names this symptom explicitly.
+- The CI workflow reclaims runner disk before starting the stack.
+
+Recovery is `docker system prune -af`, then `make clean && make up` — the
+Kafka volume has to go, because the log dir is corrupted.
+
+### 3. The first event failed to publish
+
+Before the disk issue was resolved, the topic did not exist and could not be
+created. The error — `Unknown Topic Or Partition` — reads like a
+configuration problem and is not one.
+
+**Changed:** `make smoke` prints the two commands that distinguish the cases
+when this stage fails.
+
+### 4. Alerts were labelled `"crowdstrike crowdstrike"`
+
+Visible immediately in the first successful alert. Vendor and product were
+joined without dedup, in two separate copies of the same helper — fixing one
+left the other in place.
+
+**Changed:** one shared implementation, and `make smoke` asserts the source
+label contains no repeated word.
+
+### 5. The alert description was a serialized payload
+
+The console would have shown
+`{"command_line": "powershell.exe -nop -w hidden -enc ...` where a sentence
+belongs, discarding the vendor's own description.
+
+**Changed:** the promoter prefers human text and returns empty rather than a
+dict dump. `make smoke` asserts the description does not start with `{`.
+
+---
+
+## What a clean run does *not* include
+
+Stated so the pass above is not read as broader than it is:
+
+- **The `full` profile was not exercised** in this run. ClickHouse, Neo4j,
+ Qdrant and the connectors service start under `make up-full`; that path was
+ not part of the clean-machine test.
+- **No live LLM.** No provider key was available, so agents ran their
+ deterministic offline path. AI triage quality was not measured.
+- **`install.sh` was not run end to end** on a machine without prerequisites.
+ The `make up` path was. `install.sh` now runs the same golden pipeline
+ before printing success, so the two agree.
+
+---
+
+## Re-running this test
+
+```bash
+make clean # delete all volumes, so this is genuinely a fresh start
+make up
+make doctor
+make smoke
+```
+
+`make smoke` exits non-zero if any stage fails, and names the boundary that
+broke. CI runs the same sequence on every pull request
+([`golden-pipeline.yml`](../../.github/workflows/golden-pipeline.yml)),
+including a step that stops `fusion` and asserts the test then **fails** —
+because a gate nobody has seen fail is a gate nobody knows works.
diff --git a/install.sh b/install.sh
index 4bd34fac1..f7ea88dbf 100755
--- a/install.sh
+++ b/install.sh
@@ -796,10 +796,52 @@ run_demo() {
# ─── Final banner ────────────────────────────────────────────────────────────
+# ─── Post-install verification ───────────────────────────────────────────────
+#
+# "The containers started" is not "the application works", and this installer
+# used to print a success banner purely because `pnpm aisoc:demo` exited 0.
+# A user whose pipeline was broken was told everything was fine.
+#
+# The golden pipeline posts one real event and follows it through Kafka,
+# fusion, detection and Postgres, then reads the alert back from the API. If
+# that fails, the install has failed, whatever the containers say.
+run_smoke_test() {
+ if [ "$NO_LAUNCH" = "1" ]; then
+ return 0
+ fi
+ section "Verifying the pipeline end to end"
+ local runner="$REPO_ROOT/tests/e2e/golden_pipeline/run_golden_pipeline.py"
+ if [ ! -f "$runner" ]; then
+ warn "Golden pipeline runner not found at $runner — skipping verification."
+ return 0
+ fi
+ if ! have python3; then
+ warn "python3 not on PATH — skipping pipeline verification."
+ warn "Verify manually once python3 is available: make smoke"
+ return 0
+ fi
+
+ if ( cd "$REPO_ROOT" && python3 "$runner" ); then
+ ok "Pipeline verified: a real event became a retrievable alert."
+ return 0
+ fi
+
+ err ""
+ err "The stack started, but a real event did not become an alert."
+ err "This is a genuine failure, not a warning: AiSOC is not working yet."
+ err ""
+ err "Diagnose it with:"
+ err " cd $REPO_ROOT && make doctor"
+ err ""
+ err "Then re-run the check:"
+ err " make smoke"
+ exit 5
+}
+
print_success() {
cat <<EOF
-${C_BOLD}${C_GREEN}AiSOC is up and running.${C_RESET}
+${C_BOLD}${C_GREEN}AiSOC is up and running${C_RESET}${C_GREEN}, and a real event reached the API.${C_RESET}
${C_BOLD}Web console:${C_RESET} http://localhost:3000
${C_BOLD}Showcase case:${C_RESET} http://localhost:3000/cases/INC-RT-001?tab=ledger
@@ -807,10 +849,17 @@ ${C_BOLD}${C_GREEN}AiSOC is up and running.${C_RESET}
${C_BOLD}Realtime WS:${C_RESET} ws://localhost:8086
${C_DIM}Useful commands (run from $REPO_ROOT):${C_RESET}
- pnpm aisoc:doctor # health-check the stack
- pnpm aisoc:demo:logs # tail logs
- pnpm aisoc:demo:down # stop everything and wipe demo data
- ./scripts/install/uninstall.sh # full uninstall (containers + images + repo)
+ make doctor # diagnose every dependency, with the fix for each
+ make smoke # re-run the end-to-end pipeline check
+ make status # every service and its health
+ make logs # follow logs (SERVICE=fusion to narrow)
+ make demo # load clearly-labelled synthetic data
+ make down # stop the stack, keep your data
+ make clean # stop the stack and delete all volumes
+ ./uninstall.sh # full uninstall (containers + images + repo)
+
+${C_DIM}The demo dataset is synthetic. Every row is marked is_synthetic=true and
+labelled in the console. See "Real vs synthetic data" in README.md.${C_RESET}
EOF
if [ "$DOCKER_NEEDS_NEWGRP" = "1" ]; then
@@ -861,6 +910,7 @@ main() {
ensure_env_file
run_pnpm_install
run_demo
+ run_smoke_test
print_success
}
diff --git a/scripts/doctor.sh b/scripts/doctor.sh
new file mode 100755
index 000000000..f6b7d0784
--- /dev/null
+++ b/scripts/doctor.sh
@@ -0,0 +1,286 @@
+#!/usr/bin/env bash
+#
+# AiSOC doctor — diagnose a deployment and say what to do next.
+#
+# Every check answers one question an engineer would actually ask, and a
+# failure prints the command that investigates it. The rule here is that a
+# check must probe the thing it names: "the container is running" is not
+# evidence that the service works, and this script does not report it as such.
+#
+# ./scripts/doctor.sh # diagnose the default (CORE) profile
+# ./scripts/doctor.sh --full # also check the full-profile stores
+# ./scripts/doctor.sh --quiet # only print problems
+#
+# Exit code is 0 only when every required check passes.
+set -uo pipefail
+
+PROFILE_FULL=0
+QUIET=0
+for arg in "$@"; do
+ case "$arg" in
+ --full) PROFILE_FULL=1 ;;
+ --quiet) QUIET=1 ;;
+ -h|--help)
+ sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//'
+ exit 0 ;;
+ *) echo "unknown option: $arg" >&2; exit 2 ;;
+ esac
+done
+
+if [ -t 1 ]; then
+ G=$'\033[32m'; R=$'\033[31m'; Y=$'\033[33m'; D=$'\033[2m'; B=$'\033[1m'; X=$'\033[0m'
+else
+ G=""; R=""; Y=""; D=""; B=""; X=""
+fi
+
+FAILURES=0
+WARNINGS=0
+
+# `fail() { ((N++)); }` returns the pre-increment value, which is 0 the first
+# time — under `set -e` that kills the script before it prints why. The
+# arithmetic is written as an assignment for that reason.
+pass() { [ "$QUIET" = "1" ] || printf '%s✓%s %s\n' "$G" "$X" "$1"; }
+warn() { WARNINGS=$((WARNINGS + 1)); printf '%s!%s %s\n' "$Y" "$X" "$1"; [ -n "${2:-}" ] && printf ' %sfix:%s %s\n' "$D" "$X" "$2"; return 0; }
+fail() { FAILURES=$((FAILURES + 1)); printf '%s✗%s %s\n' "$R" "$X" "$1"; [ -n "${2:-}" ] && printf ' %sfix:%s %s\n' "$D" "$X" "$2"; return 0; }
+head2() { [ "$QUIET" = "1" ] || printf '\n%s%s%s\n' "$B" "$1" "$X"; }
+
+have() { command -v "$1" >/dev/null 2>&1; }
+
+# Resolve the compose command once. Everything below runs through it so the
+# checks apply to whatever project the caller actually started.
+COMPOSE=""
+if have docker && docker compose version >/dev/null 2>&1; then
+ COMPOSE="docker compose"
+fi
+
+# `docker compose exec` needs -T when stdin is not a TTY (CI).
+dc_exec() { $COMPOSE exec -T "$@" 2>/dev/null; }
+
+svc_running() { [ -n "$($COMPOSE ps -q "$1" 2>/dev/null)" ]; }
+
+http_ok() {
+ # $1 url, $2 timeout. Prints the status code.
+ curl -s -o /dev/null -m "${2:-5}" -w '%{http_code}' "$1" 2>/dev/null || echo "000"
+}
+
+# ── 1. Host prerequisites ───────────────────────────────────────────────────
+head2 "Host"
+
+if ! have docker; then
+ fail "docker is not installed" "https://docs.docker.com/get-docker/"
+elif ! docker info >/dev/null 2>&1; then
+ fail "docker is installed but the daemon is not responding" "start Docker Desktop, or: sudo systemctl start docker"
+else
+ pass "docker daemon responding"
+fi
+
+if [ -z "$COMPOSE" ]; then
+ fail "docker compose v2 is not available" "install Docker Compose v2 (docker compose version)"
+else
+ pass "docker compose v2 available"
+fi
+
+if docker info >/dev/null 2>&1; then
+ # Disk exhaustion inside the Docker VM corrupts Kafka's log dir and the
+ # broker then reports healthy while refusing every request. That exact
+ # failure cost hours, so it is checked before anything else.
+ avail_raw="$(docker run --rm --entrypoint sh alpine:3 -c 'df -P /' 2>/dev/null | awk 'NR==2{print $4}')"
+ if [ -n "${avail_raw:-}" ]; then
+ avail_gb=$((avail_raw / 1024 / 1024))
+ if [ "$avail_gb" -lt 5 ]; then
+ fail "docker has ${avail_gb}GB free — Kafka will corrupt its log dir below ~2GB" "docker system prune -af && docker volume prune -f"
+ elif [ "$avail_gb" -lt 15 ]; then
+ warn "docker has ${avail_gb}GB free (15GB+ recommended for the full profile)" "docker system prune -af"
+ else
+ pass "docker disk space: ${avail_gb}GB free"
+ fi
+ fi
+
+ mem_bytes="$(docker info --format '{{.MemTotal}}' 2>/dev/null || echo 0)"
+ mem_gb=$((mem_bytes / 1024 / 1024 / 1024))
+ if [ "$mem_gb" -gt 0 ] && [ "$mem_gb" -lt 6 ]; then
+ fail "docker has ${mem_gb}GB RAM — CORE needs 6GB, full needs 12GB" "raise the memory limit in Docker Desktop → Settings → Resources"
+ elif [ "$mem_gb" -gt 0 ]; then
+ pass "docker memory: ${mem_gb}GB"
+ fi
+fi
+
+# ── 2. Ports ────────────────────────────────────────────────────────────────
+head2 "Ports"
+port_busy() {
+ if have lsof; then lsof -nP -iTCP:"$1" -sTCP:LISTEN >/dev/null 2>&1
+ elif have ss; then ss -ltn 2>/dev/null | grep -q ":$1 "
+ else return 1; fi
+}
+# Only flags a port held by something that is NOT our own stack.
+for spec in "5432 postgres" "6379 redis" "9092 kafka" "8000 api" "8081 ingest-worker" "3000 web"; do
+ port="${spec%% *}"; owner="${spec##* }"
+ if port_busy "$port"; then
+ if [ -n "$COMPOSE" ] && svc_running "$owner"; then
+ pass "port $port in use by aisoc $owner"
+ else
+ fail "port $port is held by another process (needed by $owner)" "lsof -nP -iTCP:$port -sTCP:LISTEN # then stop it, or change the host port in docker-compose.yml"
+ fi
+ else
+ [ "$QUIET" = "1" ] || printf '%s·%s port %s free\n' "$D" "$X" "$port"
+ fi
+done
+
+[ -z "$COMPOSE" ] && { printf '\n%sCannot check services without docker compose.%s\n' "$R" "$X"; exit 1; }
+
+# ── 3. Configuration ────────────────────────────────────────────────────────
+head2 "Configuration"
+if [ -f .env ]; then
+ pass ".env present"
+ if grep -qE '^[A-Z_]*(SECRET|PASSWORD|KEY)=(change_me|changeme|)$' .env 2>/dev/null; then
+ warn ".env has unset or placeholder secrets" "./install.sh regenerates them, or edit .env by hand"
+ fi
+else
+ warn ".env not found — compose will fall back to built-in dev defaults" "cp .env.example .env"
+fi
+
+# ── 4. Datastores — probed, not just 'running' ──────────────────────────────
+head2 "Datastores"
+
+if svc_running postgres; then
+ if dc_exec postgres pg_isready -U aisoc -d aisoc >/dev/null; then
+ pass "postgres accepting connections"
+ tables="$(dc_exec postgres psql -U aisoc -d aisoc -tAc "select count(*) from information_schema.tables where table_schema='public'" | tr -d '[:space:]')"
+ if [ "${tables:-0}" -gt 0 ] 2>/dev/null; then
+ pass "postgres schema present (${tables} tables)"
+ else
+ fail "postgres has no tables — migrations did not run" "docker compose logs api | grep -i migrat"
+ fi
+ else
+ fail "postgres container is up but not accepting connections" "docker compose logs postgres | tail -40"
+ fi
+else
+ fail "postgres is not running" "docker compose up -d postgres"
+fi
+
+if svc_running redis; then
+ # The compose default starts redis with --requirepass, so an
+ # unauthenticated PING answers NOAUTH. That is still proof the server is
+ # alive and serving, which is what this check is for — treating it as a
+ # failure reported a healthy redis as broken.
+ redis_reply="$(dc_exec redis redis-cli ping)"
+ if printf '%s' "$redis_reply" | grep -q 'PONG'; then
+ pass "redis responding to PING"
+ elif printf '%s' "$redis_reply" | grep -qi 'NOAUTH\|WRONGPASS'; then
+ pass "redis responding (authentication required, as configured)"
+ else
+ fail "redis is up but not responding to PING" "docker compose logs redis | tail -20"
+ fi
+else
+ fail "redis is not running" "docker compose up -d redis"
+fi
+
+if svc_running kafka; then
+ # `kafka-topics --list` is the check that matters: the container healthcheck
+ # passes on a broker whose log dir has failed, which is how a disk-full
+ # broker reported healthy while refusing every produce.
+ if topics="$(dc_exec kafka kafka-topics --bootstrap-server localhost:29092 --list)"; then
+ count="$(printf '%s\n' "$topics" | grep -c . || true)"
+ pass "kafka broker answering admin requests (${count} topics)"
+ if printf '%s\n' "$topics" | grep -q '^aisoc\.raw_events$'; then
+ pass "topic aisoc.raw_events exists"
+ else
+ warn "topic aisoc.raw_events does not exist yet" "it is auto-created on the first ingested event; send one with: make smoke"
+ fi
+ else
+ fail "kafka is up but not answering admin requests" "docker compose logs kafka | grep -iE 'no space|error' | tail -20"
+ fi
+else
+ fail "kafka is not running" "docker compose up -d kafka"
+fi
+
+if [ "$PROFILE_FULL" = "1" ]; then
+ head2 "Full-profile stores"
+ for spec in "clickhouse 8123 /ping" "neo4j 7474 /" "qdrant 6333 /readyz" "opensearch 9200 /"; do
+ set -- $spec; name="$1"; port="$2"; path="$3"
+ if svc_running "$name"; then
+ code="$(dc_exec "$name" sh -c "wget -qO- -T 3 http://localhost:${port}${path} >/dev/null 2>&1 && echo 200 || echo 000")"
+ if [ "$code" = "200" ]; then pass "$name responding on $port"
+ else warn "$name is running but did not answer http://localhost:${port}${path}" "docker compose logs $name | tail -20"; fi
+ else
+ warn "$name is not running (full profile)" "docker compose --profile full up -d $name"
+ fi
+ done
+fi
+
+# ── 5. Services ─────────────────────────────────────────────────────────────
+head2 "Services"
+
+check_http_service() {
+ local name="$1" url="$2" hint="$3"
+ if ! svc_running "$name"; then
+ fail "$name is not running" "docker compose up -d $name"
+ return
+ fi
+ local code; code="$(http_ok "$url" 6)"
+ case "$code" in
+ 200|204) pass "$name healthy ($url)" ;;
+ 000) fail "$name is running but $url did not respond" "$hint" ;;
+ *) fail "$name returned HTTP $code from $url" "$hint" ;;
+ esac
+}
+
+check_http_service api "${AISOC_API_URL:-http://localhost:8000}/health" "docker compose logs api | tail -40"
+check_http_service ingest-worker "${AISOC_INGEST_URL:-http://localhost:8081}/health" "docker compose logs ingest-worker | tail -40"
+
+# Fusion has no HTTP health route in every build, so it is checked by whether
+# its consumer actually joined the group — the thing that matters.
+if svc_running fusion; then
+ # Probe the service rather than grepping its log. A log line scrolls out of
+ # retention and a restart loses it, so log-grep reported a working fusion as
+ # broken. The HTTP probe answers the same question durably.
+ fusion_code="$(http_ok "${AISOC_FUSION_URL:-http://localhost:8003}/health" 6)"
+ if [ "$fusion_code" = "200" ]; then
+ pass "fusion healthy"
+ elif $COMPOSE logs fusion 2>/dev/null | grep -q 'Fusion worker started'; then
+ warn "fusion started but its HTTP health route did not answer" "docker compose logs fusion | tail -40"
+ else
+ fail "fusion is running but neither healthy nor started" "docker compose logs fusion | tail -60"
+ fi
+ if $COMPOSE logs fusion 2>/dev/null | grep -qi 'GroupCoordinatorNotAvailable\|Unable to update metadata'; then
+ warn "fusion reported Kafka metadata errors (may be transient at boot)" "docker compose logs fusion | grep -i kafka | tail -20"
+ fi
+else
+ fail "fusion is not running — events will never become alerts" "docker compose up -d fusion"
+fi
+
+for spec in "web 3000 /" "realtime 8086 /health" "agents 8001 /health"; do
+ set -- $spec; name="$1"; port="$2"; path="$3"
+ if svc_running "$name"; then
+ code="$(http_ok "http://localhost:${port}${path}" 6)"
+ if [ "$code" = "200" ] || [ "$code" = "204" ]; then pass "$name healthy"
+ else warn "$name is running but http://localhost:${port}${path} returned $code" "docker compose logs $name | tail -30"; fi
+ else
+ warn "$name is not running" "docker compose up -d $name"
+ fi
+done
+
+# ── 6. Pipeline ─────────────────────────────────────────────────────────────
+head2 "Pipeline"
+alerts="$(dc_exec postgres psql -U aisoc -d aisoc -tAc 'select count(*) from alerts' | tr -d '[:space:]')"
+if [ -n "${alerts:-}" ]; then
+ if [ "${alerts:-0}" -gt 0 ] 2>/dev/null; then
+ pass "alerts table has ${alerts} row(s)"
+ else
+ warn "no alerts yet — the pipeline has not produced one" "prove it end to end: make smoke"
+ fi
+fi
+
+# ── Summary ─────────────────────────────────────────────────────────────────
+printf '\n'
+if [ "$FAILURES" -eq 0 ] && [ "$WARNINGS" -eq 0 ]; then
+ printf '%sAll checks passed.%s Prove the pipeline with: %smake smoke%s\n\n' "$G$B" "$X" "$B" "$X"
+ exit 0
+fi
+if [ "$FAILURES" -eq 0 ]; then
+ printf '%s%d warning(s), no failures.%s AiSOC should work; see the notes above.\n\n' "$Y" "$WARNINGS" "$X"
+ exit 0
+fi
+printf '%s%d check(s) failed%s, %d warning(s).\n' "$R$B" "$FAILURES" "$X" "$WARNINGS"
+printf 'Fix the failures above, then re-run: %s./scripts/doctor.sh%s\n\n' "$B" "$X"
+exit 1
diff --git a/scripts/project_stats.py b/scripts/project_stats.py
new file mode 100755
index 000000000..95c17abc6
--- /dev/null
+++ b/scripts/project_stats.py
@@ -0,0 +1,214 @@
+#!/usr/bin/env python3
+"""Recount every figure the README publishes, from the tree.
+
+A number typed into a README is a number that goes stale silently. This
+script is the single source for the project's quantitative claims, and
+`--check` fails when the README disagrees with it — so a figure cannot drift
+without a red build.
+
+Each figure counts the thing the claim is *about*, which is not always the
+obvious file count:
+
+* **Connectors** come from the registry the service actually loads, not from
+ the number of files in the connectors directory. A module that is not
+ registered is not a connector a user can configure.
+* **Detections** count what the *engine* loads. `detections/*.yaml` is a
+ generated projection and includes thousands of quarantined imports the
+ engine never evaluates; publishing that number would overstate coverage by
+ an order of magnitude.
+* **Services** count deployable compose services, split by profile, because
+ "19 services" means something very different if 10 of them are optional.
+
+Usage:
+ python3 scripts/project_stats.py # human-readable
+ python3 scripts/project_stats.py --json # machine-readable
+ python3 scripts/project_stats.py --check # fail if README disagrees
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+
+
+def _connectors() -> int | None:
+ """Registered connector classes, read from the registry literal."""
+ init = ROOT / "services" / "connectors" / "app" / "connectors" / "__init__.py"
+ if not init.is_file():
+ return None
+ text = init.read_text(encoding="utf-8")
+ match = re.search(r"_CONNECTOR_CLASSES\s*[:=][^=]*=\s*[\(\[\{](.*?)[\)\]\}]\s*\n", text, re.S)
+ if not match:
+ return None
+ # Count class references, not commas: a trailing comma would inflate it.
+ return len(re.findall(r"\b[A-Z]\w*Connector\b", match.group(1)))
+
+
+def _executable_detections() -> int | None:
+ """Rules the fusion engine loads — the only ones that can fire."""
+ ruleset = ROOT / "services" / "fusion" / "app" / "data" / "detection_ruleset.json"
+ if not ruleset.is_file():
+ return None
+ try:
+ data = json.loads(ruleset.read_text(encoding="utf-8"))
+ except ValueError:
+ return None
+ rules = data.get("rules") if isinstance(data, dict) else data
+ return len(rules) if isinstance(rules, list) else None
+
+
+def _detection_files_on_disk() -> int:
+ """Every YAML under detections/, including the quarantine.
+
+ Reported alongside the executable count so the gap is visible rather than
+ conflated. The two numbers have been published interchangeably before.
+ """
+ d = ROOT / "detections"
+ return sum(1 for _ in d.rglob("*.yaml")) if d.is_dir() else 0
+
+
+def _compose_services() -> dict[str, int]:
+ """Deployable services, split by profile."""
+ try:
+ import yaml
+ except ImportError:
+ return {}
+ f = ROOT / "docker-compose.yml"
+ if not f.is_file():
+ return {}
+ doc = yaml.safe_load(f.read_text(encoding="utf-8")) or {}
+ services = doc.get("services") or {}
+ core = [n for n, s in services.items() if not (s or {}).get("profiles")]
+ return {"core": len(core), "total": len(services), "optional": len(services) - len(core)}
+
+
+def _claim_gate_rows() -> dict[str, int]:
+ """Claim-to-gate matrix rows by status."""
+ f = ROOT / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md"
+ if not f.is_file():
+ return {}
+ counts = {"GATED": 0, "PARTIAL": 0, "NO GATE": 0}
+ for line in f.read_text(encoding="utf-8").splitlines():
+ if not line.startswith("| ") or line.startswith("| ---"):
+ continue
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
+ if len(cells) < 4:
+ continue
+ status = cells[3].upper()
+ # `GATED (ratchet)` counts as gated; check NO GATE first so the
+ # substring "GATE" does not swallow it.
+ if "NO GATE" in status:
+ counts["NO GATE"] += 1
+ elif "PARTIAL" in status:
+ counts["PARTIAL"] += 1
+ elif "GATED" in status:
+ counts["GATED"] += 1
+ counts["total"] = counts["GATED"] + counts["PARTIAL"] + counts["NO GATE"]
+ return counts
+
+
+def _python_services() -> int:
+ d = ROOT / "services"
+ return sum(1 for p in d.iterdir() if p.is_dir() and not p.name.startswith(".")) if d.is_dir() else 0
+
+
+def collect() -> dict:
+ stats: dict = {
+ "connectors": _connectors(),
+ "detections_executable": _executable_detections(),
+ "detections_files_on_disk": _detection_files_on_disk(),
+ "services_in_repo": _python_services(),
+ "compose": _compose_services(),
+ "claim_gate": _claim_gate_rows(),
+ }
+ version = ROOT / "VERSION"
+ if version.is_file():
+ stats["version"] = version.read_text(encoding="utf-8").strip()
+ return stats
+
+
+def _render(stats: dict) -> str:
+ c = stats["compose"]
+ g = stats["claim_gate"]
+ lines = [
+ "",
+ f" AiSOC {stats.get('version', '?')} — figures recounted from the tree",
+ "",
+ f" Connectors (registered) {stats['connectors']}",
+ f" Detections (engine loads) {stats['detections_executable']}",
+ f" Detection files on disk {stats['detections_files_on_disk']} (includes quarantined imports the engine never evaluates)",
+ f" Services in repo {stats['services_in_repo']}",
+ ]
+ if c:
+ lines.append(f" Compose services {c['core']} core + {c['optional']} optional = {c['total']}")
+ if g:
+ lines.append(
+ f" Claim-to-gate matrix {g['total']} rows — {g['GATED']} gated, {g['PARTIAL']} partial, {g['NO GATE']} ungated"
+ )
+ lines.append("")
+ return "\n".join(lines)
+
+
+#: README phrases that must agree with the counts above. Each is a
+#: (regex, stat-path) pair; the regex must capture the number in group 1.
+README_CLAIMS: list[tuple[str, tuple[str, ...]]] = [
+ (r"\*\*(\d+) click-and-connect data connectors\*\*", ("connectors",)),
+ (r"(\d+) executable detection", ("detections_executable",)),
+ (r"(\d+) GATED", ("claim_gate", "GATED")),
+]
+
+
+def _lookup(stats: dict, path: tuple[str, ...]):
+ cur = stats
+ for key in path:
+ cur = cur.get(key) if isinstance(cur, dict) else None
+ if cur is None:
+ return None
+ return cur
+
+
+def check(stats: dict) -> int:
+ readme = ROOT / "README.md"
+ if not readme.is_file():
+ print("README.md not found", file=sys.stderr)
+ return 1
+ text = readme.read_text(encoding="utf-8")
+ failures = []
+ for pattern, path in README_CLAIMS:
+ expected = _lookup(stats, path)
+ if expected is None:
+ continue
+ for match in re.finditer(pattern, text):
+ claimed = int(match.group(1))
+ if claimed != expected:
+ failures.append(f"README claims {claimed} for {'.'.join(path)}; the tree has {expected} (pattern: {pattern})")
+ if failures:
+ print("project-stats: README disagrees with the tree\n", file=sys.stderr)
+ for f in failures:
+ print(f" {f}", file=sys.stderr)
+ print("\nRe-run `make stats` and correct the README.\n", file=sys.stderr)
+ return 1
+ print("project-stats: OK — every checked README figure matches the tree")
+ return 0
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument("--json", action="store_true", help="emit machine-readable JSON")
+ ap.add_argument("--check", action="store_true", help="fail if the README disagrees")
+ args = ap.parse_args()
+
+ stats = collect()
+ if args.check:
+ return check(stats)
+ print(json.dumps(stats, indent=2) if args.json else _render(stats))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/services/api/app/api/v1/endpoints/deployment.py b/services/api/app/api/v1/endpoints/deployment.py
index e39de14c7..90740cb4e 100644
--- a/services/api/app/api/v1/endpoints/deployment.py
+++ b/services/api/app/api/v1/endpoints/deployment.py
@@ -123,15 +123,24 @@ async def get_airgap_status() -> AirgapStatus:
"passed": local_llm_up,
"detail": "Local LLM running" if local_llm_up else "No local LLM configured",
},
+ # These two used to report `passed: True` with invented detail
+ # strings ("Bundle v2025.05.30 available", "487 rules loaded from
+ # offline bundle"). Nothing was measured — the booleans were literals,
+ # and the rule count contradicted the real corpus. An operator
+ # planning an air-gapped cutover would have read a green check for a
+ # bundle that was never inspected.
+ #
+ # Reported as not-checked until a real probe exists. "We did not
+ # verify this" is a usable answer; a fabricated pass is not.
{
"name": "offline_bundle",
- "passed": True,
- "detail": "Bundle v2025.05.30 available",
+ "passed": False,
+ "detail": "Not checked — no offline-bundle probe is implemented yet.",
},
{
"name": "detection_rules",
- "passed": True,
- "detail": "487 rules loaded from offline bundle",
+ "passed": False,
+ "detail": ("Not checked — the running rule count is reported by the fusion detection engine, not by this endpoint."),
},
{
"name": "threat_intel",
diff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.py
index b6485f0fc..ed9ff73a3 100644
--- a/services/api/app/api/v1/endpoints/mssp.py
+++ b/services/api/app/api/v1/endpoints/mssp.py
@@ -11,6 +11,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.endpoints.auth import get_current_user
+from app.core.config import settings
from app.db.database import get_db
from app.models.mssp import MSSPDelegation, MSSPTenantMetrics, MSSPTenantNote
from app.models.tenant import Tenant, User
@@ -762,12 +763,43 @@ _MSSP_INCIDENTS_MOCK = [
]
+# The three rollup routes below have no implementation behind them — the
+# cross-tenant aggregation query was never written. They returned the
+# hardcoded rows above to *authenticated* callers with no demo check and no
+# marker, so "Acme Corp, health 92.4, 12 open alerts" was indistinguishable
+# from a measurement. Fabricated security posture presented as real is the one
+# thing this project will not ship.
+#
+# They now serve that sample only in demo mode, and return empty outside it.
+# An empty rollup is the truthful answer: nothing has been aggregated.
+
+
+def _mssp_sample_allowed() -> bool:
+ return bool(settings.AISOC_DEMO_MODE)
+
+
@router.get("/overview", response_model=MSSPKpiOverview)
async def mssp_overview(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> MSSPKpiOverview:
- """Cross-tenant KPI summary for the MSSP parent dashboard."""
+ """Cross-tenant KPI summary for the MSSP parent dashboard.
+
+ Not yet implemented against real data. Returns zeros outside demo mode
+ rather than the sample figures, because a dashboard reading 23.4 minutes
+ MTTR that nobody measured is worse than one reading nothing.
+ """
+ if not _mssp_sample_allowed():
+ return MSSPKpiOverview(
+ total_tenants=0,
+ total_open_alerts=0,
+ total_critical_incidents=0,
+ avg_health_score=0.0,
+ avg_mttr_minutes=0.0,
+ sla_breach_count=0,
+ connectors_online=0,
+ connectors_degraded=0,
+ )
tenants = _MSSP_TENANTS_MOCK
return MSSPKpiOverview(
total_tenants=len(tenants),
@@ -786,7 +818,13 @@ async def list_managed_tenants(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[ManagedTenantRow]:
- """List managed tenants with health scores for the parent dashboard."""
+ """List managed tenants with health scores for the parent dashboard.
+
+ Empty outside demo mode. `GET /api/v1/mssp/children` is the route backed
+ by real rows.
+ """
+ if not _mssp_sample_allowed():
+ return []
return _MSSP_TENANTS_MOCK
@@ -796,7 +834,9 @@ async def list_cross_tenant_incidents(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[CrossTenantIncident]:
- """Critical incidents across all managed tenants."""
+ """Critical incidents across all managed tenants. Empty outside demo mode."""
+ if not _mssp_sample_allowed():
+ return []
incidents = _MSSP_INCIDENTS_MOCK
if severity:
incidents = [i for i in incidents if i.severity == severity]
diff --git a/services/api/app/scripts/seed_demo.py b/services/api/app/scripts/seed_demo.py
index ed7e92ac1..f1b00ab4b 100644
--- a/services/api/app/scripts/seed_demo.py
+++ b/services/api/app/scripts/seed_demo.py
@@ -31,6 +31,7 @@ from __future__ import annotations
import argparse
import asyncio
import hashlib
+import os
import random
import sys
import uuid
@@ -3322,6 +3323,33 @@ async def _main_async(args: argparse.Namespace) -> None:
await _run_full_seed()
+def _refuse_in_production() -> None:
+ """Refuse to write synthetic incidents into a production database.
+
+ This script had no guard at all: it parsed its arguments and ran against
+ whatever `DATABASE_URL` resolved to. Containment rested entirely on it
+ targeting a hardcoded demo tenant id, which is a convention rather than a
+ control — and the rows it writes are deliberately realistic, which is
+ exactly what makes them dangerous in the wrong database.
+
+ Set `AISOC_ALLOW_SEED=1` to override (that is what `make demo` does).
+ """
+ allow = os.environ.get("AISOC_ALLOW_SEED", "").strip().lower() in {"1", "true", "yes"}
+ if allow:
+ return
+ env = (os.environ.get("ENVIRONMENT") or os.environ.get("ENV") or "").strip().lower()
+ demo_mode = os.environ.get("AISOC_DEMO_MODE", "").strip().lower() in {"1", "true", "yes"}
+ if demo_mode or env in {"", "dev", "development", "local", "test"}:
+ return
+ print(
+ f"[seed] refusing to run: ENVIRONMENT={env!r} is not a development environment.\n"
+ f"[seed] This writes synthetic security incidents. If that is genuinely what\n"
+ f"[seed] you want here, re-run with AISOC_ALLOW_SEED=1.",
+ file=sys.stderr,
+ )
+ sys.exit(2)
+
+
def main(argv: list[str] | None = None) -> None:
# `parse_known_args` is intentional — `app.scripts.demo_seed` (the
# hosted-demo wrapper) imports this `main` and calls it without
@@ -3330,6 +3358,7 @@ def main(argv: list[str] | None = None) -> None:
# Silently ignoring unknown tokens keeps that path working without
# having to coordinate two argparse surfaces.
args, _unknown = _build_arg_parser().parse_known_args(argv)
+ _refuse_in_production()
asyncio.run(_main_async(args))
diff --git a/services/api/migrations/054_alert_provenance.sql b/services/api/migrations/054_alert_provenance.sql
new file mode 100644
index 000000000..b4a6d09ac
--- /dev/null
+++ b/services/api/migrations/054_alert_provenance.sql
@@ -0,0 +1,40 @@
+-- Alert provenance: is this row real telemetry, or did we generate it?
+--
+-- Until now nothing in the schema answered that question. `alerts` carried
+-- ~50 columns describing what happened and none recording where the row came
+-- from, so a seeded demo incident and a CrowdStrike detection were
+-- indistinguishable once written. The only marker was a `"demo"` string
+-- pushed into the `tags` array by some seed paths and not others — and the
+-- paths that produced the most realistic-looking incidents were the ones that
+-- omitted it.
+--
+-- That is the wrong way round. Provenance has to be a column, so it survives
+-- a query the UI did not anticipate, and it has to default to the honest
+-- value: rows written by the real pipeline are not synthetic, and anything
+-- that wants to claim otherwise must say so explicitly.
+--
+-- Note the existing `detection_rules.provenance` JSONB means something
+-- different (which Sigma repo a rule was imported from). This is about the
+-- alert row, not the rule.
+
+ALTER TABLE alerts
+ ADD COLUMN IF NOT EXISTS is_synthetic BOOLEAN NOT NULL DEFAULT FALSE,
+ -- Free-form, e.g. 'seed_demo', 'demo-producer', 'golden-pipeline'.
+ -- NULL for real telemetry.
+ ADD COLUMN IF NOT EXISTS synthetic_source TEXT,
+ -- Which scenario produced it, when the generator has scenarios. Lets a
+ -- reviewer clear one scenario's rows without touching another's.
+ ADD COLUMN IF NOT EXISTS synthetic_scenario TEXT;
+
+COMMENT ON COLUMN alerts.is_synthetic IS
+ 'TRUE when this alert was generated (seed, demo producer, test fixture) rather than ingested from a real sensor. Defaults FALSE so the real pipeline is never mislabelled.';
+COMMENT ON COLUMN alerts.synthetic_source IS
+ 'Generator that produced a synthetic alert (seed_demo, demo-producer, golden-pipeline). NULL for real telemetry.';
+COMMENT ON COLUMN alerts.synthetic_scenario IS
+ 'Scenario identifier within the generator, when it has one.';
+
+-- Partial index: the common query is "show me only the real alerts", and the
+-- synthetic rows are the minority, so indexing just those keeps it small.
+CREATE INDEX IF NOT EXISTS idx_alerts_is_synthetic
+ ON alerts (tenant_id, is_synthetic)
+ WHERE is_synthetic = TRUE;
diff --git a/services/fusion/app/services/promoter.py b/services/fusion/app/services/promoter.py
index 9ced99e3e..bd55e2b67 100644
--- a/services/fusion/app/services/promoter.py
+++ b/services/fusion/app/services/promoter.py
@@ -34,7 +34,7 @@ from typing import Any
import structlog
from app.models.alert import AlertSeverity, RawAlert
-from app.services.provenance import extract_provenance
+from app.services.provenance import extract_provenance, product_label
logger = structlog.get_logger()
@@ -109,10 +109,44 @@ def _title(ocsf: dict[str, Any]) -> str:
def _source(ocsf: dict[str, Any]) -> str:
- vendor = _get_nested(ocsf, "metadata", "product", "vendor_name")
- product = _get_nested(ocsf, "metadata", "product", "name")
- parts = [p for p in (vendor, product) if isinstance(p, str) and p]
- return " ".join(parts) or "ingest"
+ """Human-readable origin, e.g. "CrowdStrike Falcon" or "crowdstrike".
+
+ Delegates to `provenance.product_label` so the vendor/product join exists
+ once. Two copies of it used to exist, and fixing only this one left
+ `connector_type` still reading "crowdstrike crowdstrike" on the alert row.
+ """
+ return product_label(ocsf) or "ingest"
+
+
+def _description(ocsf: dict[str, Any]) -> str:
+ """Prefer a human sentence over a serialized payload.
+
+ This used to be `str(ocsf.get("raw_data"))`, so every alert's description
+ was the whole event dumped as a Python dict repr — unreadable in the
+ console, and it discarded the vendor's own description even when one was
+ supplied. Verified against a live stack: a CrowdStrike event carrying
+ "powershell.exe -enc ... spawned by winword.exe" produced a description
+ that began `{"command_line": "powershell.exe ...`.
+
+ The raw payload is not lost: it stays on the alert's `raw_event`, which is
+ what the investigation surfaces read.
+ """
+ raw = ocsf.get("raw_data")
+ if isinstance(raw, dict):
+ for key in ("description", "message", "summary", "detail", "reason"):
+ value = raw.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()[:2000]
+ finding_desc = _get_nested(ocsf, "finding", "desc")
+ if isinstance(finding_desc, str) and finding_desc.strip():
+ return finding_desc.strip()[:2000]
+ message = ocsf.get("message")
+ if isinstance(message, str) and message.strip():
+ return message.strip()[:2000]
+ # Nothing human-authored anywhere. An empty description is more honest
+ # than a dict repr pretending to be prose; the console renders the raw
+ # event beneath it either way.
+ return ""
def _event_time(ocsf: dict[str, Any]) -> datetime | None:
@@ -168,7 +202,7 @@ def promote_normalized_event(message: dict[str, Any]) -> RawAlert | None:
tenant_id=tenant_id,
source=_source(ocsf),
title=_title(ocsf),
- description=str(ocsf.get("raw_data") or "")[:2000],
+ description=_description(ocsf),
severity=severity,
src_ip=_get_nested(ocsf, "src_endpoint", "ip"),
dst_ip=_get_nested(ocsf, "dst_endpoint", "ip"),
diff --git a/services/fusion/app/services/provenance.py b/services/fusion/app/services/provenance.py
index 3c9cf2c8e..7d7d03a6e 100644
--- a/services/fusion/app/services/provenance.py
+++ b/services/fusion/app/services/provenance.py
@@ -28,17 +28,36 @@ def _parse_uuid(value: Any) -> uuid.UUID | None:
return None
-def _product_label(ocsf: dict[str, Any]) -> str | None:
+def product_label(ocsf: dict[str, Any]) -> str | None:
+ """Vendor + product, deduplicated.
+
+ Most connectors set `vendor_name` and `name` to the same string, so a
+ naive join produced `connector_type = "crowdstrike crowdstrike"` on every
+ alert. Verified on a live stack.
+
+ This is the single implementation. `promoter._source()` delegates here;
+ there used to be two copies of the join and only one of them was fixed,
+ which is why the doubled label survived the first repair.
+ """
meta = ocsf.get("metadata") if isinstance(ocsf, dict) else None
product = meta.get("product") if isinstance(meta, dict) else None
if not isinstance(product, dict):
return None
- vendor = product.get("vendor_name")
- name = product.get("name")
- parts = [p for p in (vendor, name) if isinstance(p, str) and p]
+ parts: list[str] = []
+ for value in (product.get("vendor_name"), product.get("name")):
+ if not isinstance(value, str) or not value.strip():
+ continue
+ cleaned = value.strip()
+ if any(cleaned.lower() == seen.lower() for seen in parts):
+ continue
+ parts.append(cleaned)
return " ".join(parts) or None
+#: Retained so existing imports keep working.
+_product_label = product_label
+
+
def extract_provenance(
message: dict[str, Any],
ocsf: dict[str, Any] | None = None,
diff --git a/services/fusion/tests/test_promoter_alert_text.py b/services/fusion/tests/test_promoter_alert_text.py
new file mode 100644
index 000000000..c3c96d6a3
--- /dev/null
+++ b/services/fusion/tests/test_promoter_alert_text.py
@@ -0,0 +1,101 @@
+"""An alert's source and description are what an analyst reads first.
+
+Both were wrong, and both were found by pushing one real event through a live
+CORE stack rather than by reading code:
+
+* `connector_type` came back as **"crowdstrike crowdstrike"**, because
+ `_source()` joined `vendor_name` and `name` without noticing they were the
+ same string. Most connectors set both.
+* `description` came back as ``{"command_line": "powershell.exe -nop -w ...``
+ — the whole event serialized with `str()` — while the vendor's own
+ human-written description was discarded.
+"""
+
+from __future__ import annotations
+
+from app.services.promoter import _description, _source
+
+
+def _ocsf(vendor: str | None, product: str | None, **rest) -> dict:
+ meta: dict = {"product": {}}
+ if vendor is not None:
+ meta["product"]["vendor_name"] = vendor
+ if product is not None:
+ meta["product"]["name"] = product
+ return {"metadata": meta, **rest}
+
+
+# ── source ────────────────────────────────────────────────────────────────
+
+
+def test_a_vendor_repeated_as_the_product_is_not_doubled() -> None:
+ """The live regression."""
+ assert _source(_ocsf("crowdstrike", "crowdstrike")) == "crowdstrike"
+
+
+def test_the_dedup_is_case_insensitive() -> None:
+ """Both spellings appear across connectors, so the dedup ignores case."""
+ assert _source(_ocsf("CrowdStrike", "crowdstrike")) == "CrowdStrike"
+
+
+def test_a_genuine_vendor_and_product_are_both_kept() -> None:
+ assert _source(_ocsf("CrowdStrike", "Falcon")) == "CrowdStrike Falcon"
+
+
+def test_either_half_alone_is_enough() -> None:
+ assert _source(_ocsf("Splunk", None)) == "Splunk"
+ assert _source(_ocsf(None, "Sentinel")) == "Sentinel"
+
+
+def test_no_product_metadata_falls_back_to_ingest() -> None:
+ assert _source({"metadata": {}}) == "ingest"
+
+
+def test_blank_strings_are_not_treated_as_a_name() -> None:
+ assert _source(_ocsf(" ", "")) == "ingest"
+
+
+# ── description ───────────────────────────────────────────────────────────
+
+
+def test_the_vendors_own_description_wins() -> None:
+ """The live regression: this text was thrown away."""
+ ocsf = {
+ "raw_data": {
+ "description": "powershell.exe -enc JABzAD0A spawned by winword.exe",
+ "command_line": "powershell.exe -nop -w hidden -enc JABzAD0A",
+ "host": "WIN-FIN-01",
+ }
+ }
+ assert _description(ocsf) == "powershell.exe -enc JABzAD0A spawned by winword.exe"
+
+
+def test_a_description_is_never_a_serialized_payload() -> None:
+ """The property that actually matters, stated directly."""
+ ocsf = {"raw_data": {"command_line": "whoami", "host": "WIN-01", "pid": 4242}}
+ result = _description(ocsf)
+ assert not result.startswith("{"), f"description is a dict dump: {result[:60]}"
+ assert "'pid'" not in result and '"pid"' not in result
+
+
+def test_alternative_human_keys_are_accepted() -> None:
+ for key in ("message", "summary", "detail", "reason"):
+ assert _description({"raw_data": {key: f"via {key}"}}) == f"via {key}"
+
+
+def test_a_security_finding_description_is_used() -> None:
+ assert _description({"finding": {"desc": "Notable: brute force"}}) == "Notable: brute force"
+
+
+def test_a_top_level_message_is_used_when_nothing_else_is() -> None:
+ assert _description({"message": "Impossible travel detected"}) == "Impossible travel detected"
+
+
+def test_nothing_human_anywhere_yields_empty_not_a_dump() -> None:
+ """An empty description is more honest than a dict repr pretending to be
+ prose. The console renders the raw event beneath it either way."""
+ assert _description({"raw_data": {"a": 1, "b": 2}}) == ""
+
+
+def test_descriptions_are_capped() -> None:
+ assert len(_description({"raw_data": {"description": "x" * 5000}})) == 2000
diff --git a/tests/e2e/golden_pipeline/run_golden_pipeline.py b/tests/e2e/golden_pipeline/run_golden_pipeline.py
new file mode 100755
index 000000000..4025f44b3
--- /dev/null
+++ b/tests/e2e/golden_pipeline/run_golden_pipeline.py
@@ -0,0 +1,229 @@
+#!/usr/bin/env python3
+"""The golden pipeline: one real event through the real stack.
+
+This is the canonical proof that AiSOC works end to end. It pushes a single
+suspicious-PowerShell event into the ingest HTTP API and then follows it
+through the actual production path — Kafka, fusion, detection, promotion,
+Postgres — and finally reads it back out of the public API.
+
+What it deliberately does NOT do
+================================
+
+It does not insert an alert. It does not call fusion's internals. It does not
+stub Kafka. Every stage is observed from the outside, because a test that
+reaches past a component cannot tell you that component works. The only thing
+it asserts about the internals is what an operator could also check.
+
+Each stage reports PASS or FAIL independently, so a break names the boundary
+that broke rather than "the pipeline failed".
+
+Usage
+=====
+
+ python3 tests/e2e/golden_pipeline/run_golden_pipeline.py
+
+Environment (all optional; defaults match `docker compose up`):
+
+ AISOC_INGEST_URL default http://localhost:8081
+ AISOC_API_URL default http://localhost:8000
+ AISOC_TENANT_ID default the seeded canonical tenant
+ AISOC_GOLDEN_TIMEOUT seconds to wait for the alert (default 90)
+
+Exit code is 0 only when every stage passes.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import time
+import urllib.error
+import urllib.request
+import uuid
+from dataclasses import dataclass, field
+
+INGEST_URL = os.environ.get("AISOC_INGEST_URL", "http://localhost:8081").rstrip("/")
+API_URL = os.environ.get("AISOC_API_URL", "http://localhost:8000").rstrip("/")
+TENANT_ID = os.environ.get("AISOC_TENANT_ID", "00000000-0000-0000-0000-000000000001")
+TIMEOUT_SECONDS = int(os.environ.get("AISOC_GOLDEN_TIMEOUT", "90"))
+
+#: Unique per run so a re-run cannot pass by finding the previous run's alert
+#: — the failure mode that makes an end-to-end test permanently green.
+RUN_ID = uuid.uuid4().hex[:12]
+ALERT_TITLE = f"Golden pipeline: encoded PowerShell from Office [{RUN_ID}]"
+
+
+@dataclass
+class Report:
+ stages: list[tuple[str, bool, str]] = field(default_factory=list)
+
+ def record(self, name: str, ok: bool, detail: str = "") -> bool:
+ self.stages.append((name, ok, detail))
+ mark = "PASS" if ok else "FAIL"
+ line = f" [{mark}] {name}"
+ if detail:
+ line += f" — {detail}"
+ print(line, flush=True)
+ return ok
+
+ @property
+ def ok(self) -> bool:
+ return all(ok for _, ok, _ in self.stages)
+
+
+def _request(method: str, url: str, body: dict | None = None, timeout: float = 20.0) -> tuple[int, str]:
+ data = json.dumps(body).encode() if body is not None else None
+ req = urllib.request.Request(url, data=data, method=method)
+ req.add_header("Content-Type", "application/json")
+ req.add_header("X-Tenant-ID", TENANT_ID)
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 - fixed local URLs
+ return resp.status, resp.read().decode("utf-8", "replace")
+ except urllib.error.HTTPError as exc:
+ return exc.code, exc.read().decode("utf-8", "replace")
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
+ return 0, str(exc)
+
+
+def golden_event() -> dict:
+ """A realistic Windows endpoint detection.
+
+ Office spawning an encoded PowerShell child is a genuine, widely-detected
+ pattern (T1059.001 with T1566 delivery), so the alert this produces is
+ recognisable rather than arbitrary.
+ """
+ return {
+ "connector_id": f"golden-pipeline-{RUN_ID}",
+ "connector_type": "crowdstrike",
+ "source_format": "json",
+ "events": [
+ {
+ "severity": "high",
+ "title": ALERT_TITLE,
+ "description": ("winword.exe spawned powershell.exe with an encoded command line on WIN-FIN-01"),
+ "host": "WIN-FIN-01",
+ "user": "j.doe",
+ "process_name": "powershell.exe",
+ "parent_process": "winword.exe",
+ "command_line": "powershell.exe -nop -w hidden -enc JABzAD0A",
+ "event_type": "process_create",
+ "technique": "T1059.001",
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ }
+ ],
+ }
+
+
+def main() -> int:
+ print(f"\nGolden pipeline — run {RUN_ID}")
+ print(f" ingest: {INGEST_URL}")
+ print(f" api: {API_URL}\n")
+ r = Report()
+
+ # ── 1. The two entry points are reachable ────────────────────────────
+ status, body = _request("GET", f"{INGEST_URL}/health")
+ if not r.record("ingest service is reachable", status == 200, f"HTTP {status}" if status != 200 else body[:60]):
+ return _finish(r)
+
+ status, body = _request("GET", f"{API_URL}/health")
+ if not r.record("api service is reachable", status == 200, f"HTTP {status}" if status != 200 else ""):
+ return _finish(r)
+
+ # ── 2. Raw telemetry is accepted ─────────────────────────────────────
+ status, body = _request("POST", f"{INGEST_URL}/v1/ingest/batch", golden_event(), timeout=30)
+ accepted = 0
+ if status == 200:
+ try:
+ accepted = int(json.loads(body).get("accepted", 0))
+ except (ValueError, TypeError):
+ accepted = 0
+ if not r.record(
+ "raw telemetry accepted by ingest",
+ status == 200 and accepted == 1,
+ f"HTTP {status} {body[:140]}",
+ ):
+ # The single most common cause, worth naming rather than making the
+ # reader search: the broker refuses the first publish when the topic
+ # does not exist and cannot be auto-created.
+ print("\n Hint: if this says 'failed to publish events', check Kafka:")
+ print(" docker compose logs kafka | tail -40")
+ print(" docker compose exec kafka kafka-topics --bootstrap-server localhost:29092 --list")
+ return _finish(r)
+
+ # ── 3..6. The event traverses Kafka -> fusion -> detection -> Postgres,
+ # observed through the public API rather than by reaching inside. ─────
+ print(f"\n waiting up to {TIMEOUT_SECONDS}s for the alert to surface…", flush=True)
+ deadline = time.time() + TIMEOUT_SECONDS
+ alert: dict | None = None
+ last_status = 0
+ while time.time() < deadline:
+ last_status, body = _request("GET", f"{API_URL}/api/v1/alerts?limit=50")
+ if last_status == 200:
+ try:
+ items = json.loads(body).get("items", [])
+ except (ValueError, TypeError):
+ items = []
+ for item in items:
+ if RUN_ID in str(item.get("title", "")):
+ alert = item
+ break
+ if alert:
+ break
+ time.sleep(3)
+
+ if not r.record(
+ "event traversed the spine and became an alert",
+ alert is not None,
+ "" if alert else (f"no alert carrying run id {RUN_ID} after {TIMEOUT_SECONDS}s (last API status {last_status})"),
+ ):
+ print("\n The event was accepted but never became an alert. Check, in order:")
+ print(" docker compose logs fusion | tail -60 # consumer + promotion")
+ print(" docker compose exec kafka kafka-topics --bootstrap-server localhost:29092 --list")
+ print(" docker compose exec postgres psql -U aisoc -d aisoc -c 'select count(*) from alerts;'")
+ return _finish(r)
+
+ assert alert is not None # for type checkers; guarded above
+
+ # ── 7. The alert is retrievable individually, not just in a list ─────
+ alert_id = alert.get("id")
+ status, body = _request("GET", f"{API_URL}/api/v1/alerts/{alert_id}")
+ r.record("alert is retrievable by id from the API", status == 200, f"HTTP {status}" if status != 200 else str(alert_id))
+
+ # ── 8. Provenance survived the journey ───────────────────────────────
+ # These assertions exist because each one has been wrong in a shipped
+ # release: severity collapsed, the vendor label doubled, and the
+ # description arrived as a serialized payload.
+ r.record(
+ "severity survived normalization",
+ alert.get("severity") in {"high", "critical"},
+ f"severity={alert.get('severity')!r}",
+ )
+
+ connector_type = str(alert.get("connector_type") or "")
+ words = connector_type.lower().split()
+ r.record(
+ "source attribution is not duplicated",
+ bool(connector_type) and len(words) == len(set(words)),
+ f"connector_type={connector_type!r}",
+ )
+
+ description = str(alert.get("description") or "")
+ r.record(
+ "description is prose, not a serialized payload",
+ not description.strip().startswith(("{", "[")),
+ f"description={description[:70]!r}",
+ )
+
+ return _finish(r)
+
+
+def _finish(r: Report) -> int:
+ passed = sum(1 for _, ok, _ in r.stages if ok)
+ total = len(r.stages)
+ print(f"\n{'PASS' if r.ok else 'FAIL'}: {passed}/{total} stages\n")
+ return 0 if r.ok else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())