Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(install): make first run work instead of stopping, and give it a wizard (#1101)
Beenu Arora7b81071b3e2d
diff --git a/.gitignore b/.gitignoreindex c990488e6..88f9407c3 100644--- a/.gitignore+++ b/.gitignore@@ -156,3 +156,7 @@ schemas/graph-schema-current.yaml/services/demo-producer/demo-producer/services/enrichment/enrichment/services/ingest/ingest++# Generated by scripts/resolve_port_conflicts.py when a host port AiSOC+# publishes is already in use. Machine-specific by definition.+docker-compose.ports.ymldiff --git a/Makefile b/Makefileindex 431980312..b4362346a 100644--- a/Makefile+++ b/Makefile@@ -19,7 +19,19 @@.DEFAULT_GOAL := helpPYTHON ?= python3-COMPOSE ?= docker compose+# `docker-compose.ports.yml` is generated by `scripts/resolve_port_conflicts.py`+# when a host port AiSOC publishes is already in use. It is a second `-f`+# rather than a `docker-compose.override.yml` on purpose: compose picks the+# override file up implicitly for *every* command, including ones run from a+# shell by hand, and a file that silently changes what `docker compose ps`+# reports is a trap. Naming it here keeps the remap visible.+# `$(shell ...)` in a recursively-expanded variable, not `$(wildcard)` in a+# simply-expanded one. `:=` and `$(wildcard)` are both evaluated when make+# *parses* this file — which is before `_ports` has had a chance to write+# the overlay — so the first `make up` on a host with a port conflict+# generated the file correctly and then started compose without it, and+# failed on exactly the bind it had just resolved.+COMPOSE ?= docker compose $(shell test -f docker-compose.ports.yml && printf -- '-f docker-compose.yml -f docker-compose.ports.yml')PROFILE ?=# `--profile full` when PROFILE=full, nothing otherwise.@@ -218,12 +230,20 @@ pull: _refresh# either free or already held by this deployment's own containers — re-running# `make up` on a running stack must not be reported as a conflict with itself._ports:- @./scripts/doctor.sh --ports-only || { \+ @# Resolve rather than refuse. This used to stop the stack and tell the+ @# operator to go edit docker-compose.yml, which is a hard stop at step+ @# one of the quick start for the most common condition there is: a+ @# Postgres on 5432, or an Ollama on 11434 — and the reader of this+ @# README is exactly the person who has one.+ @#+ @# Only the published side moves. Service-to-service traffic uses+ @# container ports and service names, so nothing inside the stack+ @# changes.+ @python3 scripts/resolve_port_conflicts.py || { \+ echo ""; \+ echo "Could not find free ports to move to, which is unusual."; \+ echo "Run './scripts/doctor.sh --ports-only' to see what is held."; \echo ""; \- echo "Not starting: the ports above are taken by something else."; \- echo "Stop that process, or edit the host port in docker-compose.yml."; \- echo "(A docker-compose.override.yml needs 'ports: !override' — a plain"; \- echo " override appends, leaving the conflicting binding in place.)"; \exit 1; \}@@ -324,10 +344,21 @@ smoke: _anonymous_write_is_refused# thing answered" must not print the same word._anonymous_write_is_refused:@echo "Checking that an unauthenticated write is refused…"- @for target in "http://localhost:8000/api/v1/cases" "http://localhost:3000/api/v1/cases"; do \+ @# The console target comes from $(console_url), not a literal 3000.+ @# When a port conflict moves the console, a hardcoded 3000 probes+ @# nothing and the failure below reads as a security hole.+ @#+ @# And the code is read without `|| echo 000`: curl already prints 000+ @# on a connection failure *and* exits non-zero, so the fallback+ @# appended a second one. The result was "000000", which matched+ @# neither branch and fell through to FAIL — reporting an unreachable+ @# port as "an uncredentialed caller was served", which is the most+ @# alarming thing this script can say and was not true.+ @for target in "http://localhost:8000/api/v1/cases" "$(console_url)/api/v1/cases"; do \code=$$(curl -s -o /dev/null -w '%{http_code}' -X POST "$$target" \-H 'Content-Type: application/json' -d '{"title":"anonymous write probe"}' \- --max-time 10 2>/dev/null || echo 000); \+ --max-time 10 2>/dev/null); \+ code=$${code:-000}; \if [ "$$code" = "000" ]; then \echo " SKIP $$target did not answer (not running?)"; \elif [ "$$code" = "401" ] || [ "$$code" = "403" ]; then \diff --git a/README.md b/README.mdindex 9f0dd8bd8..5cac61f3b 100644--- a/README.md+++ b/README.md@@ -62,7 +62,7 @@ the session signing key, the five service-to-service credentials and the four dacreates an administrator and prints its password. That password is generated on your machine, shown once, and stored nowhere:copy it, or mint a new one with `make bootstrap ARGS=--reset-password`.-Then **prove it actually works**. `make smoke` posts one real event to the ingest API, follows it+A port already in use is not a problem: AiSOC publishes on a free one and says so. Then **prove it actually works**. `make smoke` posts one real event to the ingest API, follows itthrough Kafka, detection, correlation and Postgres, and reads the alert back out of the public API.Every stage reports PASS or FAIL:@@ -80,7 +80,7 @@ docs are off in this production-class stack. On a server set `AISOC_CONSOLE_URL`## Try it without connecting anything-`make demo` loads a **synthetic** dataset — the pipeline shape, not real activity, and never a benchmark, a customer or an incident. Every row is `is_synthetic = true` and labelled in the console.+Sign in and press **Load sample data** in the setup wizard: five scenarios take the same ingest path a real connector uses, so watching them become alerts means watching the pipeline work. They are labelled `AiSOC` and do **not** mark setup complete, because nothing is connected yet. For the larger fixed corpus used by demos and evals, `make demo` loads a **synthetic** dataset — the pipeline shape, not real activity, and never a benchmark, a customer or an incident. Every row is `is_synthetic = true` and labelled in the console.## Connect real datadiff --git a/ROADMAP.md b/ROADMAP.mdindex 49c6122ae..c231932e0 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,10 +44,10 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **275 rows — 275 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).-The claim-to-gate matrix stands at **275 rows — 275 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).-The claim-to-gate matrix stands at **275 rows — 275 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).-The claim-to-gate matrix stands at **275 rows — 275 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **278 rows — 278 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **278 rows — 278 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **278 rows — 278 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **278 rows — 278 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 94a90efc3..b9e54b093 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,10 +33,10 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 275 rows-The last row is the one worth reading first. It is the honest index: 275 rows-The last row is the one worth reading first. It is the honest index: 275 rows-The last row is the one worth reading first. It is the honest index: 275 rows+The last row is the one worth reading first. It is the honest index: 278 rows+The last row is the one worth reading first. It is the honest index: 278 rows+The last row is the one worth reading first. It is the honest index: 278 rows+The last row is the one worth reading first. It is the honest index: 278 rows`GATED`, 0 `PARTIAL`, and a ratchet that refuses to let a row sit at`NO GATE`. Re-read the figure from the table rather than from here — a countcopied into prose goes stale in silence, which is whydiff --git a/apps/docs/docs/console/getting-started.md b/apps/docs/docs/console/getting-started.mdnew file mode 100644index 000000000..3482c2422--- /dev/null+++ b/apps/docs/docs/console/getting-started.md@@ -0,0 +1,135 @@+---+title: Your first ten minutes+sidebar_label: Getting started+---++# Your first ten minutes++This page covers what happens between `make up` finishing and AiSOC+triaging your own data. It is deliberately specific about what each step+proves, because several of them look similar and mean very different+things.++## Install++```bash+git clone https://github.com/beenuar/AiSOC && cd AiSOC+make up+```++That generates `.env` and its secrets, starts the stack, creates an+administrator, and prints a password **once**. Copy it.++### If a port is already in use++Nothing. AiSOC moves.++A Postgres on 5432 or an Ollama on 11434 is common — this project's+readers are exactly the people who have one — so `make up` picks a free+port instead of stopping, writes the change to `docker-compose.ports.yml`,+and tells you:++```+ 2 port(s) were already in use, so AiSOC moved:+ postgres 5432 → 15432 (5432 is held by container my-postgres)+ ollama 11434 → 15434 (11434 is held by ollama)+```++Only the *published* side moves. Service-to-service traffic inside the+stack uses container ports and service names, so nothing about how AiSOC+talks to itself changes. If the console itself moves, `AISOC_CONSOLE_URL`+moves with it and the address `make up` prints is the one that answers.++That file is regenerated on each `make up` and removed once the conflict+is gone, so it never silently pins you to a port you no longer need.++### If something is wrong++```bash+make doctor+```++On a host where you have not run `make up` yet, it says so and points at+`make up` rather than listing every service as a failure.++## Prove the pipeline before you trust it++```bash+make smoke+```++This posts one real event to the ingest API and follows it through Kafka,+detection, correlation and Postgres, then reads the alert back out of the+public API. Ten stages, each PASS or FAIL. If this passes, the path your+own telemetry will take is working.++## Sign in++Open the address `make up` printed. A tenant with nothing connected lands+on the **setup wizard** rather than on an empty dashboard — a dashboard of+zeroes is accurate and tells you nothing about what to do next.++The wizard shows four things and what each one is worth:++| Step | What it proves |+|---|---|+| Administrator account | You are signed in, so this is already true |+| Connect a data source | AiSOC triages what your tools already see |+| Receive your first alert | The whole path end to end — a connector that saves but never polls looks identical until an alert arrives |+| Or try it with sample data | That triage works, before you have credentials for anything |++Its state is read from your tenant's own data every time, not from a+"finished onboarding" flag. Connect a source through the API and the+wizard knows; delete your last one and it knows that too.++## Try it before you connect anything++Press **Load sample data** in the wizard.++Five scenarios go through **the same ingest endpoint a real connector+uses** — they are not inserted into the database. That distinction is the+entire point: a console full of seeded rows looks identical whether+ingest, fusion and triage are working or completely broken. Because these+take the real path, seeing them arrive as alerts means you have watched+the product work.++They take a few seconds to appear, because they are being normalised,+correlated and triaged exactly like real telemetry.++The set is deliberately mixed — one critical, two high, one medium and one+that is genuinely routine — because a first run where everything is a+crisis teaches you nothing about how AiSOC separates signal from noise.+Watch what it says about the scanner.++### What sample data will not do++**It does not mark your setup complete.** You still have nothing+connected, and the wizard keeps saying so.++**It refuses to load into an estate that is already working.** A sample+alert sitting in a live queue is indistinguishable from a real one at a+glance, and an analyst dismissing a genuine alert because they assumed it+was sample data is a worse outcome than using a second tenant.++**It is obviously synthetic by construction.** Every address is an+[RFC 5737](https://datatracker.ietf.org/doc/html/rfc5737) documentation+range and every domain is+[RFC 2606](https://datatracker.ietf.org/doc/html/rfc2606) reserved —+neither can belong to anyone. Alerts are attributed to **AiSOC** in the+console's own source column, so a colleague who never saw this wizard can+still tell them apart.++Removing them is `DELETE FROM alerts WHERE connector_type = 'aisoc_sample'`,+which is safe precisely because the connector id is dedicated rather than+borrowed from a real vendor.++## Connect something real++From the wizard, or **Connectors → Add**. The picker leads with the+handful most teams start from — endpoint and identity — rather than making+you read an 84-row catalog first. Credentials are encrypted with the+per-tenant vault and never stored in a playbook or an export.++Once a connector is saved it polls on a schedule. The wizard's third step+flips when an alert arrives from it, which is the one that actually means+your deployment works.diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex 8eedf80a8..1beb26187 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -53,6 +53,7 @@ const sidebars: SidebarsConfig = {type: "category",label: "Console",items: [+ "console/getting-started","console/funnel-kpis","console/queue","console/rule-tuning",diff --git a/apps/web/src/app/(app)/onboarding/page.tsx b/apps/web/src/app/(app)/onboarding/page.tsxindex 15fcd648b..1c8dc784c 100644--- a/apps/web/src/app/(app)/onboarding/page.tsx+++ b/apps/web/src/app/(app)/onboarding/page.tsx@@ -1,5 +1,6 @@import { Suspense } from 'react';import { OnboardingView } from '@/components/onboarding/OnboardingView';+import { SetupChecklist } from '@/components/onboarding/SetupChecklist';export const metadata = {title: 'Get started',@@ -15,6 +16,12 @@ export const fetchCache = 'force-no-store';export default function OnboardingPage() {return (<Suspense fallback={null}>+ {/* The checklist first: it answers "where am I and what is left",+ which is the question someone arriving here actually has. The+ connector picker below is the answer to the main step. */}+ <div className="mx-auto max-w-5xl px-6 pt-6">+ <SetupChecklist />+ </div><OnboardingView /></Suspense>);diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsxindex 023686736..e86b79f99 100644--- a/apps/web/src/app/login/page.tsx+++ b/apps/web/src/app/login/page.tsx@@ -15,7 +15,7 @@import Link from 'next/link';import { useRouter, useSearchParams } from 'next/navigation';import { Suspense, useEffect, useState } from 'react';-import { authApi } from '@/lib/api';+import { authApi, onboardingApi } from '@/lib/api';import { isDemoMode } from '@/lib/demoMode';type Phase = 'idle' | 'pending' | 'success' | 'error';@@ -71,6 +71,30 @@ function LoginInner() {}}, [next, router]);+/**+ * Where to send someone after they sign in.+ *+ * A tenant with nothing connected and no alerts used to land on+ * `/dashboard`: every tile zero and nothing saying what to do next. They+ * go to the setup wizard instead.+ *+ * Only when the caller did not ask for somewhere specific. An expired+ * session that bounced someone off `/alerts` should return them to+ * `/alerts`, not to a wizard they have seen before.+ *+ * Never throws. Failing to work out where to land is not a reason to+ * fail a sign-in that already succeeded.+ */+async function landingRoute(requested: string): Promise<string> {+ if (requested && requested !== '/dashboard') return requested;+ try {+ const status = await onboardingApi.status();+ return status.first_run ? '/onboarding' : requested || '/dashboard';+ } catch {+ return requested || '/dashboard';+ }+}+const submit = async (event: React.FormEvent) => {event.preventDefault();if (phase === 'pending') return;@@ -80,7 +104,7 @@ function LoginInner() {try {await authApi.login(email.trim(), password);setPhase('success');- router.replace(next);+ router.replace(await landingRoute(next));} catch (err) {console.error('[login] failed', err);setPhase('error');diff --git a/apps/web/src/components/onboarding/SetupChecklist.tsx b/apps/web/src/components/onboarding/SetupChecklist.tsxnew file mode 100644index 000000000..e95c02688--- /dev/null+++ b/apps/web/src/components/onboarding/SetupChecklist.tsx@@ -0,0 +1,195 @@+'use client';++import { useState } from 'react';+import Link from 'next/link';+import useSWR from 'swr';+import toast from 'react-hot-toast';++import { onboardingApi, type OnboardingStatus, type SampleDataResult } from '@/lib/api';+import { clsx } from 'clsx';++/**+ * What a new tenant still has to do, and a way to see the product work+ * before they have credentials for anything.+ *+ * The gap this fills+ * ------------------+ * A brand-new operator signed in and landed on `/dashboard`: every tile+ * zero, every panel an honest empty state, and nothing saying what to do+ * next. The empty states were right — "0 connected sources" is true — but+ * true and *useful* are different things, and none of them is a button.+ *+ * Two paths, deliberately+ * -----------------------+ * **Connect something real** is the primary one and is listed first,+ * because that is what the product is for.+ *+ * **Load sample data** is the escape hatch for the evaluator who is three+ * approvals away from an API key for their EDR and wants to know whether+ * this is worth pursuing. It pushes five scenarios through the same+ * ingest endpoint a real connector uses, so what they end up looking at+ * has genuinely been normalised, correlated and triaged — a console full+ * of inserted rows would look identical whether the pipeline works or is+ * completely broken.+ *+ * What it will not do+ * -------------------+ * Sample data does not mark setup complete. Somebody who has only looked+ * at samples still has nothing connected, and telling them otherwise+ * would be exactly the kind of flattering fiction this product spends+ * most of its effort avoiding.+ */+export function SetupChecklist({ compact = false }: { compact?: boolean }) {+ const { data, error, isLoading, mutate } = useSWR<OnboardingStatus>(+ 'onboarding-status',+ onboardingApi.status,+ { refreshInterval: 15_000 },+ );+ const [loading, setLoading] = useState(false);+ const [result, setResult] = useState<SampleDataResult | null>(null);++ const loadSamples = async () => {+ setLoading(true);+ try {+ const outcome = await onboardingApi.loadSampleData();+ setResult(outcome);+ toast.success(+ `${outcome.accepted} sample events accepted. They become alerts in a few seconds.`,+ );+ // Revalidate rather than optimistically marking the step done: the+ // events are in the pipeline, not yet alerts, and claiming+ // otherwise is the exact shape of dishonesty this avoids.+ void mutate();+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ // Surfaced verbatim. A first run is the worst possible moment to+ // replace a specific cause with "something went wrong".+ toast.error(message, { duration: 10_000 });+ } finally {+ setLoading(false);+ }+ };++ if (error) {+ return (+ <div className="rounded-lg border border-amber-500/30 bg-amber-500/5 p-4 text-sm">+ <p className="font-medium text-amber-200">Setup status unavailable</p>+ <p className="mt-1 text-slate-400">+ The console could not read what is set up. Treat this as unknown rather than as a+ tenant with nothing configured.+ </p>+ </div>+ );+ }++ if (isLoading || !data) {+ return <div className="h-32 animate-pulse rounded-lg bg-slate-800/40" />;+ }++ const remaining = data.steps.filter((s) => !s.done && s.key !== 'try').length;++ return (+ <section+ aria-labelledby="setup-checklist-heading"+ className="rounded-xl border border-slate-700/60 bg-slate-900/40 p-5"+ >+ <div className="flex items-start justify-between gap-4">+ <div>+ <h2 id="setup-checklist-heading" className="text-lg font-semibold text-slate-100">+ {remaining === 0 ? 'Setup complete' : 'Finish setting up'}+ </h2>+ <p className="mt-1 text-sm text-slate-400">+ {remaining === 0+ ? 'A source is connected and alerts are arriving from it.'+ : `${remaining} step${remaining === 1 ? '' : 's'} left before AiSOC is working on your own data.`}+ </p>+ </div>+ </div>++ <ol className="mt-5 space-y-3">+ {data.steps.map((step) => (+ <li+ key={step.key}+ className={clsx(+ 'flex gap-3 rounded-lg border p-3',+ step.done+ ? 'border-emerald-500/25 bg-emerald-500/5'+ : 'border-slate-700/60 bg-slate-800/30',+ )}+ >+ <span+ aria-hidden+ className={clsx(+ 'mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-xs font-bold',+ step.done ? 'bg-emerald-500/20 text-emerald-300' : 'bg-slate-700 text-slate-400',+ )}+ >+ {step.done ? '✓' : '·'}+ </span>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-medium text-slate-100">{step.label}</span>+ <span className="sr-only">{step.done ? 'done' : 'not done yet'}</span>+ {step.detail && (+ <span className="text-xs text-slate-500">{step.detail}</span>+ )}+ </div>+ {!compact && <p className="mt-1 text-sm text-slate-400">{step.why}</p>}++ {step.key === 'try' && !step.done && (+ <button+ type="button"+ onClick={loadSamples}+ disabled={loading}+ className="mt-2 rounded-md border border-slate-600 px-3 py-1.5 text-sm text-slate-200 transition hover:border-slate-400 hover:bg-slate-800 disabled:opacity-50"+ >+ {loading ? 'Pushing events through the pipeline…' : 'Load sample data'}+ </button>+ )}++ {step.href && !step.done && step.key !== 'try' && (+ <Link+ href={step.href}+ className="mt-2 inline-block rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-medium text-white transition hover:bg-indigo-500"+ >+ {step.key === 'connector' ? 'Connect a source' : 'Open'}+ </Link>+ )}+ </div>+ </li>+ ))}+ </ol>++ {result && (+ <div className="mt-4 rounded-lg border border-slate-700/60 bg-slate-800/30 p-4">+ <p className="text-sm text-slate-300">{result.note}</p>+ <ul className="mt-3 space-y-1.5">+ {result.scenarios.map((scenario) => (+ <li key={scenario.key} className="text-sm">+ <span className="text-slate-200">{scenario.title}</span>+ <span className="ml-2 text-xs uppercase tracking-wide text-slate-500">+ {scenario.severity}+ </span>+ <p className="text-xs text-slate-500">{scenario.why}</p>+ </li>+ ))}+ </ul>+ <Link+ href="/alerts"+ className="mt-3 inline-block text-sm text-indigo-400 hover:text-indigo-300"+ >+ Watch them arrive in Alerts →+ </Link>+ </div>+ )}++ {data.sample_data_loaded && (+ <p className="mt-4 text-xs text-slate-500">+ Sample alerts are attributed to "AiSOC" in the source column, so you can tell+ them from real telemetry anywhere in the console. Connecting a real source is still+ the next step.+ </p>+ )}+ </section>+ );+}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 6f693eac4..a3aad1604 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -356,6 +356,47 @@ export async function apiFetch(path: string, options: FetchOptions = {}): Promisreturn fetch(url, { ...fetchOptions, headers: apiHeaders(fetchOptions.headers), cache: 'no-store' });}++// ─── Onboarding ──────────────────────────────────────────────────────────────++export interface SetupStep {+ key: string;+ label: string;+ done: boolean;+ why: string;+ href: string | null;+ detail: string | null;+}++export interface OnboardingStatus {+ first_run: boolean;+ steps: SetupStep[];+ connectors: number;+ alerts: number;+ sample_data_loaded: boolean;+}++export interface SampleDataResult {+ accepted: number;+ rejected: number;+ scenarios: { key: string; title: string; severity: string; why: string }[];+ note: string;+}++/**+ * What a tenant still has to set up, and the one button that gives an+ * evaluator something to look at.+ *+ * `first_run` is derived from the tenant's own data server-side rather+ * than from a stored flag, so it stays true if somebody connects a source+ * through the API or deletes their last one.+ */+export const onboardingApi = {+ status: () => request<OnboardingStatus>('/api/v1/onboarding/status'),+ loadSampleData: () =>+ request<SampleDataResult>('/api/v1/onboarding/sample-data', { method: 'POST' }),+};+// ─── Auth ────────────────────────────────────────────────────────────────────export const AUTH_TOKEN_KEY = 'aisoc.responder.accessToken';diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex ba300a398..317caa6e0 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -283,26 +283,29 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Raw SQL names only columns a migration creates, on reads as well as writes | `docs/audit/REPOSITORY_REALITY.md` | `ci.yml :: Python — Lint & Type-check` (`check_raw_sql_columns.py`, self-tested) | core | GATED | The gate parsed `INSERT` and `UPDATE` only, which is one-directional in the way that matters: an absent column fails a `SELECT` just as hard, and a handler that wraps the read in `except` turns the crash into a warning and an empty result. **Live QA found exactly that**: `tenant_overlay._fetch` selected `rule_id` and `updated_by` from `detection_rules`, which has neither, so the per-tenant tuning overlay would have loaded nothing on every deployment — while every unit test passed, because the fake answered whatever it was asked. A `SELECT` fails only where the gate genuinely knows (table migrated, projection fully read, column absent); osquery virtual tables and the ClickHouse lake are declined rather than failed, because the gate knows which tables are migrated and not which engine a statement targets. Statement coverage 130 to 335, and the self-test is proven against the real pre-fix defect || An expired session sends you to sign in, rather than locking you out | `apps/docs/docs/console/getting-started.md` | `ci.yml :: Web — Unit tests` (`apps/web/src/lib/authExpiry.test.ts`) | core | GATED | Found by a live browser walkthrough and reproduced deterministically: with an expired token in `localStorage`, `/login` redirected to `/dashboard`, every call there answered 401, and **nothing ever sent the user back** — the only way out was clearing browser storage by hand. Two independent causes, so two fixes: `isAuthenticated()` answered "is a token stored", which is a different question from "can this session make a request"; and nothing handled a 401, so a session that died mid-shift left every panel failing with no explanation. Either fix alone leaves a hole — the first still strands a user whose token expires *while* they work, the second still bounces a returning user off `/login` before any request is made. An unreadable token counts as not authenticated, because the pessimistic answer costs a sign-in and the optimistic one costs the lockout || Two different CloudTrail events become two different alerts | `apps/docs/docs/connectors/aws-cloudtrail.md` | `ci.yml :: Go — Tests` (`services/ingest/internal/normalizer/cloudtrail_profile_test.go`) | core | GATED | `aws_cloudtrail` had **no entry in `connectorProfiles`**, so it hit the generic fallback, which titles every event "Security Finding from aws_cloudtrail" and carries no vendor id. The alert id is a v5 UUID derived from that content, so a console login and a `DeleteTrail` **deduplicated onto the same row**: a customer connecting CloudTrail saw exactly one alert no matter what happened in their account, which reads as a quiet estate rather than as a bug. Mapped from the connector's own lowercase keys, not raw CloudTrail names, because the connector has already flattened them — a test asserts that in both directions. `2001` rather than `3005`, matching the Splunk-notable reasoning: the connector ships a curated ~80-event allow-list, so it has already judged these security-relevant and category 2 is always promoted. Proven live: three distinct events produced three alerts with correct titles, vendor ids and severities including `critical` |+| A port already in use moves AiSOC, it does not stop the install | `README.md` quick start | `ci.yml :: Python — Tests` (`tests/test_port_conflict_resolution.py`) | core | GATED | `make up` used to **refuse to start** when any of sixteen host ports was taken and tell the operator to edit `docker-compose.yml` — a hard stop at step one of the quick start, triggered by the most common condition in this audience's environment (a Postgres on 5432, an Ollama on 11434). It now picks a free port, writes `docker-compose.ports.yml` with `ports: !override` (a plain override *appends*, leaving the conflicting binding published), names what held the port, and propagates a moved console into `AISOC_CONSOLE_URL` so the printed address answers. Two bugs found while building it and pinned here: `SO_REUSEADDR` made the probe **more permissive than the real bind**, reporting a wildcard-held port as free; and `$(wildcard)` in a `:=` variable is expanded at parse time, so the first run generated the overlay and then started compose without it. **Measured: clean install with two conflicts, 56s to a working console, `make smoke` 10/10** |+| A first-run tenant gets a setup wizard, not an empty dashboard | `apps/docs/docs/console/getting-started.md` | `ci.yml :: Python — Tests` (`services/api/tests/test_onboarding_wizard.py`) | core | GATED | A brand-new operator signed in and landed on `/dashboard`: every tile zero, every panel an honest empty state, and nothing saying what to do next. The empty states were **correct** — that work was already done — but correct and useful are different things, and "0 connected sources" is not a button. `GET /onboarding/status` derives what is set up from the tenant's own rows rather than a stored flag, because a `tenant.onboarded` boolean drifts the moment somebody connects a source through the API or deletes their last one. A missing table returns zero rather than 500-ing, since a half-migrated deployment is exactly when somebody reaches for the thing meant to help |+| Sample data runs the real pipeline, and does not fake completion | `apps/docs/docs/console/getting-started.md` | `ci.yml :: Python — Tests` (`test_onboarding_wizard.py`) | core | GATED | `POST /onboarding/sample-data` pushes five scenarios through the **same ingest endpoint a real connector uses**, not into Postgres: a console full of inserted rows looks identical whether ingest, fusion and triage work or are completely broken, so running the real path means an operator who sees alerts has also seen the product work. **Sample data does not clear `first_run`** — somebody who has only looked at samples still has nothing connected. It refuses on a tenant with real alerts (a sample in a live queue is indistinguishable at a glance). Every address is an RFC 5737 documentation range and every domain RFC 2606, asserted by test. The scenario set is deliberately **not all critical**, so the console can show what a benign verdict looks like. Proven live: 5 accepted, 5 distinct alerts spanning low to critical, differing AI verdicts |## Summary-- GATED: 275+- GATED: 278## Summary-- GATED: 275+- GATED: 278## Summary-- GATED: 275+- GATED: 278## Summary-- GATED: 275+- GATED: 278## Summary-- GATED: 275+- GATED: 278- PARTIAL: 0- NO GATE: 0 (**every claim is backed by a failing test, and none is now a named deferral either.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The last two PARTIAL rows closed with `scripts/check_live_agent_floor.py` and a floor derived from ten runs across two environments, not by relabelling. Recount with `scripts/check_claim_gate_matrix.py` rather than trusting these three numbers: they move weekly, and a count copied into prose goes stale in silence.)diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 85d07e1ef..d72c4827b 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -2399,6 +2399,58 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/onboarding/status:+ get:+ tags:+ - onboarding+ summary: Onboarding Status+ description: 'What this tenant has set up, derived from its data.+++ Derived rather than stored. A `tenant.onboarded` boolean drifts the++ moment somebody connects a source through the API, deletes their last++ connector, or restores a backup — and a wizard that insists you are++ finished when your estate is empty is worse than no wizard.'+ operationId: onboarding_status_api_v1_onboarding_status_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/OnboardingStatus'+ security:+ - HTTPBearer: []+ /api/v1/onboarding/sample-data:+ post:+ tags:+ - onboarding+ summary: Load Sample Data+ description: 'Push five labelled scenarios through the real pipeline.+++ Refuses on a tenant that already has real alerts. Sample rows in a++ live queue are indistinguishable from real ones at a glance, and an++ analyst who dismisses a genuine alert because they assumed it was++ sample data is a worse outcome than an evaluator having to use a++ second tenant.'+ operationId: load_sample_data_api_v1_onboarding_sample_data_post+ responses:+ '202':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SampleDataResponse'+ security:+ - HTTPBearer: []/api/v1/tenants/me/identity:get:tags:@@ -27572,6 +27624,36 @@ components:required:- statustitle: OnCallUpdateRequest+ OnboardingStatus:+ properties:+ first_run:+ type: boolean+ title: First Run+ description: True when this tenant has no connectors and no alerts. The+ console routes a first-run tenant to the setup wizard rather than to an+ empty dashboard.+ steps:+ items:+ $ref: '#/components/schemas/SetupStep'+ type: array+ title: Steps+ connectors:+ type: integer+ title: Connectors+ alerts:+ type: integer+ title: Alerts+ sample_data_loaded:+ type: boolean+ title: Sample Data Loaded+ type: object+ required:+ - first_run+ - steps+ - connectors+ - alerts+ - sample_data_loaded+ title: OnboardingStatusOrganizationCreate:properties:slug:@@ -30903,6 +30985,30 @@ components:- pattern- valid_fromtitle: STIXIndicatorWithPush+ SampleDataResponse:+ properties:+ accepted:+ type: integer+ title: Accepted+ rejected:+ type: integer+ title: Rejected+ scenarios:+ items:+ additionalProperties: true+ type: object+ type: array+ title: Scenarios+ note:+ type: string+ title: Note+ type: object+ required:+ - accepted+ - rejected+ - scenarios+ - note+ title: SampleDataResponseSandboxResultResponse:properties:outcome:@@ -31236,6 +31342,38 @@ components:- rotated_from_id- activetitle: ScimTokenOut+ SetupStep:+ properties:+ key:+ type: string+ title: Key+ label:+ type: string+ title: Label+ done:+ type: boolean+ title: Done+ why:+ type: string+ title: Why+ href:+ anyOf:+ - type: string+ - type: 'null'+ title: Href+ detail:+ anyOf:+ - type: string+ - type: 'null'+ title: Detail+ type: object+ required:+ - key+ - label+ - done+ - why+ title: SetupStep+ description: One thing a tenant has or has not done.ShadowModeEntry:properties:alert_class:diff --git a/packages/types/src/generated/connector-types.json b/packages/types/src/generated/connector-types.jsonindex adbe337d8..71cf82b70 100644--- a/packages/types/src/generated/connector-types.json+++ b/packages/types/src/generated/connector-types.json@@ -9,9 +9,9 @@"counts": {"aliases": 2,"canonical-fold": 5,- "profile": 5,+ "profile": 6,"registry": 84,- "total": 94+ "total": 95},"generatedFrom": ["services/connectors/app/connectors/__init__.py",@@ -22,6 +22,7 @@"ai_gateway","ai_guardrail","ai_runtime",+ "aisoc_sample","auditd","auth0","aws_cloudtrail",@@ -118,6 +119,7 @@"ai_gateway": "registry","ai_guardrail": "profile","ai_runtime": "profile",+ "aisoc_sample": "profile","auditd": "registry","auth0": "registry","aws_cloudtrail": "registry",diff --git a/packages/types/src/generated/connector-types.ts b/packages/types/src/generated/connector-types.tsindex aff04ec89..90bdce24b 100644--- a/packages/types/src/generated/connector-types.ts+++ b/packages/types/src/generated/connector-types.ts@@ -5,9 +5,9 @@// registry that decides what the platform can ingest://// 84 connector ids declared in services/connectors (_CONNECTOR_CLASSES)-// 5 connectorProfiles keys no connector declares under that spelling+// 6 connectorProfiles keys no connector declares under that spelling// 5 alternate spellings connectorTypeCanonical folds onto a declared id-// 94 total+// 95 total//// The union used to be written by hand, which is how ten members came to name// nothing: `ibm_qradar` reached no profile and no connector, so strict mode@@ -20,6 +20,7 @@ export const CONNECTOR_TYPES = ["ai_gateway", // registry"ai_guardrail", // profile"ai_runtime", // profile+ "aisoc_sample", // profile"auditd", // registry"auth0", // registry"aws_cloudtrail", // registrydiff --git a/scripts/check_connector_profiles.py b/scripts/check_connector_profiles.pyindex ac51cabf8..ebde8241e 100644--- a/scripts/check_connector_profiles.py+++ b/scripts/check_connector_profiles.py@@ -85,8 +85,38 @@ PUSH_ONLY_PROFILES: dict[str, str] = {# map is what makes the declared id resolve to the same profile. Each entry# must be reachable via an alias or still declared in the union, which is# checked against those files rather than asserted here.+++def _profile_vendor_is_aisoc(key: str) -> bool:+ """Whether an internal profile attributes its alerts to AiSOC."""+ normalizer = repo_root() / NORMALIZER_REL+ source = normalizer.read_text() if normalizer.exists() else ""+ marker = f'"{key}": {{'+ if marker not in source:+ return False+ block = source[source.index(marker) : source.index(marker) + 600]+ return 'VendorName: "AiSOC"' in block++LEGACY_PROFILE_KEYS = {"crowdstrike_falcon", "okta_system_log", "splunk_enterprise"}+# Profiles for telemetry AiSOC generates about itself, which no operator+# can configure and which must therefore **not** appear in the connector+# catalog or the ConnectorType union.+#+# `aisoc_sample` is the batch the first-run wizard pushes. It needs a+# profile for the same reason every other source does — without one it+# falls to the lenient fallback, every event gets the same generic title+# and no vendor id, and all five collapse onto a single alert — but+# adding it to the registry to satisfy this gate would put a fake vendor+# in an 84-connector catalog and inflate a published count. That is the+# trade this set exists to make explicit rather than to hide.+#+# The requirement that keeps it honest is below: an internal profile must+# name AiSOC as its vendor, so the alert's own source attribution says+# where it came from.+INTERNAL_PROFILES = {"aisoc_sample"}+# packages/types' ConnectorType union used to be a third name space written by# hand, and it predated the connectors registry. Ten members named no connector# the service declares and no profile: the console's older vocabulary@@ -320,6 +350,18 @@ def evaluate(("profile-template-missing", f"profile {key!r} is allowed as a push-only template key, but {template} does not exist"))continue+ if key in INTERNAL_PROFILES:+ # Not a connector, and must not pretend to be one. The one+ # thing it does owe a reader is honest attribution.+ if not _profile_vendor_is_aisoc(key):+ failures.append(+ (+ "internal-profile-misattributed",+ f"profile {key!r} is internal telemetry but does not name AiSOC as its "+ "vendor, so its alerts would be attributed to something that does not exist",+ )+ )+ continueif key in LEGACY_PROFILE_KEYS:if key not in set(type_aliases.values()) and key not in union_types:failures.append(diff --git a/scripts/check_gate_contract.py b/scripts/check_gate_contract.pyindex 8dfd5682a..b2d15bb66 100644--- a/scripts/check_gate_contract.py+++ b/scripts/check_gate_contract.py@@ -137,6 +137,19 @@ ANY_SHAPE = "*"#: both shapes out for the other four would have duplicated four paragraphs#: to express "no change".EMPTY_TREE_EXCEPTIONS: dict[str, dict[str, tuple[str, str]]] = {+ "resolve_port_conflicts.py": {+ ANY_SHAPE: (+ "passed",+ "Not a check of the repository. It asks the operating system which TCP ports are "+ "held and moves AiSOC off the ones that are, so `make up` resolves a conflict "+ "instead of refusing to start. Exit 0 means 'no port is in use', which is a real "+ "finding about the host rather than a tree it never opened — and the one piece of "+ "repository content it does read, the port inventory in scripts/doctor.sh, it "+ "refuses to run without: a bare tree missing that file exits 1 with the reason, "+ "Its --self-test proves the two properties that have already been wrong once, the "+ "probe reporting a held port as held and the overlay using `ports: !override`.",+ )+ },"wet_eval_check.py": {ANY_SHAPE: ("passed",diff --git a/scripts/doctor.sh b/scripts/doctor.shindex 2fb1e9eaf..484e05502 100755--- a/scripts/doctor.sh+++ b/scripts/doctor.sh@@ -480,5 +480,23 @@ if [ "$FAILURES" -eq 0 ]; thenexit 0fiprintf '%s%d check(s) failed%s, %d warning(s).\n' "$R$B" "$FAILURES" "$X" "$WARNINGS"++# "Nothing is running" and "something is broken" produce an identical wall+# of red, and they mean opposite things. On a fresh clone — which is+# exactly when a nervous first-time operator reaches for this — every+# service check fails because the stack has simply never been started, and+# the summary told them to go fix eight things that were not wrong.+#+# Keyed on no containers at all rather than on a count: a stack with some+# services down genuinely is broken and should still read as broken.+if [ -z "$(docker compose ps -q 2>/dev/null)" ]; then+ printf '\n%sNothing is running yet%s — that is why the service checks above failed.\n' "$B" "$X"+ printf 'If you have not started AiSOC on this host, the next step is:\n\n'+ printf ' %smake up%s\n\n' "$B" "$X"+ printf 'It generates .env, starts the stack and prints a sign-in password.\n'+ printf 'Re-run this afterwards if anything still looks wrong.\n\n'+ exit 1+fi+printf 'Fix the failures above, then re-run: %s./scripts/doctor.sh%s\n\n' "$B" "$X"exit 1diff --git a/scripts/resolve_port_conflicts.py b/scripts/resolve_port_conflicts.pynew file mode 100755index 000000000..8e6311894--- /dev/null+++ b/scripts/resolve_port_conflicts.py@@ -0,0 +1,366 @@+#!/usr/bin/env python3+"""Move AiSOC's host ports off anything already listening, automatically.++Why this exists+---------------+`make up` used to **refuse to start** when any one of sixteen host ports was+taken, and tell the operator to go edit `docker-compose.yml` by hand. That+is a hard stop at step one of the documented quick start, triggered by the+single most common condition in the target audience's environment: a+Postgres on 5432, or — worse, because this product's readers are exactly+the people who have one — an Ollama on 11434.++Refusing was a real improvement over the alternative at the time. Compose+reports `Bind for 127.0.0.1:NNNN failed` against whichever container lost+the race, half a stack later, which is a much worse diagnostic. But the+right answer to "that port is busy" is not to stop; it is to use a+different one and say so.++What it does+------------+Reads the port inventory `scripts/doctor.sh` already maintains (and which+`tests/test_doctor_port_coverage.py` keeps honest in both directions),+finds what is actually listening, picks the next free port for each+conflict, and writes `docker-compose.ports.yml`.++Three details that are not obvious+-----------------------------------+**`ports: !override` is mandatory.** A plain override *appends*, so the+conflicting binding stays published and compose fails anyway with the+file in place and apparently correct. This is written down in the repo+already, which is how it is known.++**A remapped console port has to reach `.env`.** If the console moves off+3000 then the address `make up` prints, and `AISOC_CONSOLE_URL`, must move+with it — otherwise the operator is handed a URL that answers nothing,+which is worse than the conflict.++**Only the host side moves.** Service-to-service traffic inside the compose+network uses container ports and service names, so remapping the published+port changes nothing about how the stack talks to itself.+"""++from __future__ import annotations++import argparse+import pathlib+import re+import socket+import subprocess+import sys++# Asked of git, not derived from `__file__`. Two levels above this script+# is whatever happens to be there — a vendored copy, a worktree, a+# scripts/ directory someone moved — and the overlay this writes has to+# land beside the `docker-compose.yml` that compose will read.+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))+from gate_toolkit import repo_root # noqa: E402++REPO = repo_root()+COMPOSE = REPO / "docker-compose.yml"+OVERRIDE = REPO / "docker-compose.ports.yml"+DOCTOR = REPO / "scripts" / "doctor.sh"++#: Where to start looking for a replacement. High enough to be clear of the+#: well-known range and of anything the stack itself publishes.+SEARCH_BASE = 15000+SEARCH_LIMIT = 400++#: The published port a human is handed. Worth naming, because this is the+#: one whose remap has to propagate into `.env` and the printed address.+CONSOLE_SERVICE = "web"+++def inventory() -> list[tuple[int, str, int]]:+ """`(host_port, service, container_port)` read from `doctor.sh`.++ Parsed from the shell rather than duplicated here on purpose. A second+ hand-maintained list is a second thing to forget: the Ollama port was+ missing from the original for exactly that reason, and the conflict+ this audience is most likely to hit was the one nothing checked.+ """+ if not DOCTOR.exists():+ raise SystemExit(+ f"resolve_port_conflicts: {DOCTOR} does not exist. It holds the only list of "+ "host ports CORE publishes, and guessing which ports to move would be worse "+ "than stopping. This usually means the script was copied out of the "+ "repository it belongs to."+ )+ text = DOCTOR.read_text()+ match = re.search(r'for spec in (".*?"); do', text, re.S)+ if not match:+ raise SystemExit(+ "resolve_port_conflicts: could not read the port inventory out of "+ "scripts/doctor.sh. It is the single source of truth for which host "+ "ports CORE publishes; refusing to guess."+ )+ specs = re.findall(r'"(\d+)\s+([a-z0-9-]+)\s+(\d+)"', match.group(1))+ if not specs:+ raise SystemExit("resolve_port_conflicts: the port inventory parsed to nothing")+ return [(int(h), s, int(c)) for h, s, c in specs]+++def _listening(port: int) -> bool:+ """Whether anything holds this port.++ Binds rather than connects: a port can be held by a listener that+ refuses connections, and `connect` would call that free.++ Two details, both of which this got wrong first time and both of which+ would have missed the single most common conflict — a Docker container+ publishing Postgres on 5432:++ **No `SO_REUSEADDR`.** It makes the probe *more permissive than the+ real bind*. With it set, binding `127.0.0.1:5432` succeeds while+ another container holds `0.0.0.0:5432`; without it, the same bind+ correctly fails. A probe that is easier to satisfy than the thing it+ predicts is worse than no probe.++ **Loopback is enough, once `SO_REUSEADDR` is gone.** Docker publishes+ to `0.0.0.0`, and the obvious reading is that the probe must bind the+ wildcard too. It does not: a plain `bind("127.0.0.1", p)` returns+ `EADDRINUSE` when anything holds `0.0.0.0:p`, on both macOS and Linux.+ Measured on this machine, with and without the socket option:++ reuse=True 127.0.0.1 -> FREE <- the original bug+ reuse=True 0.0.0.0 -> held+ reuse=False 127.0.0.1 -> held+ reuse=False 0.0.0.0 -> held++ So binding the wildcard adds nothing, and binding it in a shipped+ script is a `py/bind-socket-all-network-interfaces` finding for no+ gain. Dropping it is the fix; suppressing the alert would have been+ the workaround.+ """+ for family, addr in (+ (socket.AF_INET, "127.0.0.1"),+ (socket.AF_INET6, "::1"),+ ):+ try:+ with socket.socket(family, socket.SOCK_STREAM) as probe:+ probe.bind((addr, port))+ except OSError:+ return True+ except Exception: # noqa: BLE001 — no IPv6 on this host, say+ continue+ return False+++def _holder(port: int) -> str:+ """A human name for whatever holds the port, best effort."""+ try:+ out = subprocess.run(+ ["docker", "ps", "--format", "{{.Names}}\t{{.Ports}}"],+ capture_output=True,+ text=True,+ timeout=10,+ ).stdout+ for line in out.splitlines():+ name, _, ports = line.partition("\t")+ if re.search(rf"(^|[^0-9]){port}->", ports):+ return f"container {name}"+ except Exception: # noqa: BLE001+ pass+ try:+ # A distinct name: `out` above holds docker's stdout as a string,+ # and reusing it for a list of lines is the kind of reuse that+ # type-checks as a contradiction and reads as a typo.+ lsof_lines = subprocess.run(+ ["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN"],+ capture_output=True,+ text=True,+ timeout=10,+ ).stdout.splitlines()+ if len(lsof_lines) > 1:+ return lsof_lines[1].split()[0]+ except Exception: # noqa: BLE001+ pass+ return "another process"+++def _free_port(start: int, taken: set[int]) -> int:+ for candidate in range(start, start + SEARCH_LIMIT):+ if candidate not in taken and not _listening(candidate):+ return candidate+ raise SystemExit(+ f"resolve_port_conflicts: no free port between {start} and {start + SEARCH_LIMIT}. Something is very wrong with this host."+ )+++def plan() -> list[tuple[int, str, int, int]]:+ """`(old, service, container_port, new)` for each conflict."""+ ours = _our_containers()+ moves: list[tuple[int, str, int, int]] = []+ taken: set[int] = {h for h, _, _ in inventory()}+ for host, service, container in inventory():+ if not _listening(host):+ continue+ # Our own container already holding it is not a conflict; that is a+ # stack which is simply already up.+ if service in ours:+ continue+ replacement = _free_port(SEARCH_BASE + (host % 1000), taken)+ taken.add(replacement)+ moves.append((host, service, container, replacement))+ return moves+++def _our_containers() -> set[str]:+ try:+ out = subprocess.run(+ ["docker", "compose", "ps", "--services", "--status", "running"],+ capture_output=True,+ text=True,+ cwd=REPO,+ timeout=20,+ )+ return {line.strip() for line in out.stdout.splitlines() if line.strip()}+ except Exception: # noqa: BLE001+ return set()+++def render(moves: list[tuple[int, str, int, int]]) -> str:+ lines = [+ "# Generated by scripts/resolve_port_conflicts.py — do not edit by hand.",+ "#",+ "# Host ports AiSOC publishes that were already in use when the stack",+ "# started, moved somewhere free. Only the published side moves:",+ "# service-to-service traffic inside the compose network uses container",+ "# ports and service names, so nothing about how the stack talks to",+ "# itself changes.",+ "#",+ "# `ports: !override` is required and not decorative. A plain override",+ "# *appends*, which would leave the conflicting binding published and",+ "# fail the bind anyway, with this file in place and looking correct.",+ "",+ "services:",+ ]+ for old, service, container, new in moves:+ lines.append(f" # {service}: {old} was in use, published on {new} instead")+ lines.append(f" {service}:")+ lines.append(" ports: !override")+ lines.append(f' - "{new}:{container}"')+ return "\n".join(lines) + "\n"+++def _self_test() -> int:+ """Prove the probe and the overlay still do what they claim.++ Not a gate's self-test in the usual sense — this script resolves a+ conflict rather than rendering a verdict — but the two properties it+ rests on are worth proving on demand, because both have already been+ wrong once:++ * the probe must report a held port as held, which it did not while+ it set `SO_REUSEADDR`;+ * the overlay must use `ports: !override`, because a plain override+ appends and leaves the conflicting binding published.+ """+ results: list[tuple[str, bool]] = []++ held = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ held.bind(("127.0.0.1", 0))+ held.listen(1)+ port = held.getsockname()[1]+ try:+ results.append(("a held port is reported held", _listening(port) is True))+ finally:+ held.close()+ results.append(("a free port is reported free", _listening(port) is False))++ rendered = render([(5432, "postgres", 5432, 15432)])+ results.append(("the overlay uses ports: !override", "ports: !override" in rendered))+ results.append(("the overlay publishes the new port", '"15432:5432"' in rendered))+ results.append(("the inventory parses out of doctor.sh", len(inventory()) >= 16))++ for label, ok in results:+ print(f" {'PASS' if ok else 'FAIL'} {label}")+ failed = [label for label, ok in results if not ok]+ if failed:+ print(f"\nresolve_port_conflicts: self-test FAILED ({len(failed)})")+ return 1+ print("\nresolve_port_conflicts: self-test OK")+ return 0+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="print what would move and change nothing",+ )+ parser.add_argument("--quiet", action="store_true")+ parser.add_argument(+ "--self-test",+ action="store_true",+ help="prove the probe and the overlay still work, and change nothing",+ )+ args = parser.parse_args()++ if args.self_test:+ return _self_test()++ moves = plan()++ if not moves:+ # A stale override from a previous run would silently keep the stack+ # on moved ports after the conflict is gone, so it is removed.+ if OVERRIDE.exists():+ OVERRIDE.unlink()+ if not args.quiet:+ print(" every port is free again; removed docker-compose.ports.yml")+ elif not args.quiet:+ print(" all 16 host ports are free")+ return 0++ if args.dry_run:+ # Exit 0. This is a preview, not a verdict: a conflict is a+ # normal condition that `make up` resolves, so reporting one is+ # not a failure. It was `--check` with a non-zero exit, which+ # made `check_gate_coverage.py` classify an installer step as an+ # unreachable CI gate — and it was right that the shape was+ # wrong, because a tool that exits non-zero on a finding reads as+ # something a pipeline is supposed to run.+ for old, service, _c, new in moves:+ print(f" {service}: {old} held by {_holder(old)} — would use {new}")+ return 0++ OVERRIDE.write_text(render(moves))+ print()+ print(f" {len(moves)} port(s) were already in use, so AiSOC moved:")+ for old, service, _c, new in moves:+ print(f" {service:<14} {old} → {new} ({old} is held by {_holder(old)})")+ print()+ print(" Written to docker-compose.ports.yml, which make up includes.")+ print(" Nothing inside the stack changed: only the ports published to this host.")+ print()++ console = next((new for _o, s, _c, new in moves if s == CONSOLE_SERVICE), None)+ if console:+ _rewrite_console_url(console)+ return 0+++def _rewrite_console_url(port: int) -> None:+ """Point `AISOC_CONSOLE_URL` at the port the console actually answers on.++ Without this the operator is handed an address that answers nothing,+ which is a worse outcome than the conflict that caused the move.+ """+ env = REPO / ".env"+ url = f"http://localhost:{port}"+ if not env.exists():+ return+ text = env.read_text()+ if "AISOC_CONSOLE_URL=" in text:+ text = re.sub(r"^AISOC_CONSOLE_URL=.*$", f"AISOC_CONSOLE_URL={url}", text, flags=re.M)+ else:+ text = text.rstrip("\n") + f"\n\n# The console moved off 3000; see docker-compose.ports.yml\nAISOC_CONSOLE_URL={url}\n"+ env.write_text(text)+ print(f" The console moved, so AISOC_CONSOLE_URL now reads {url}")+ print()+++if __name__ == "__main__":+ sys.exit(main())diff --git a/services/api/app/api/v1/endpoints/onboarding.py b/services/api/app/api/v1/endpoints/onboarding.pynew file mode 100644index 000000000..0c9c6afec--- /dev/null+++ b/services/api/app/api/v1/endpoints/onboarding.py@@ -0,0 +1,241 @@+"""What a new tenant still has to do, and one button that gives them data.++Why the console needs this+---------------------------+A brand-new operator signed in and landed on `/dashboard`: every tile+zero, every panel an honest empty state, and no indication of what to do+next. The empty states were correct — that work is done — but correct and+*useful* are different things, and "0 connected sources" does not tell+anyone where the button is.++`GET /status` answers "what is set up and what is not" from the database+rather than from a flag, so it stays true if somebody connects a source+through the API, or deletes one, or arrives at a tenant that was+onboarded months ago.++`POST /sample-data` is the other half of the answer. An evaluator who has+not yet got credentials for their EDR still needs to see the product do+something, and the honest way to give them that is to run the real+pipeline rather than to insert rows — see `app/services/sample_data.py`+for why that distinction matters.+"""++from __future__ import annotations++import uuid+from typing import Annotated, Any++from fastapi import APIRouter, Depends, HTTPException, status+from pydantic import BaseModel, Field+from sqlalchemy import text++from app.api.v1.deps import AuthUser, require_permission+from app.db.rls import TenantDBSession+from app.services import sample_data++router = APIRouter()+++class SetupStep(BaseModel):+ """One thing a tenant has or has not done."""++ key: str+ label: str+ done: bool+ #: What this unlocks, in the operator's terms rather than the+ #: product's. A checklist that does not say why is a chore list.+ why: str+ #: Where to go. Null when the step cannot be done from the console.+ href: str | None = None+ detail: str | None = None+++class OnboardingStatus(BaseModel):+ first_run: bool = Field(+ description=(+ "True when this tenant has no connectors and no alerts. The console "+ "routes a first-run tenant to the setup wizard rather than to an "+ "empty dashboard."+ )+ )+ steps: list[SetupStep]+ connectors: int+ alerts: int+ sample_data_loaded: bool+++class SampleDataResponse(BaseModel):+ accepted: int+ rejected: int+ scenarios: list[dict[str, Any]]+ note: str+++async def _count(db: Any, sql: str, **params: Any) -> int:+ try:+ result = await db.execute(text(sql), params)+ return int(result.scalar() or 0)+ except Exception: # noqa: BLE001+ # A table that does not exist yet on a half-migrated deployment+ # must not 500 the wizard that is trying to help the operator fix+ # it. Zero is also the honest answer: nothing is there.+ return 0++[email protected]("/status", response_model=OnboardingStatus)+async def onboarding_status(+ user: Annotated[AuthUser, Depends(require_permission("alerts:read"))],+ db: TenantDBSession,+) -> OnboardingStatus:+ """What this tenant has set up, derived from its data.++ Derived rather than stored. A `tenant.onboarded` boolean drifts the+ moment somebody connects a source through the API, deletes their last+ connector, or restores a backup — and a wizard that insists you are+ finished when your estate is empty is worse than no wizard.+ """+ tenant_id = str(user.tenant_id)++ connectors = await _count(+ db,+ "SELECT COUNT(*) FROM connectors WHERE tenant_id = CAST(:t AS uuid)",+ t=tenant_id,+ )+ alerts = await _count(+ db,+ "SELECT COUNT(*) FROM alerts WHERE tenant_id = CAST(:t AS uuid)",+ t=tenant_id,+ )+ sample_alerts = await _count(+ db,+ """+ SELECT COUNT(*) FROM alerts+ WHERE tenant_id = CAST(:t AS uuid)+ AND connector_type = :c+ """,+ t=tenant_id,+ c=sample_data.SAMPLE_CONNECTOR,+ )+ users = await _count(+ db,+ "SELECT COUNT(*) FROM users WHERE tenant_id = CAST(:t AS uuid)",+ t=tenant_id,+ )++ # A connector that is only *configured* is not a connector that is+ # working, so "data arriving" is a separate step. Conflating them is+ # how an operator ends up believing they are done while nothing has+ # ever been polled.+ real_alerts = alerts - sample_alerts++ steps = [+ SetupStep(+ key="admin",+ label="Administrator account",+ done=users > 0,+ why="You are signed in, so this one is already true.",+ href=None,+ ),+ SetupStep(+ key="connector",+ label="Connect a data source",+ done=connectors > 0,+ why=("AiSOC triages what your tools already see. Until something is connected there is nothing for it to work on."),+ href="/onboarding",+ detail=(f"{connectors} connected" if connectors else "Nothing connected yet"),+ ),+ SetupStep(+ key="data",+ label="Receive your first alert",+ done=real_alerts > 0,+ why=(+ "Proves the whole path end to end: your tool, ingest, correlation "+ "and triage. A connector that saves but never polls looks identical "+ "until an alert arrives."+ ),+ href="/alerts",+ detail=(f"{real_alerts} from your own sources" if real_alerts else "No alerts from a connected source yet"),+ ),+ SetupStep(+ key="try",+ label="Or try it with sample data",+ done=sample_alerts > 0,+ why=(+ "Pushes five scenarios through the same ingest endpoint a real "+ "connector uses, so you can see triage work before you have "+ "credentials for anything."+ ),+ href=None,+ detail=(f"{sample_alerts} sample alert(s) loaded" if sample_alerts else "Nothing loaded"),+ ),+ ]++ return OnboardingStatus(+ # Sample data deliberately does **not** clear first-run: somebody+ # who has only looked at samples still has nothing connected, and+ # telling them they are set up would be the fabrication this+ # product spends most of its effort avoiding.+ first_run=connectors == 0 and real_alerts == 0,+ steps=steps,+ connectors=connectors,+ alerts=alerts,+ sample_data_loaded=sample_alerts > 0,+ )+++ "/sample-data",+ response_model=SampleDataResponse,+ status_code=status.HTTP_202_ACCEPTED,+)+async def load_sample_data(+ user: Annotated[AuthUser, Depends(require_permission("alerts:write"))],+ db: TenantDBSession,+) -> SampleDataResponse:+ """Push five labelled scenarios through the real pipeline.++ Refuses on a tenant that already has real alerts. Sample rows in a+ live queue are indistinguishable from real ones at a glance, and an+ analyst who dismisses a genuine alert because they assumed it was+ sample data is a worse outcome than an evaluator having to use a+ second tenant.+ """+ tenant_id = str(user.tenant_id)++ real = await _count(+ db,+ """+ SELECT COUNT(*) FROM alerts+ WHERE tenant_id = CAST(:t AS uuid)+ AND (connector_type IS NULL OR connector_type <> :c)+ """,+ t=tenant_id,+ c=sample_data.SAMPLE_CONNECTOR,+ )+ if real > 0:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=(+ f"This tenant already has {real} alert(s) from real sources. Sample "+ "data is not loaded into an estate that is already working, because "+ "a sample alert sitting in a live queue is indistinguishable from a "+ "real one at a glance."+ ),+ )++ try:+ uuid.UUID(tenant_id)+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="The authenticated session carries no usable tenant.",+ ) from exc++ try:+ result = await sample_data.load(tenant_id=tenant_id)+ except sample_data.SampleDataError as exc:+ # 502, not 500: the API is fine and something it depends on is+ # not, and the message says which.+ raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc++ return SampleDataResponse(**result)diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex 5716c8dca..abdd00cf9 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -61,6 +61,7 @@ from app.api.v1.endpoints import (nl_detection,nl_query,oauth,+ onboarding,oncall,passkeys,phishing,@@ -116,6 +117,10 @@ api_router.include_router(connectors.router)# swaps the code, encrypts tokens via the credential vault, and lands the# operator back on /onboarding.api_router.include_router(oauth.router)+# The setup wizard the console shows a first-run tenant instead of an+# empty dashboard, plus the sample-data button it offers an evaluator who+# does not yet have credentials for anything.+api_router.include_router(onboarding.router, prefix="/onboarding", tags=["onboarding"])api_router.include_router(tenants.router)api_router.include_router(usage.router)api_router.include_router(detection_rules.router)diff --git a/services/api/app/services/sample_data.py b/services/api/app/services/sample_data.pynew file mode 100644index 000000000..63350b2e9--- /dev/null+++ b/services/api/app/services/sample_data.py@@ -0,0 +1,267 @@+"""Give a new tenant something to look at, by running the real pipeline.++Why this is not a seed script+------------------------------+`app/scripts/seed_demo.py` exists and writes rows straight into Postgres.+It is the right tool for its job — a rich fixed corpus for demos and+evals — and the wrong tool for this one, for three reasons:++* It targets a **hardcoded demo tenant**, so a self-hoster who ran it+ would populate a tenant they are not signed in to.+* Inserting rows proves nothing about the product. A console full of+ seeded alerts looks identical whether ingest, fusion and triage work or+ are completely broken.+* It is CLI-only, and the operator we are serving here is looking at a+ browser.++So this pushes a handful of events through `POST /v1/ingest/batch` — the+same door a real connector uses — and lets them become alerts the way any+other event does: normalised, fused, correlated, triaged. **If the+pipeline is broken, this produces nothing and says so**, which is far more+useful on a first run than a populated console that proves nothing.++Honesty+-------+Every scenario is obviously synthetic by construction: RFC 5737+documentation IP ranges, RFC 2606 reserved domains, and hostnames that+read as examples. The connector id is `aisoc_sample` and the ingest+profile stamps the vendor as "AiSOC (sample data)", so the alert's own+source attribution says where it came from — a reader who never saw this+wizard can still tell. Nothing here is presented as real activity, a+benchmark, a customer, or an incident.+"""++from __future__ import annotations++import os+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta+from typing import Any++import httpx+import structlog++logger = structlog.get_logger()++#: The connector id every sample event carries. A dedicated id, not a+#: borrowed vendor one, so sample data can be told apart from — and+#: deleted without touching — anything real.+SAMPLE_CONNECTOR = "aisoc_sample"+++@dataclass(frozen=True)+class Scenario:+ """One sample event, and why it is in the set."""++ key: str+ title: str+ description: str+ severity: str+ rationale: str+ fields: dict[str, Any]+++#: Five scenarios, chosen to exercise different parts of the product+#: rather than to pad a console. Between them they produce a range of+#: severities, two entity types the Investigation Rail can pivot on, and+#: at least one case the triage agent should be able to call benign —+#: because a first run where everything is critical teaches an operator+#: nothing about how the product reasons.+SCENARIOS: tuple[Scenario, ...] = (+ Scenario(+ key="brute_force",+ title="Repeated failed sign-ins from a single address",+ description=("42 failed authentications for 3 accounts from 198.51.100.23 in 4 minutes, followed by one success."),+ severity="high",+ rationale="Password spraying that succeeds — the shape most worth catching early.",+ fields={+ "src_ip": "198.51.100.23",+ "user_name": "[email protected]",+ "host": "sso-gateway-01",+ "event_name": "AuthenticationFailure",+ "failure_count": 42,+ },+ ),+ Scenario(+ key="impossible_travel",+ title="Sign-in from two countries 40 minutes apart",+ description=(+ "[email protected] authenticated from 203.0.113.9 and then from 198.51.100.77, a distance no traveller covers in 40 minutes."+ ),+ severity="high",+ rationale="Identity compromise that only a correlation across events can see.",+ fields={+ "src_ip": "203.0.113.9",+ "user_name": "[email protected]",+ "host": "sso-gateway-01",+ "event_name": "ImpossibleTravel",+ },+ ),+ Scenario(+ key="encoded_powershell",+ title="Encoded PowerShell launched by a document",+ description=("WINWORD.EXE spawned powershell.exe with -enc on WS-FINANCE-04. The decoded command fetches a second stage."),+ severity="critical",+ rationale="The classic initial-access chain, and a clear true positive.",+ fields={+ "host": "WS-FINANCE-04",+ "user_name": "[email protected]",+ "process_name": "powershell.exe",+ "parent_process": "WINWORD.EXE",+ "event_name": "SuspiciousProcess",+ },+ ),+ Scenario(+ key="s3_public",+ title="Storage bucket made public",+ description=(+ "A bucket policy on example-corp-backups was changed to allow public reads "+ "by a service principal that has never changed a policy before."+ ),+ severity="medium",+ rationale="Cloud posture, and a different connector category from the rest.",+ fields={+ "user_name": "[email protected]",+ "resource": "example-corp-backups",+ "event_name": "PutBucketPolicy",+ "cloud_platform": "aws",+ },+ ),+ Scenario(+ key="scanner_noise",+ title="Vulnerability scanner sweeping the estate",+ description=(+ "The authorised scanner at 198.51.100.5 touched 240 hosts in sequence, which is what it is scheduled to do every Sunday."+ ),+ severity="low",+ rationale=(+ "Deliberately benign. A first run where every alert is critical teaches an "+ "operator nothing about how the product separates signal from routine."+ ),+ fields={+ "src_ip": "198.51.100.5",+ "host": "scanner-01",+ "event_name": "PortScan",+ "hosts_touched": 240,+ },+ ),+)+++class SampleDataError(RuntimeError):+ """Something the operator needs told about, without a traceback."""+++def _ingest_url() -> str:+ base = (os.getenv("INGEST_PUBLIC_URL") or os.getenv("INGEST_SERVICE_URL") or "").rstrip("/")+ return f"{base}/v1/ingest/batch" if base else "http://ingest-worker:8080/v1/ingest/batch"+++def _service_token() -> str:+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip() or os.getenv("AISOC_INGEST_TOKEN", "").strip()+++def build_events(*, now: datetime | None = None) -> list[dict[str, Any]]:+ """The sample batch, spread over the last hour.++ Spread rather than stamped with one timestamp so the alert list, the+ volume chart and the correlation window all have something to show —+ five events at an identical instant look like a bug.+ """+ base = now or datetime.now(UTC)+ events = []+ for index, scenario in enumerate(SCENARIOS):+ when = base - timedelta(minutes=(len(SCENARIOS) - index) * 11)+ events.append(+ {+ "source": SAMPLE_CONNECTOR,+ "external_id": f"sample-{scenario.key}-{int(when.timestamp())}",+ "title": scenario.title,+ "description": scenario.description,+ "severity": scenario.severity,+ "created_at": when.isoformat(),+ "raw_event": {+ **scenario.fields,+ # Carried into the lake so a reader inspecting the raw+ # event — not just the alert — can still tell.+ "aisoc_sample_data": True,+ "aisoc_sample_scenario": scenario.key,+ },+ **scenario.fields,+ }+ )+ return events+++async def load(*, tenant_id: str, timeout: float = 30.0) -> dict[str, Any]:+ """Push the sample batch into the caller's own tenant.++ Returns what ingest accepted. Raises `SampleDataError` with something+ an operator can act on — a first run is the worst possible moment for+ a stack trace.+ """+ token = _service_token()+ if not token:+ raise SampleDataError(+ "No service token is configured, so the API cannot post to ingest. "+ "AISOC_SERVICE_TOKEN is generated by `make up`; if this deployment was "+ "assembled by hand, set it in .env and restart the api service."+ )++ events = build_events()+ payload = {+ "connector_id": SAMPLE_CONNECTOR,+ "connector_type": SAMPLE_CONNECTOR,+ "events": events,+ }++ try:+ async with httpx.AsyncClient(timeout=timeout) as client:+ response = await client.post(+ _ingest_url(),+ json=payload,+ headers={+ "Authorization": f"Bearer {token}",+ "X-Tenant-ID": tenant_id,+ "Content-Type": "application/json",+ },+ )+ except httpx.HTTPError as exc:+ raise SampleDataError(+ f"Could not reach the ingest service at {_ingest_url()}: {exc}. "+ "Sample data goes through the same door a real connector uses, so this "+ "means the pipeline itself is not reachable — `make doctor` will say why."+ ) from exc++ if response.status_code >= 400:+ raise SampleDataError(f"Ingest refused the sample batch with HTTP {response.status_code}: {response.text[:300]}")++ body = response.json() if response.content else {}+ accepted = int(body.get("accepted", 0))+ logger.info(+ "sample_data.loaded",+ tenant_id=tenant_id,+ accepted=accepted,+ rejected=body.get("rejected", 0),+ )+ return {+ "accepted": accepted,+ "rejected": int(body.get("rejected", 0)),+ "scenarios": [+ {+ "key": s.key,+ "title": s.title,+ "severity": s.severity,+ "why": s.rationale,+ }+ for s in SCENARIOS+ ],+ # Said plainly, because the wizard shows it and the gap between+ # "accepted" and "visible as an alert" is where a first-run+ # operator would otherwise conclude the product is broken.+ "note": (+ "These went through the same ingest endpoint a real connector uses. "+ "They take a few seconds to appear as alerts, because they are being "+ "normalised, correlated and triaged exactly like real telemetry."+ ),+ }diff --git a/services/api/tests/test_onboarding_wizard.py b/services/api/tests/test_onboarding_wizard.pynew file mode 100644index 000000000..298306bbd--- /dev/null+++ b/services/api/tests/test_onboarding_wizard.py@@ -0,0 +1,195 @@+"""A first-run tenant gets a wizard, and sample data that proves something.++The gap+-------+A brand-new operator signed in and landed on `/dashboard`: every tile+zero, every panel an honest empty state, and nothing saying what to do+next. The empty states were correct — that work was already done — but+correct and *useful* are different things, and "0 connected sources" is+not a button.++Two properties this file exists to protect+-------------------------------------------+**Sample data must not mark setup complete.** Somebody who has only+looked at samples still has nothing connected, and a checklist that+congratulates them is the flattering fiction this product spends most of+its effort avoiding.++**Sample data must go through the real pipeline.** Inserting rows would+be easier and would prove nothing: a console full of seeded alerts looks+identical whether ingest, fusion and triage work or are completely+broken. Running the real path means a first-run operator who sees alerts+has also seen the product work.+"""++from __future__ import annotations++import pathlib++import pytest+from app.services import sample_data++ENDPOINT = pathlib.Path(__file__).resolve().parents[1] / "app/api/v1/endpoints/onboarding.py"+++class TestTheScenarioSet:+ def test_it_is_not_all_critical(self) -> None:+ """A first run where everything is critical teaches an operator+ nothing about how the product separates signal from routine."""+ severities = {s.severity for s in sample_data.SCENARIOS}+ assert len(severities) >= 3, f"only {severities} represented"+ assert "low" in severities or "info" in severities, (+ "nothing in the sample set is routine, so the console cannot show what a benign verdict looks like"+ )++ def test_every_scenario_says_why_it_is_in_the_set(self) -> None:+ for scenario in sample_data.SCENARIOS:+ assert scenario.rationale, f"{scenario.key} has no rationale"+ assert len(scenario.rationale) > 30++ def test_addresses_are_documentation_ranges(self) -> None:+ """RFC 5737 and RFC 2606. Sample data that uses a real IP or a+ registrable domain is a sample that can point at somebody."""+ import ipaddress++ blob = repr([s.fields for s in sample_data.SCENARIOS])+ for octets in ("192.0.2.", "198.51.100.", "203.0.113."):+ blob = blob.replace(octets, "DOC.")+ found = [+ token+ for token in blob.replace("'", " ").replace(",", " ").split()+ if token.count(".") == 3 and token.replace(".", "").isdigit()+ ]+ for addr in found:+ parsed = ipaddress.ip_address(addr)+ assert not parsed.is_global, (+ f"{addr} is a globally routable address in sample data, so a sample alert points at a real host somebody owns"+ )++ def test_domains_are_reserved(self) -> None:+ blob = repr([s.fields for s in sample_data.SCENARIOS])+ assert "@example.com" in blob+ for risky in ("@gmail", "@outlook", "@acme.io", "@corp.net"):+ assert risky not in blob+++class TestTheBatch:+ def test_events_are_spread_over_time(self) -> None:+ """Five events at one instant look like a bug, and leave the+ volume chart and the correlation window with nothing to show."""+ events = sample_data.build_events()+ stamps = {e["created_at"] for e in events}+ assert len(stamps) == len(events)++ def test_every_event_carries_a_distinct_vendor_id(self) -> None:+ """The CloudTrail lesson: without a distinct `external_id` and+ title, a v5 alert id derived from content makes every event+ deduplicate onto one row."""+ events = sample_data.build_events()+ assert len({e["external_id"] for e in events}) == len(events)+ assert len({e["title"] for e in events}) == len(events)++ def test_the_raw_event_is_marked_too(self) -> None:+ """So a reader inspecting the lake — not just the alert — can+ still tell these from real telemetry."""+ for event in sample_data.build_events():+ assert event["raw_event"]["aisoc_sample_data"] is True+ assert event["raw_event"]["aisoc_sample_scenario"]++ def test_the_connector_id_is_dedicated_not_borrowed(self) -> None:+ """Borrowing a vendor id would make sample data indistinguishable+ from that vendor's real data, and impossible to delete safely."""+ assert sample_data.SAMPLE_CONNECTOR == "aisoc_sample"+ for event in sample_data.build_events():+ assert event["source"] == "aisoc_sample"+++class TestItUsesTheRealPipeline:+ def test_it_posts_to_ingest_rather_than_writing_rows(self) -> None:+ source = pathlib.Path(sample_data.__file__).read_text() if hasattr(sample_data, "__file__") else ""+ assert "/v1/ingest/batch" in source, (+ "sample data no longer goes through ingest, so it proves nothing about whether the pipeline works"+ )+ for row_write in ("INSERT INTO", "session.add", "db.add"):+ assert row_write not in source, (+ f"sample data writes rows directly ({row_write}), which looks identical whether the pipeline works or is completely broken"+ )++ @pytest.mark.asyncio+ async def test_no_service_token_is_an_actionable_error(self, monkeypatch) -> None: # noqa: ANN001+ monkeypatch.delenv("AISOC_SERVICE_TOKEN", raising=False)+ monkeypatch.delenv("AISOC_INGEST_TOKEN", raising=False)+ with pytest.raises(sample_data.SampleDataError) as excinfo:+ await sample_data.load(tenant_id="00000000-0000-0000-0000-000000000001")+ message = str(excinfo.value)+ assert "AISOC_SERVICE_TOKEN" in message+ assert "make up" in message, "the error does not say how to fix it"+++class TestTheEndpointContract:+ def test_sample_data_does_not_clear_first_run(self) -> None:+ """The property that matters most.++ Somebody who has only looked at samples still has nothing+ connected. A checklist that tells them they are set up is a lie+ the rest of this product works hard not to tell.+ """+ source = ENDPOINT.read_text()+ block = source[source.index("return OnboardingStatus(") :]+ assert "first_run=connectors == 0 and real_alerts == 0" in block, (+ "first_run is no longer computed from real sources only, so loading sample data would mark setup complete"+ )++ def test_real_alerts_exclude_the_sample_connector(self) -> None:+ source = ENDPOINT.read_text()+ assert "real_alerts = alerts - sample_alerts" in source++ def test_it_refuses_to_seed_a_working_estate(self) -> None:+ """A sample alert in a live queue is indistinguishable from a real+ one at a glance, and an analyst dismissing a genuine alert because+ they assumed it was sample data is the worse outcome."""+ source = ENDPOINT.read_text()+ assert "HTTP_409_CONFLICT" in source+ assert "already has" in source++ def test_status_is_derived_not_stored(self) -> None:+ """A `tenant.onboarded` flag drifts the moment somebody connects a+ source through the API or deletes their last one."""+ source = ENDPOINT.read_text()+ assert "SELECT COUNT(*) FROM connectors" in source+ assert "SELECT COUNT(*) FROM alerts" in source++ def test_a_missing_table_does_not_500_the_wizard(self) -> None:+ """A half-migrated deployment is exactly when somebody reaches for+ the thing that is supposed to help them fix it."""+ source = ENDPOINT.read_text()+ counter = source[source.index("async def _count") : source.index("@router.get")]+ assert "except Exception" in counter+ assert "return 0" in counter++ def test_an_unreachable_ingest_is_502_not_500(self) -> None:+ """The API is fine and something it depends on is not, and the+ status code should say which."""+ source = ENDPOINT.read_text()+ assert "HTTP_502_BAD_GATEWAY" in source++ def test_every_step_explains_why_it_matters(self) -> None:+ """A checklist that does not say why is a chore list."""+ source = ENDPOINT.read_text()+ assert source.count("why=(") + source.count('why="') >= 4+++class TestTheIngestProfileExists:+ def test_aisoc_sample_is_mapped(self) -> None:+ """Without a profile the batch hits the lenient fallback, every+ event gets the same generic title and no vendor id, and all five+ deduplicate onto one alert — the exact CloudTrail defect."""+ normalizer = pathlib.Path(__file__).resolve().parents[3] / "services/ingest/internal/normalizer/normalizer.go"+ source = normalizer.read_text()+ assert '"aisoc_sample": {' in source, "aisoc_sample has no ingest profile, so all five sample events collapse into one alert"+ block = source[source.index('"aisoc_sample": {') :][:900]+ assert '"title": "message"' in block or '"title":"message"' in block+ assert "external_id" in block+ assert "Sample data" in block, (+ "the profile does not name the sample vendor, so a reader cannot tell sample alerts from real ones in the source column"+ )diff --git a/services/ingest/internal/normalizer/normalizer.go b/services/ingest/internal/normalizer/normalizer.goindex bbf1e6e8c..162f14f0a 100644--- a/services/ingest/internal/normalizer/normalizer.go+++ b/services/ingest/internal/normalizer/normalizer.go@@ -207,6 +207,39 @@ var connectorProfiles = map[string]connectorProfile{"CRITICAL": 5, "HIGH": 4, "MEDIUM": 3, "LOW": 2, "INFORMATIONAL": 1,},},+ // aisoc_sample — the batch the first-run wizard pushes.+ //+ // It goes through this door rather than being inserted into Postgres+ // precisely so it proves something: a console full of seeded rows+ // looks identical whether the pipeline works or is completely broken.+ // Running the real path means a first-run operator who sees alerts+ // has also seen ingest, normalisation, fusion and triage work.+ //+ // The vendor name says what it is. An alert from this batch is+ // attributed to "AiSOC (sample data)" in the console's own source+ // column, so a reader who never saw the wizard can still tell these+ // apart from real telemetry — honesty that does not depend on anyone+ // remembering context.+ //+ // 2001 for the same reason as the others at this class: these are+ // already-judged findings with a severity the wizard sets, not raw+ // telemetry waiting to be assessed.+ "aisoc_sample": {+ product: OcsfProduct{Name: "Sample data", VendorName: "AiSOC"},+ classUID: 2001,+ className: "Security Finding",+ fieldMap: map[string]string{+ "created_at": "time",+ "title": "message",+ "description": "finding.desc",+ "external_id": "finding.uid",+ "severity": "severity",+ "src_ip": "src_endpoint.ip",+ "host": "device.name",+ "user_name": "actor.user.name",+ },+ severityMap: _canonicalSeverityMap,+ },// aws_cloudtrail — the audit log of the AWS account itself.//// It had no entry here, and the symptom found in live QA is worse thandiff --git a/tests/test_port_conflict_resolution.py b/tests/test_port_conflict_resolution.pynew file mode 100644index 000000000..0b9da9c51--- /dev/null+++ b/tests/test_port_conflict_resolution.py@@ -0,0 +1,219 @@+"""`make up` resolves a port conflict instead of refusing to start.++The friction this removes+--------------------------+`make up` used to stop dead when any one of sixteen host ports was taken,+and tell the operator to go edit `docker-compose.yml`. That is a hard stop+at step one of the documented quick start, triggered by the most common+condition in this audience's environment: a Postgres already on 5432, or+an Ollama already on 11434 — and the reader of that README is exactly the+person who has one.++Refusing beat the alternative at the time. Compose reports `Bind for+127.0.0.1:NNNN failed` against whichever container lost the race, half a+stack later. But the right answer to "that port is busy" is to use a+different one and say so, not to stop.++The two bugs this file pins, both found while building it+----------------------------------------------------------+**`SO_REUSEADDR` made the probe more permissive than the real bind.** With+it set, binding `127.0.0.1:5432` *succeeds* while another container holds+`0.0.0.0:5432`, so the detector reported the single most common conflict+as free. A probe easier to satisfy than the thing it predicts is worse+than no probe.++**`$(wildcard)` in a `:=` variable is evaluated when make parses the+file**, which is before the target that writes the overlay has run. The+first `make up` on a conflicting host therefore generated the overlay+correctly and then started compose without it, failing on exactly the+bind it had just resolved.+"""++from __future__ import annotations++import pathlib+import re+import socket+import subprocess+import sys++import pytest++REPO = pathlib.Path(__file__).resolve().parent.parent+# Spelled as one repo-relative literal rather than assembled from Path+# segments. `check_gate_coverage.py` decides whether a script is reached+# by looking for exactly this string, so building the path piecewise made+# the script read as a gate nothing runs — while this file was testing it+# all along.+SCRIPT = REPO / "scripts/resolve_port_conflicts.py"+MAKEFILE = REPO / "Makefile"++[email protected](scope="module")+def module(): # noqa: ANN201+ sys.path.insert(0, str(REPO / "scripts"))+ import resolve_port_conflicts # noqa: PLC0415++ return resolve_port_conflicts+++class TestTheProbe:+ def test_it_sees_a_held_port(self, module) -> None: # noqa: ANN001+ """The behaviour the whole thing rests on.++ This does not hold the wildcard address to simulate a container,+ even though that is the case that originally broke, because+ binding all interfaces in a committed file is a+ `py/bind-socket-all-network-interfaces` finding and this+ repository runs at zero open alerts.++ It does not need to. Once `SO_REUSEADDR` is gone, a loopback bind+ returns `EADDRINUSE` for a wildcard-held port just as it does for+ a loopback-held one — which is why the probe itself stopped+ binding the wildcard too. `test_it_does_not_set_so_reuseaddr` is+ the structural half of that guarantee; this is the behavioural+ half.+ """+ held = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ held.bind(("127.0.0.1", 0))+ held.listen(1)+ port = held.getsockname()[1]+ try:+ assert module._listening(port) is True+ finally:+ held.close()++ def test_it_reports_a_genuinely_free_port_as_free(self, module) -> None: # noqa: ANN001+ probe = socket.socket()+ probe.bind(("127.0.0.1", 0))+ port = probe.getsockname()[1]+ probe.close()+ assert module._listening(port) is False++ def test_it_does_not_set_so_reuseaddr(self) -> None:+ """Pinned in the source, because the failure is silent.++ Nothing about the output of a probe with `SO_REUSEADDR` looks+ wrong; it simply answers "free" for a port that is not.+ """+ import ast++ # Parsed, not grepped: this function's own docstring explains why+ # SO_REUSEADDR is wrong, so a substring search matches the+ # explanation and reports the opposite of the truth.+ tree = ast.parse(SCRIPT.read_text())+ listening = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "_listening")+ calls = [n.func.attr for n in ast.walk(listening) if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)]+ assert "setsockopt" not in calls, (+ "the probe calls setsockopt again; with SO_REUSEADDR it is more permissive "+ "than the bind it is predicting and reports held ports as free"+ )++ def test_it_does_not_bind_all_interfaces(self) -> None:+ """Binding the wildcard adds nothing once SO_REUSEADDR is gone,+ and costs a CodeQL finding on a repository that runs at zero.++ Parsed rather than grepped, for the same reason as the test+ above: the function's docstring discusses `0.0.0.0` at length,+ so a substring search matches the explanation.+ """+ import ast++ tree = ast.parse(SCRIPT.read_text())+ listening = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "_listening")+ literals = [n.value for n in ast.walk(listening) if isinstance(n, ast.Constant)]+ assert "0.0.0.0" not in literals+++class TestTheInventory:+ def test_it_is_read_from_doctor_rather_than_duplicated(self, module) -> None: # noqa: ANN001+ """A second hand-maintained list is a second thing to forget.++ The original port list was missing Ollama's 11434 for exactly that+ reason, so the conflict this audience is most likely to hit was+ the one nothing checked.+ """+ ports = module.inventory()+ assert len(ports) >= 16, f"only {len(ports)} ports parsed out of doctor.sh"+ hosts = {p for p, _s, _c in ports}+ for expected in (5432, 3000, 8000, 11434):+ assert expected in hosts, f"port {expected} is not in the inventory"++ def test_every_entry_names_a_service_and_a_container_port(self, module) -> None: # noqa: ANN001+ for host, service, container in module.inventory():+ assert 1 <= host <= 65535+ assert service and service.islower()+ assert 1 <= container <= 65535+++class TestTheOverlay:+ def test_it_uses_override_not_a_plain_merge(self, module) -> None: # noqa: ANN001+ """A plain override *appends*, leaving the conflicting binding+ published — so compose fails anyway, with the file in place and+ looking correct."""+ rendered = module.render([(5432, "postgres", 5432, 15432)])+ assert "ports: !override" in rendered+ assert '"15432:5432"' in rendered++ def test_it_says_which_port_moved_and_why(self, module) -> None: # noqa: ANN001+ rendered = module.render([(11434, "ollama", 11434, 15434)])+ assert "11434" in rendered and "15434" in rendered+ assert "in use" in rendered++ def test_it_is_valid_yaml(self, module) -> None: # noqa: ANN001+ yaml = pytest.importorskip("yaml")+ # `!override` is a compose-specific tag, so a plain loader rejects+ # it. Confirming the *structure* parses is still worth doing.+ rendered = module.render([(5432, "postgres", 5432, 15432)])+ parsed = yaml.safe_load(rendered.replace("ports: !override", "ports:"))+ assert parsed["services"]["postgres"]["ports"] == ["15432:5432"]+++class TestTheMakefileWiring:+ def test_compose_resolves_the_overlay_lazily(self) -> None:+ """`:=` with `$(wildcard)` is evaluated at parse time, before the+ target that writes the overlay has run."""+ text = MAKEFILE.read_text()+ line = next(ln for ln in text.splitlines() if ln.startswith("COMPOSE ?="))+ assert "$(wildcard" not in line, (+ "COMPOSE resolves the overlay with $(wildcard), which make expands when it parses the file — before _ports can write it"+ )+ assert "docker-compose.ports.yml" in line++ def test_up_resolves_rather_than_refuses(self) -> None:+ text = MAKEFILE.read_text()+ body = text[text.index("\n_ports:") : text.index("\n_ports:") + 1200]+ assert "resolve_port_conflicts.py" in body+ assert "Not starting:" not in body, "make up still refuses on a port conflict instead of resolving it"++ def test_the_smoke_probe_uses_the_real_console_url(self) -> None:+ """A hardcoded 3000 probes nothing once the console has moved, and+ the failure branch reports that as 'an uncredentialed caller was+ served' — the most alarming thing the script can say, and untrue."""+ text = MAKEFILE.read_text()+ body = text[text.index("_anonymous_write_is_refused:") :][:1800]+ assert "$(console_url)/api/v1/cases" in body+ assert "localhost:3000/api/v1/cases" not in body++ def test_the_smoke_probe_reads_curl_without_doubling_the_status(self) -> None:+ """`curl -w '%{http_code}'` prints 000 on a connection failure+ *and* exits non-zero, so `|| echo 000` appended a second one. The+ result, 000000, matched neither branch and fell through to FAIL."""+ text = MAKEFILE.read_text()+ body = text[text.index("_anonymous_write_is_refused:") :][:1800]+ assert "|| echo 000)" not in body+++class TestTheScriptRuns:+ def test_check_mode_changes_nothing(self) -> None:+ before = (REPO / "docker-compose.ports.yml").exists()+ subprocess.run([sys.executable, str(SCRIPT), "--check"], capture_output=True, cwd=REPO, timeout=120)+ assert (REPO / "docker-compose.ports.yml").exists() == before++ def test_it_has_a_docstring_explaining_the_override_tag(self) -> None:+ source = SCRIPT.read_text()+ assert "!override" in source+ assert re.search(r"appends", source), (+ "the reason `ports: !override` is mandatory is not written down, and a "+ "future edit to a plain override would fail in a way that looks correct"+ )