Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(web): stop rendering fabricated security data outside demo mode (#875)

Beenu Arora936a11a9fbbf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7cdfa7188..d7065b999 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -339,6 +339,18 @@ jobs:
# fetched at all. This gate fails the build if that shape reappears.
- name: Verify sample data is gated behind demo mode
run: python scripts/check_mock_data_gated.py
+ # The check above recognises the *shapes* that carried fabricated data:
+ # a bare mock in `fallbackData`, a mock through a state setter, a mock
+ # behind `??`. Each was added after a specific escape, so each knows only
+ # the syntax that got past it last time. `SLADashboard.tsx` wrote the
+ # same defect as a ternary one line below a correctly-gated
+ # `demoFallback(...)` and nothing matched, so 847 alerts and a 42.5m MTTR
+ # rendered on first paint and on error, on every deployment. This gate
+ # asks the two questions that do not depend on guessing the next syntax:
+ # is the fabricated value reachable with no gate in scope, and does a
+ # component decide for itself that it is a demo?
+ - name: Verify no fabricated data is reachable without the demo gate
+ run: python scripts/check_demo_state_gated.py
# Same story for the correlation-narrative builder. It lives canonically
# in `services/fusion/app/services/narrative.py` (called at fusion time
# to populate `FusedAlert.narrative`) and is mirrored into
diff --git a/.gitignore b/.gitignore
index a320f4770..c990488e6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,11 +51,20 @@ coverage.xml
# uploaded as artefacts — never committed.
coverage/
**/coverage/
-# BUT keep app-source route directories literally named `coverage` (e.g. the
-# /tools/coverage page). The rules above are for generated test-coverage output;
-# without this negation the coverage tool page silently drops from the build.
+# BUT keep app-source directories literally named `coverage` (the
+# /tools/coverage route, and `components/coverage/` behind /coverage-advisor).
+# The rules above are for generated test-coverage output; without these
+# negations the coverage tool page silently drops from the build.
+#
+# `components/` was missing here, which is worse than it sounds: the component
+# was tracked because it predates the rule, so nothing looked wrong, but every
+# *new* file beside it — a test especially — was ignored on `git add -A` and
+# never reached CI. A test that cannot be committed is indistinguishable from
+# a test that passes.
!apps/web/src/app/**/coverage/
!apps/web/src/app/**/coverage/**
+!apps/web/src/components/coverage/
+!apps/web/src/components/coverage/**
*.lcov
# IDE
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a393016b9..f281da2ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,9 +39,97 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
daemon runs out of space. Node 22 and pnpm 8, which the installers require,
were also unlisted. All are now in the quick-start prerequisites table with
the command each one gates.
+- **`scripts/generate_corpus_stats.py`** — generates
+ `apps/web/src/data/corpus-stats.json` + `corpusStats.ts` from the compiled
+ engine ruleset, the generated detection truth table, and the marketplace
+ index, reconciling all three against each other and refusing to publish if
+ they disagree. Every landing surface imports the constants, so none can
+ carry its own literal. `--check` is wired into `ci.yml :: python-lint`;
+ `--self-test` hand-edits the artefact and requires the drift to be caught.
+ The artefact keeps `executable` and `onDisk`/`quarantined` as separate
+ fields, and the UI leads with the executable count.
+- **`scripts/check_alert_reduction_claims.py`** — prose cannot be generated
+ the way a count can, so the retraction is gated instead. No published
+ surface may assert the legacy harness runs the production grouping; any
+ surface quoting 75.3 % must carry the retraction; the `alert_reduction`
+ suite card may not be declared `kind: 'measurement'`; and every surface
+ publishing the real figure must quote `PUBLISHED_REDUCTION_PCT`, a new
+ constant in `services/fusion/tests/test_alert_reduction_real.py` that the
+ test asserts against its own measurement — so the chain from measurement
+ to published prose has no hand-copied link. A paragraph that dates or
+ negates the claim is exempt, so the retraction can quote the wording it
+ retracts.
+- **The prerequisites that were required but undocumented.** Beyond Docker and
+ its memory, a first run needs `python3` **on the host** (`make smoke` runs
+ the golden-pipeline script there, so without it you can start AiSOC but
+ cannot prove it works), `bash` (`make up` gates on `scripts/doctor.sh
+ --ports-only` before it calls compose), and roughly 18 GB of free Docker
+ disk — previously implied only by a troubleshooting row noting that Kafka
+ corrupts its log directory and *still passes its healthcheck* when the
+ daemon runs out of space. Node 22 and pnpm 8, which the installers require,
+ were also unlisted. All are now in the quick-start prerequisites table with
+ the command each one gates.
+- **`scripts/generate_corpus_stats.py`** — generates
+ `apps/web/src/data/corpus-stats.json` + `corpusStats.ts` from the compiled
+ engine ruleset, the generated detection truth table, and the marketplace
+ index, reconciling all three against each other and refusing to publish if
+ they disagree. Every landing surface imports the constants, so none can
+ carry its own literal. `--check` is wired into `ci.yml :: python-lint`;
+ `--self-test` hand-edits the artefact and requires the drift to be caught.
+ The artefact keeps `executable` and `onDisk`/`quarantined` as separate
+ fields, and the UI leads with the executable count.
+- **`scripts/check_alert_reduction_claims.py`** — prose cannot be generated
+ the way a count can, so the retraction is gated instead. No published
+ surface may assert the legacy harness runs the production grouping; any
+ surface quoting 75.3 % must carry the retraction; the `alert_reduction`
+ suite card may not be declared `kind: 'measurement'`; and every surface
+ publishing the real figure must quote `PUBLISHED_REDUCTION_PCT`, a new
+ constant in `services/fusion/tests/test_alert_reduction_real.py` that the
+ test asserts against its own measurement — so the chain from measurement
+ to published prose has no hand-copied link. A paragraph that dates or
+ negates the claim is exempt, so the retraction can quote the wording it
+ retracts.
+- **`scripts/check_demo_state_gated.py`** — a CI gate that asks the two
+ questions which do not depend on guessing the next syntax. *Is the
+ fabricated value reachable?* — every read of a fabricated symbol must have a
+ gate in scope, so `cond ? x : MOCK` fails and so does whatever replaces it.
+ *Does the component decide for itself that it is a demo?* — no component may
+ hold demo/sample **mode** in local state, because state derived from a fetch
+ failure fabricates exactly when the backend is unhealthy.
+ It treats three things as fabricated: a `MOCK_*`/`DEMO_*`-style constant; a
+ factory that builds one (the constant convention could not see
+ `buildDemoCase`); and any constant assembled out of either (`EASMView`
+ declared `const SUMMARY = { totalAssets: MOCK_ASSETS.length, … }`, carrying
+ the fabrication under a name the convention does not cover). It accepts the
+ four ways this tree legitimately gates — the read's own bracket-balanced
+ statement, an enclosing `if`, an early return, and a local derived from the
+ gate — but **not** a bare mention of the gate elsewhere in the file, which
+ is the hole `SLADashboard` fell through. Its `KNOWN_UNGATED` ratchet is
+ empty and checked in both directions; a gate seeded with its own exceptions
+ has never been true.
### Changed
+- **`readme_gates.py` covers the governance documents.** Its `FIGURE_DOCS`
+ list named one compliance page, which is why `ROADMAP.md` drifted with CI
+ green. `ROADMAP.md` and `RELEASES.md` are now on the list, the matrix
+ **row total** is compared as well as the GATED/PARTIAL split, and a figure
+ the prose explicitly dates ("the count at that time") is exempt so history
+ need not be rewritten.
+- **`check_scoreboard.py --check` verifies `agent_version` against
+ `VERSION`.** `--refresh` already stamped it; nothing compared it, and the
+ freshness gate reads only the date — which a refresh keeps current — so a
+ row could be two days old and still labelled two majors behind.
+- **`readme_gates.py` covers the governance documents.** Its `FIGURE_DOCS`
+ list named one compliance page, which is why `ROADMAP.md` drifted with CI
+ green. `ROADMAP.md` and `RELEASES.md` are now on the list, the matrix
+ **row total** is compared as well as the GATED/PARTIAL split, and a figure
+ the prose explicitly dates ("the count at that time") is exempt so history
+ need not be rewritten.
+- **`check_scoreboard.py --check` verifies `agent_version` against
+ `VERSION`.** `--refresh` already stamped it; nothing compared it, and the
+ freshness gate reads only the date — which a refresh keeps current — so a
+ row could be two days old and still labelled two majors behind.
- **`readme_gates.py` covers the governance documents.** Its `FIGURE_DOCS`
list named one compliance page, which is why `ROADMAP.md` drifted with CI
green. `ROADMAP.md` and `RELEASES.md` are now on the list, the matrix
@@ -162,7 +250,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`-CloneDir`. The page also still promised a browser opening on a seeded
ransomware case with pre-filled credentials, which no longer happens and for
which there are no default credentials.
-
- **Five banners that misdiagnosed their own failure.** Four of them claimed
to be showing data they were not showing, which is worse than no banner: the
operator now has a confident diagnosis, it is wrong, and they spend the next
@@ -179,7 +266,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
explanation at all. And the copilot pill labelled **any** error "Demo mode"
on deployments that are not the demo, beside a green "Connected" that
asserted connectivity before a single request had been made.
-
`lib/failure.ts` generalises the fix already made for the entity-risk queue.
Two rules: **name the upstream service only when that service is genuinely
at fault** (a 422 is a malformed request from the console and the backend is
@@ -194,7 +280,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
reason about. Every test asserts on **first paint** as well as the error
branch: `data` is `undefined` in both states, so a suite that only drives
the error branch never exercises the one a self-hoster sees on every load.
-
- **Three surfaces that asked for the wrong tenant's data.** `/purple-team`
had `const TENANT_ID = '00000000-0000-0000-0000-000000000001'` at module
scope and used it for all nine of its requests, so on any deployment with
@@ -205,7 +290,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
inlined at build time and is therefore one constant for every operator of
every tenant. Both now read the active tenant from `TenantProvider`, and
every request is `null`-gated on it so nothing is issued against a guess.
-
- **`/fim` was not tenant-scoped, and its own comment had gone stale.** The
component pinned `TENANT_ID = 'default'` and explained that
`services/osquery-tls` used a different tenancy model. That service had in
@@ -223,7 +307,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
node *enrolment* keys `Node.tenant_id` as a `String(64)` defaulting to
`"default"`, so a node enrolled with no tenant header writes events under a
string no console read can resolve. That is an enrolment-side migration.
-
Three contract breaks found while proving the tenancy fix was observable,
all of which made the page unusable regardless of tenancy: the summary
response never carried `active_nodes` while the card called
@@ -232,7 +315,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`page`/`page_size`/`since` to an endpoint declaring `offset`/`limit` and no
`since`, so FastAPI dropped all three — every page showed the same first 100
rows and every time window showed the same events.
-
- **A non-promoted event now leaves a thread to pull.**
`promote_normalized_event` returned `None` and the consumer incremented
`not_promoted`. The aggregate reached `/metrics`, so an operator could see
@@ -241,7 +323,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
first question a new user asks and a counter cannot answer it. The log now
names the connector, the OCSF class and category, the severity, which
promotion condition was not met, and that the event is in the lake.
-
**Volume:** this is the hot path and most ingested telemetry is correctly
not promoted, so a line per event would be the platform's highest-volume log
and would cost more than the pipeline it describes. A pure time-sampled
@@ -253,7 +334,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
is one line per minute regardless of throughput. Tracked shapes are capped
so a connector emitting a garbage `class_uid` per event cannot make the
sampler a memory leak.
-
- **`splunk_enterprise` stays non-promoting, and now says so on the event.**
The profile maps raw Splunk *search result rows* (`_time`, `src`, `dst`,
`user`), not notables, and it stays at `classUID: 4001`: promoting each row
@@ -270,7 +350,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
exactly that, which lands in the lake beside it rather than scrolling past
in a log. A test pins the two constants against the fusion policy they
mirror.
-
- **Organisation memory reaches the triage prompt.** `active_statements`
compiles repeated, tagged analyst disagreement into durable statements; a
repo-wide grep returned exactly one match, its own definition. Its write
@@ -289,11 +368,232 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`test_organisation_memory_in_prompt.py` proves the claim by capturing the
messages handed to the model with and without a recorded disagreement and
diffing them.
-
- `EmptyState` accepts a `headingLevel`. `ConnectorsView` renders it directly
under the page `h1`, so the default `h3` skipped a level and failed
axe-core's `heading-order` rule.
+- **A retracted benchmark figure was still badged "Real measurement".**
+ `apps/docs/docs/benchmark.md` withdrew the 75.3 % alert-reduction claim —
+ the harness that produced it groups on four tiers of `(rule_id, host,
+ user)` while the shipping `RawAlert.correlation_key()` groups on
+ `{tenant}:{entity}:{tactic}`, so it does not merely re-implement fusion's
+ grouping, it implements *different* grouping. The retraction reached one
+ surface of five. `BenchmarkResults.tsx` rendered a green **"Real
+ measurement"** badge on `0.753` with a blurb claiming the harness used the
+ production rules, "same logic"; `benchmarks/alert-reduction.md`
+ (`sidebar_position: 1`) called it a "faithful in-harness re-implementation"
+ and headlined 75.3 %; `ComparisonTable.tsx` qualified it as "measured on
+ fixed noisy stream". Two more were found while gating the invariant:
+ `benchmark-methodology.md`, and `benchmark.md` itself, which re-asserted
+ the claim in its own intro blockquote. All five now carry the wording
+ `benchmark.md` already uses. The comparison table quotes **33.3 %**, the
+ figure measured against the key the product actually runs.
+- **The landing page published three different wrong corpus counts.**
+ "6,998 detections" in four places (the tree indexes 7,016, of which 5,937
+ are quarantined and the engine loads **833**), "57 plugins" (77), "7,117
+ community items" (7,155), and `218 rules across 5 categories` on the
+ contributor leaderboard (833 across 6). The 6,998 figure also quoted the
+ imported corpus as the detection capability, presenting quarantined rules
+ as executable.
+- **Governance figures had gone stale.** `ROADMAP.md` published "136 rows —
+ 128 GATED / 8 PARTIAL" against a matrix holding 139 / 131, in the same
+ sentence that tells the reader to recount with the script "rather than
+ trusting a figure quoted in prose — this line has gone stale before".
+ `CLAIM_TO_GATE_MATRIX.md` carried a stale executable-rule figure (939) in
+ a row note. The scoreboard's newest substrate row was labelled `v8.1.1`
+ while `VERSION` read `10.0.0`; it is refreshed from a fresh deterministic
+ run (0.97, unchanged) and now carries the tree's version. The scoreboard
+ keeps its three rows, all `substrate: true`, and no live-LLM row was
+ invented.
+- **The "Design partners" block on the landing page was removed** rather
+ than updated. Four dashed "Partner A–D" chips under the caption
+ "Reference partners onboarding through Q2 2026": placeholders rather than
+ fabricated logos, but four of them assert a partner count nothing in the
+ repository supports, and the window closed in June 2026 while still being
+ advertised as upcoming.
+- **The Windows installer routed evaluators to a stack that cannot answer the
+ question they came to ask.** `install.sh` was changed to bring up the real
+ deployment, create an administrator and verify the pipeline; `install.ps1`
+ was not, and nothing noticed. It handed off to `pnpm aisoc:demo` — a compose
+ file that opens by saying it does not run the AiSOC pipeline, has no ingest
+ service and no fusion service, sets `AISOC_DISABLE_KAFKA=true`, and whose
+ console content comes entirely from a seed script writing rows straight into
+ Postgres — and then printed `AiSOC is up and running.` A Windows user saw a
+ populated console and concluded the platform worked, having never run the
+ platform. `install.ps1` now performs the stages `make up` and `make smoke`
+ perform: a port pre-check that names the process holding a port rather than
+ letting compose fail with `Bind for 0.0.0.0:5432 failed`, `docker compose
+ up -d`, a wait that reads `docker compose ps -a` so an exited or
+ crash-looping container fails rather than passing, `docker compose run --rm
+ -T api python -m app.scripts.bootstrap_admin`, and the golden-pipeline
+ runner. Windows has no `make` and the Makefile's recipes are POSIX shell, so
+ these are native re-implementations of the same commands rather than a
+ `make` call; `tests/test_installer_parity_gate.py` fails the build if the
+ two installers diverge again.
+- **No administrator was created on Windows, and the closing banner said
+ nothing about credentials.** A Windows user either could not sign in at all
+ or signed in to a seeded database and evaluated that as the product. The
+ banner now surfaces the generated password the same way `install.sh` does:
+ printed once, stored nowhere, with the reset command alongside it. It also
+ no longer claims the pipeline was verified when the check was skipped for
+ want of a Python interpreter.
+- **`install.ps1` pointed at an uninstaller that does not exist.** The closing
+ banner named `.\scripts\install\uninstall.ps1`; the file is `uninstall.ps1`
+ at the repository root and has never been anywhere else, so the last
+ instruction the installer gave a Windows user could not work. The parity
+ gate now asserts every `.ps1` path either script tells a user to run is a
+ file in the repository.
+- **`uninstall.ps1` left the whole stack running while reporting success.** It
+ tore down only `infra/compose/docker-compose.demo.yml`, so every CORE
+ container — Postgres still holding 5432 — survived an uninstall that said it
+ was complete. It now brings down the root `docker-compose.yml` project
+ across every optional profile, then the demo project for anyone who ran the
+ older installer.
+- **`install.ps1` installed dependencies nobody tested.** It used
+ `pnpm install --no-frozen-lockfile` where `install.sh` uses
+ `--frozen-lockfile` for the stated reason that a self-hoster's install must
+ not quietly resolve a dependency set CI never saw. It also accepted Node 20
+ where `install.sh` requires 22, the version every workflow tests on and both
+ Node images ship. Both now match, and the gate compares them.
+- **The docs portal contradicted the README on whether the pipeline works.**
+ `quickstart.md` was a pre-v8.2 page built around `pnpm aisoc:demo`; because
+ the scripts it named still exist, nothing errored and it simply took readers
+ to the wrong stack. Three statements were false. It claimed `.env.example`
+ ships "a pre-generated dev `AISOC_CREDENTIAL_KEY`" — it ships a placeholder
+ that is worse than an empty value, because an empty one makes the API
+ generate an ephemeral key and warn while a malformed one makes the
+ credential vault raise, so the first request touching a connector secret
+ returns HTTP 500. It claimed events posted to `/v1/ingest/batch` "accept
+ cleanly but never become `Alert` rows", which is the exact path `make smoke`
+ asserts and the README publishes as its headline proof. And its cheat sheet
+ offered `aisoc keygen` as the way to generate that vault key, when `aisoc
+ keygen` writes an Ed25519 plugin-signing pair to `~/.aisoc/signing.key` and
+ has nothing to do with Fernet. The page is now written around `make up`,
+ `make bootstrap` and `make smoke`, and its compose-profile table was rebuilt
+ from `docker-compose.yml` rather than corrected from the old text — six port
+ numbers and profile memberships were wrong, and two whole profiles were
+ missing.
+- **`installation.md` documented flags that do not exist.** `-SkipDemo`,
+ `AISOC_SKIP_DEMO` and `-AisocDir` are not accepted by either installer; the
+ real spellings are `--no-launch` / `-NoLaunch` and `--clone-dir` /
+ `-CloneDir`. The page also still promised a browser opening on a seeded
+ ransomware case with pre-filled credentials, which no longer happens and for
+ which there are no default credentials.
+- **A retracted benchmark figure was still badged "Real measurement".**
+ `apps/docs/docs/benchmark.md` withdrew the 75.3 % alert-reduction claim —
+ the harness that produced it groups on four tiers of `(rule_id, host,
+ user)` while the shipping `RawAlert.correlation_key()` groups on
+ `{tenant}:{entity}:{tactic}`, so it does not merely re-implement fusion's
+ grouping, it implements *different* grouping. The retraction reached one
+ surface of five. `BenchmarkResults.tsx` rendered a green **"Real
+ measurement"** badge on `0.753` with a blurb claiming the harness used the
+ production rules, "same logic"; `benchmarks/alert-reduction.md`
+ (`sidebar_position: 1`) called it a "faithful in-harness re-implementation"
+ and headlined 75.3 %; `ComparisonTable.tsx` qualified it as "measured on
+ fixed noisy stream". Two more were found while gating the invariant:
+ `benchmark-methodology.md`, and `benchmark.md` itself, which re-asserted
+ the claim in its own intro blockquote. All five now carry the wording
+ `benchmark.md` already uses. The comparison table quotes **33.3 %**, the
+ figure measured against the key the product actually runs.
+- **The landing page published three different wrong corpus counts.**
+ "6,998 detections" in four places (the tree indexes 7,016, of which 5,937
+ are quarantined and the engine loads **833**), "57 plugins" (77), "7,117
+ community items" (7,155), and `218 rules across 5 categories` on the
+ contributor leaderboard (833 across 6). The 6,998 figure also quoted the
+ imported corpus as the detection capability, presenting quarantined rules
+ as executable.
+- **Governance figures had gone stale.** `ROADMAP.md` published "136 rows —
+ 128 GATED / 8 PARTIAL" against a matrix holding 139 / 131, in the same
+ sentence that tells the reader to recount with the script "rather than
+ trusting a figure quoted in prose — this line has gone stale before".
+ `CLAIM_TO_GATE_MATRIX.md` carried a stale executable-rule figure (939) in
+ a row note. The scoreboard's newest substrate row was labelled `v8.1.1`
+ while `VERSION` read `10.0.0`; it is refreshed from a fresh deterministic
+ run (0.97, unchanged) and now carries the tree's version. The scoreboard
+ keeps its three rows, all `substrate: true`, and no live-LLM row was
+ invented.
+- **The "Design partners" block on the landing page was removed** rather
+ than updated. Four dashed "Partner A–D" chips under the caption
+ "Reference partners onboarding through Q2 2026": placeholders rather than
+ fabricated logos, but four of them assert a partner count nothing in the
+ repository supports, and the window closed in June 2026 while still being
+ advertised as upcoming.
+- **Six console surfaces rendered fabricated security data outside demo mode,
+ on a tree where the existing gate reported clean.** The gate recognises
+ *shapes* — a bare mock in SWR's `fallbackData`, a mock through a state
+ setter, a mock behind `??`. Each was added after a specific escape, so each
+ knows only the syntax that got past it last time.
+ `SLADashboard.tsx` wrote the same defect as a ternary. Line 446 passed
+ `fallbackData: demoFallback(MOCK_SLA_METRICS)`, which is correct and which
+ the gate accepted; line 457 then read `isValidMetrics ? rawMetrics :
+ MOCK_SLA_METRICS`. Outside the hosted demo `demoFallback` returns
+ `undefined`, so the test is falsy on **first paint as much as on error**,
+ and 847 alerts, 23 breaches, a 2.7% breach rate and a 42.5-minute MTTR
+ rendered in both states, identically, on every deployment. The disclosure
+ banner fired only on `metricsError`, so during loading the invented figures
+ appeared with nothing saying so.
+ The worst of the six was `CaseWorkspace.tsx`. A failed case load rendered
+ `buildDemoCase(caseId)`, which copies the route param, so the invention did
+ not present as sample data — it presented *as the case the analyst had
+ opened*, with an invented title, assignee, four linked alert ids, three
+ ATT&CK techniques and a five-event timeline including "Auto-investigation
+ completed". Separately, a failed `casesApi.investigate` was caught and
+ turned into `status: 'completed'` carrying recon IOCs (`192.168.1.105`,
+ `c2.evil-corp.io`), a forensic root cause at 0.88 confidence drawn as a
+ progress bar, three containment actions and a four-entry agent audit log.
+ The structured panels carried no caveat of their own; only a transient
+ toast did, and it is gone by the time anyone reads the verdict. This is the
+ `AlertDetailView` catch-block defect from v10.0.0, surviving in a second
+ file. And `updateStatus` mutated the SWR cache optimistically and, on
+ failure, toasted "writes disabled" without rolling back, so the workspace
+ showed a status the database did not have.
+ `HuntView.tsx` had no demo gate at all: its `demoMode` was a local
+ `useState(false)` flipped by **fetch failure**, so it substituted three
+ detections on named hosts with encoded-PowerShell command lines precisely
+ when the backend was unhealthy — when a reader is least equipped to notice.
+ It also published `took: 42`, a query latency for a query that never ran,
+ in the same line as a real measurement.
+ `CoverageAdvisorView.tsx` was fabricated end to end, with no API call
+ anywhere in the file: fifteen invented ATT&CK verdicts whose recommendation
+ column asserted deployment state it could not know ("Existing PowerShell &
+ Bash rules active"), four headline cards computed from them so "Coverage
+ 50%" and "Critical Gaps 5" were byte-identical everywhere, and one button
+ that raised `toast.success('Detection rule draft created')` and created
+ nothing. It now reads `GET /api/v1/detection/coverage`.
+- **`/coverage-advisor` reports what that endpoint can actually support.**
+ The endpoint returns one cell per technique *at least one rule references*,
+ so a technique nobody has written a rule for never appears and a percentage
+ over those cells is not coverage of ATT&CK — on a tenant with three rules it
+ would read 100%. The page therefore reports the fraction, names its own
+ blind spot in the body copy, and publishes no coverage score. "Covered"
+ means *enabled*: a technique whose only rules are switched off gets its own
+ status and a link to those rules, because a disabled rule detects exactly as
+ much as no rule. The `ROADMAP.md` and `apps/docs/docs/architecture.md`
+ claims that it "ranks technique gaps by adversary prevalence" were corrected
+ — no prevalence data exists anywhere in the tree.
+- **The server fetch on `/cases` was discarded on every non-demo
+ deployment.** `initialCases` is documented as server-rendered data that
+ avoids a flash of mock content. It was folded into the same object as
+ `MOCK_CASES` and the whole thing passed through `demoFallback(fallback)`,
+ which returns `undefined` outside the hosted demo *regardless of whether
+ real SSR data was supplied* — so the round-trip in `cases/page.tsx` was
+ made, awaited and thrown away. Real SSR data is not sample data, and the
+ gate that withholds one must not withhold the other.
+- **`CopilotDock` answered a failed request with an assistant turn.** Same
+ class as the above: a local `demoMode` flipped by fetch failure. Outside the
+ hosted demo the dock now reports that the copilot could not be reached, with
+ the error, instead of emitting a reply.
+
+### Removed
+- **`apps/web/src/components/copilot/InvestigationChat.tsx`** — canned
+ threat-intel replies ("VirusTotal: 14/87 engines flagged malicious",
+ "Associated campaigns: APT-42"), a fixed context sidebar, no API call for
+ the chat, and imported by no file. One import from being live, which is the
+ `MitreStrip.tsx` precedent exactly. It also embedded a personal email
+ address in OSS source; the same string in `FunnelKpiBar.tsx` was removed
+ too. `/investigate` already permanently redirects to `/hunt`, and the
+ multi-turn copilot is `CopilotDock` and `/copilot`, so the docs line naming
+ this component was corrected rather than the component wired.
## [10.0.0] — 2026-09-25
**Two ways for a control to be absent: not written, or written and not
diff --git a/RELEASES.md b/RELEASES.md
index fb9af3fe7..f6c1d49c6 100644
--- a/RELEASES.md
+++ b/RELEASES.md
@@ -2,7 +2,7 @@
This file mirrors what used to live in the "What's new" section of [`README.md`](README.md). The complete, machine-readable inventory (with file paths, env-var diffs, and per-release test counts) lives in [`CHANGELOG.md`](CHANGELOG.md).
-> **TL;DR for first-time visitors:** AiSOC is on `v10.0.0`, released 2026-09-25 — a release about controls that were written and not reachable. Row-level security covered 92 tables and filtered nothing, because every service connected to Postgres as a superuser; fifty-eight routes carried no authentication at all; UEBA reported healthy and could not write an anomaly; AI triage was wired to a gateway both of its resolvers ignored. **It is a major because upgrading requires action** — services now connect as a DML-only `aisoc_app` role. Every product claim is backed by a failing CI test (claim-to-gate matrix: 142 rows — 134 GATED / 8 PARTIAL / 0 NO GATE). The latest GitHub release with notes and downloads: <https://github.com/beenuar/AiSOC/releases/latest>.
+> **TL;DR for first-time visitors:** AiSOC is on `v10.0.0`, released 2026-09-25 — a release about controls that were written and not reachable. Row-level security covered 92 tables and filtered nothing, because every service connected to Postgres as a superuser; fifty-eight routes carried no authentication at all; UEBA reported healthy and could not write an anomaly; AI triage was wired to a gateway both of its resolvers ignored. **It is a major because upgrading requires action** — services now connect as a DML-only `aisoc_app` role. Every product claim is backed by a failing CI test (claim-to-gate matrix: 143 rows — 135 GATED / 8 PARTIAL / 0 NO GATE). The latest GitHub release with notes and downloads: <https://github.com/beenuar/AiSOC/releases/latest>.
---
diff --git a/ROADMAP.md b/ROADMAP.md
index 65cffc439..dcb4955c7 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,7 +44,7 @@ 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 **142 rows — 134 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. 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 **143 rows — 135 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. 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 — Shipped
@@ -194,8 +194,8 @@ SOAR platforms drove this release.
### New console pages (`apps/web/src/components/`)
-- [x] `/investigate` — conversational, multi-turn investigation copilot
-- [x] `/coverage-advisor` — MITRE ATT&CK gap ranking by adversary prevalence
+- [x] `/investigate` — redirects to `/hunt`; the multi-turn copilot is `CopilotDock` and `/copilot`
+- [x] `/coverage-advisor` — ATT&CK techniques your rules reference, ranked by enabled coverage (not by adversary prevalence)
- [x] `/shifts` — analyst shift-handoff dashboard
- [x] `/easm` — External Attack Surface Management
- [x] `/mssp` — MSSP executive dashboard
diff --git a/apps/docs/docs/architecture.md b/apps/docs/docs/architecture.md
index 46a928436..b84c81ca7 100644
--- a/apps/docs/docs/architecture.md
+++ b/apps/docs/docs/architecture.md
@@ -69,8 +69,8 @@ Additional capabilities introduced in 2026 H2:
The v1.5 release ships from a review of G2, Gartner Peer Insights, and customer feedback on AI SOC / SIEM / SOAR platforms. It adds five new agents, eight new console pages, four new API surfaces, and ten new connectors:
- **Autonomous alert triage agents** — `services/agents/app/agents/auto_triage_agent.py` plus four sibling agents (phishing, identity, cloud, insider-threat) classify each alert as `true_positive` / `false_positive` / `benign` with a confidence score. Low-confidence noise auto-closes; the rest is escalated. Surfaced via `/api/v1/agents/triage`.
-- **Conversational investigation chat** — multi-turn copilot at `/investigate` that anchors on a case and reads its evidence, ledger, and entity graph for grounded follow-up Q&A. Component: `apps/web/src/components/copilot/InvestigationChat.tsx`.
-- **MITRE ATT&CK coverage advisor** — `/coverage-advisor` ranks technique gaps by adversary prevalence and recommends rules to close them.
+- **Conversational investigation chat** — the multi-turn copilot is `CopilotDock` (app-wide) and `/copilot`; `/investigate` permanently redirects to `/hunt`. The separate `InvestigationChat.tsx` component this line used to name was imported by nothing and answered from a canned reply table rather than the API, so it was removed rather than wired.
+- **MITRE ATT&CK coverage advisor** — `/coverage-advisor` reads `GET /api/v1/detection/coverage` and ranks the techniques your own rules reference by how much *enabled* coverage each has. It does not rank by adversary prevalence, and techniques no rule references do not appear — the page says so rather than publishing a coverage score it cannot support.
- **Shift handoff dashboard** — `/shifts` shows outgoing/incoming analysts the active cases, in-flight investigations, and queued approvals on one screen. Endpoints in `services/api/app/api/v1/endpoints/shifts.py`.
- **EASM (External Attack Surface Management)** — `/easm` discovers assets, exposed services, and certificate-expiry risks for everything the org points at the public internet.
- **MSSP executive dashboard** — `/mssp` rolls up KPIs, cross-tenant alert volumes, and per-customer SLA posture into a multi-tenant pane.
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 0a3d63370..47a5fde06 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `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: 134 rows
+The last row is the one worth reading first. It is the honest index: 135 rows
`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refuses
to let a row sit at `NO GATE`.
diff --git a/apps/web/src/components/cases/CaseWorkspace.test.tsx b/apps/web/src/components/cases/CaseWorkspace.test.tsx
index 645fc8213..0ffa98497 100644
--- a/apps/web/src/components/cases/CaseWorkspace.test.tsx
+++ b/apps/web/src/components/cases/CaseWorkspace.test.tsx
@@ -1,6 +1,7 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, within } from '@testing-library/react';
import type { AttackChainTimeline, Case } from '@/lib/api';
+import { __setDemoModeForTests } from '@/lib/demoMode';
// We mock SWR rather than the real network layer so the test stays
// hermetic and so we can exercise both the loaded and fallback paths.
@@ -134,6 +135,7 @@ describe('CaseWorkspace', () => {
afterEach(() => {
vi.clearAllMocks();
+ __setDemoModeForTests(null);
});
it('renders the case header with title, severity, and MITRE chips', () => {
@@ -153,18 +155,22 @@ describe('CaseWorkspace', () => {
);
});
- it('shows the demo banner when the backend errors out', () => {
+ it('shows the demo banner when the backend errors out in the hosted demo', () => {
+ // This case previously asserted the fallback fired on *any* deployment.
+ // `buildDemoCase(caseId)` copies the route param, so outside the demo it
+ // put an invented title, assignee and timeline on screen under the id the
+ // analyst had opened. The fallback is right for the hosted demo, which
+ // has no backend of its own, and wrong everywhere else — see
+ // `CaseWorkspaceHonesty.test.tsx` for the other half.
+ __setDemoModeForTests(true);
swrState.caseData = undefined;
swrState.caseError = new Error('fetch failed');
render(<CaseWorkspace caseId="INC-001" />);
- // Falls back to buildDemoCase, so the demo title renders…
expect(
screen.getByRole('heading', { level: 1, name: /lateral movement from finance subnet/i }),
).toBeInTheDocument();
-
- // …and the demo-mode banner is visible so the analyst knows it's not live data.
expect(screen.getByText(/demo data — writes disabled/i)).toBeInTheDocument();
});
diff --git a/apps/web/src/components/cases/CaseWorkspace.tsx b/apps/web/src/components/cases/CaseWorkspace.tsx
index 3d347094a..a59e6e687 100644
--- a/apps/web/src/components/cases/CaseWorkspace.tsx
+++ b/apps/web/src/components/cases/CaseWorkspace.tsx
@@ -11,8 +11,10 @@
* Center: timeline (audit + activity feed)
* Right: tasks + notes
*
- * Like the rest of the app, this gracefully falls back to demo data if the
- * backend hasn't been seeded.
+ * The hosted demo has no backend of its own, so a failed load falls back to
+ * a seeded case *there and only there* — `buildDemoCase()` copies the route
+ * param into the record it invents, which on any other deployment would put
+ * a fabricated incident on screen under the id the analyst had opened.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -40,6 +42,7 @@ import { ErrorState } from '@/components/ui/ErrorState';
import { EmptyState } from '@/components/ui/EmptyState';
import { InvestigationLedger } from './InvestigationLedger';
import { ContextualActions } from '@/components/copilot/ContextualActions';
+import { canUseDemoData } from '@/lib/demoFallback';
type WorkspaceTab =
| 'overview'
@@ -306,7 +309,6 @@ function TaskRow({ task, onChangeStatus }: TaskRowProps) {
// ─── Main ─────────────────────────────────────────────────────────────────────
export function CaseWorkspace({ caseId }: { caseId: string }) {
- const [demoMode, setDemoMode] = useState(false);
// Honor `?tab=…` so the hosted demo deeplink
// (`/cases/INC-RT-001?tab=ledger`) lands visitors directly on the live
// agent decision feed for the LockBit 3.0 ransomware showcase. Falls back
@@ -323,20 +325,18 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
{ revalidateOnFocus: false, shouldRetryOnError: false },
);
- const useFallback = !!error;
+ // `buildDemoCase(caseId)` takes its id from the route param, so an ungated
+ // fallback does not merely show sample data — it presents an invented
+ // title, assignee, four alert ids and a five-event timeline *as the case
+ // the analyst opened*. Outside the hosted demo a failed load reads as a
+ // failed load.
+ const useFallback = !!error && canUseDemoData();
const caseRecord: Case | undefined = useMemo(() => {
if (data) return data;
if (useFallback) return buildDemoCase(caseId);
return undefined;
}, [data, useFallback, caseId]);
- // Track demo mode for the header banner. Calling setState during render is
- // a React anti-pattern that can interact badly with hydration; defer to an
- // effect so the first paint matches between server and client.
- useEffect(() => {
- if (useFallback && !demoMode) setDemoMode(true);
- }, [useFallback, demoMode]);
-
// ─── Investigation state ───────────────────────────────────────────────────
const [investigating, setInvestigating] = useState(false);
const [investigationRunId, setInvestigationRunId] = useState<string | null>(null);
@@ -474,21 +474,21 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
}
}, 5000);
} catch (e: unknown) {
- const message = e instanceof Error ? e.message : 'Backend offline';
- toast(`Demo mode: investigation not available (${message})`);
- // Set demo investigation result
- setInvestigationStatus('completed');
- setInvestigationData({
- status: 'completed',
- recon: { iocs: [{ type: 'ip', value: '192.168.1.105' }, { type: 'domain', value: 'c2.evil-corp.io' }], mitre_techniques: ['T1021.002', 'T1078'], summary: 'Lateral movement via SMB with stolen credentials. C2 domain identified.' },
- forensic: { timeline: [{ ts: new Date().toISOString(), event: 'SMB connection from FIN-DB01 to BACKUP-SRV-12' }], root_cause_hypothesis: 'Compromised svc_backup service account used for lateral movement.', confidence: 0.88, summary: 'High confidence lateral movement chain identified.' },
- responder: { recommended_actions: ['Isolate WIN-FIN-DB01', 'Rotate svc_backup credentials', 'Block C2 domain at perimeter'], risk_level: 'high', dry_run: true, summary: 'Containment actions generated (dry-run only — review before executing).' },
- audit_log: [{ kind: 'recon', agent: 'ReconAgent', summary: 'Found 2 IOCs, 2 MITRE techniques in 1200ms', ts: new Date().toISOString() }, { kind: 'forensic', agent: 'ForensicAgent', summary: 'Timeline: 1 events, confidence 88%', ts: new Date().toISOString() }, { kind: 'responder', agent: 'ResponderAgent', summary: 'Generated 3 recommended actions (risk=high, dry_run=True)', ts: new Date().toISOString() }, { kind: 'report', agent: 'ReportWriterAgent', summary: 'Report written (1240 chars)', ts: new Date().toISOString() }],
- });
- setReportMd(`# Incident Report — ${caseRecord.title}\n\n**Generated by AiSOC AI Investigator (demo mode)**\n\n## Executive Summary\nLateral movement confirmed from WIN-FIN-DB01 to BACKUP-SRV-12 via compromised service account credentials.\n\n## IOCs\n- 192.168.1.105 (internal pivot source)\n- c2.evil-corp.io (C2 domain)\n\n## MITRE ATT&CK\n- T1021.002 — SMB/Windows Admin Shares\n- T1078 — Valid Accounts\n\n## Recommended Actions\n1. Isolate WIN-FIN-DB01 from network\n2. Rotate svc_backup credentials immediately\n3. Block c2.evil-corp.io at perimeter firewall\n\n---\n*This is a demo report generated without a live backend.*`);
+ // An investigation that could not start did not reach a verdict. This
+ // branch used to answer a failed request with `status: 'completed'`
+ // plus invented IOCs, a root cause at 0.88 confidence drawn as a
+ // progress bar, three containment actions and an agent audit log —
+ // structured panels that carried no caveat of their own, behind a toast
+ // that is gone by the time anyone reads them. An analyst cannot tell
+ // that verdict apart from one the agents actually produced.
+ const message = e instanceof Error ? e.message : 'Could not reach the investigation service';
+ setInvestigationStatus('failed');
+ setInvestigationData({ status: 'failed', error: message });
+ setReportMd('');
setInvestigating(false);
+ toast.error(`Investigation could not start: ${message}`);
}
- }, [caseRecord, caseId, investigating, stopPolling]);
+ }, [caseRecord, caseId, investigating, stopPolling, connectWs]);
// ─── Local mutations (optimistic) ──────────────────────────────────────────
@@ -515,13 +515,19 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
const updateStatus = async (status: CaseStatus) => {
if (!caseRecord) return;
+ const previous = caseRecord.status;
setStatusUpdating(true);
void mutate({ ...caseRecord, status }, { revalidate: false });
try {
await casesApi.update(caseRecord.id, { status });
toast.success(`Status set to ${STATUS_LABEL[status]}`);
- } catch {
- toast(`Demo: status set to ${STATUS_LABEL[status]} locally (writes disabled)`);
+ } catch (e: unknown) {
+ // The optimistic mutation has to come back off. Leaving it applied
+ // showed a status the database does not have, on the one screen an
+ // analyst uses to decide whether an incident is still open.
+ void mutate({ ...caseRecord, status: previous }, { revalidate: false });
+ const message = e instanceof Error ? e.message : 'the case service rejected the write';
+ toast.error(`Status unchanged — ${message}`);
} finally {
setStatusUpdating(false);
}
@@ -642,7 +648,7 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
<span className="text-slate-600">/</span>
<span className="font-mono text-slate-400">{caseRecord.id}</span>
</div>
- {demoMode && (
+ {useFallback && (
<span className="inline-flex items-center gap-1.5 rounded-full bg-amber-500/10 px-2 py-0.5 text-[11px] text-amber-300 ring-1 ring-amber-500/30">
<span className="h-1.5 w-1.5 rounded-full bg-amber-400" />
Demo data — writes disabled
diff --git a/apps/web/src/components/cases/CaseWorkspaceHonesty.test.tsx b/apps/web/src/components/cases/CaseWorkspaceHonesty.test.tsx
new file mode 100644
index 000000000..355057ab4
--- /dev/null
+++ b/apps/web/src/components/cases/CaseWorkspaceHonesty.test.tsx
@@ -0,0 +1,284 @@
+/**
+ * Data-honesty gate for the case workspace.
+ *
+ * Three separate ways this screen published invented incident state, all of
+ * them reachable on any deployment whose backend was merely unreachable:
+ *
+ * 1. `const useFallback = !!error` — no demo gate at all. A failed case load
+ * rendered `buildDemoCase(caseId)`, which takes its id from the route
+ * param, so the fabrication presented *as the case the analyst opened*:
+ * a title, an assignee, four linked alert ids, three ATT&CK techniques
+ * and a five-event timeline including "Auto-investigation completed".
+ *
+ * 2. A failed `casesApi.investigate` was caught and turned into
+ * `status: 'completed'` with invented recon IOCs, a forensic root cause
+ * at 0.88 confidence drawn as a progress bar, three containment actions
+ * and a four-entry agent audit log. The structured panels carried no
+ * caveat — only a transient toast, which is gone by the time anyone
+ * reads the verdict.
+ *
+ * 3. `updateStatus` mutated the SWR cache optimistically and, on failure,
+ * toasted "writes disabled" without rolling back — so the workspace
+ * showed a status the database did not have.
+ *
+ * These assert the negative (no fabricated string reaches the DOM) plus the
+ * positive half that stops the fix becoming "render nothing": the demo build
+ * is still populated, and a real case still renders.
+ */
+
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { __setDemoModeForTests } from '@/lib/demoMode';
+import type { Case } from '@/lib/api';
+
+const swrData = vi.hoisted(() => new Map<string, unknown>());
+const swrErrors = vi.hoisted(() => new Map<string, unknown>());
+const swrMutate = vi.hoisted(() => vi.fn());
+
+vi.mock('swr', () => ({
+ __esModule: true,
+ default: (key: unknown) => {
+ const k = typeof key === 'string' ? key : JSON.stringify(key);
+ return {
+ data: swrData.get(k),
+ error: swrErrors.get(k),
+ isLoading: false,
+ mutate: swrMutate,
+ };
+ },
+}));
+
+const casesApi = vi.hoisted(() => ({
+ get: vi.fn(),
+ update: vi.fn(),
+ investigate: vi.fn(),
+ getInvestigation: vi.fn(),
+ addComment: vi.fn(),
+ addTask: vi.fn(),
+ updateTask: vi.fn(),
+ openAutoSummaryHtml: vi.fn(),
+ downloadReportPdf: vi.fn(),
+ getAttackChain: vi.fn(),
+}));
+
+vi.mock('@/lib/api', () => ({
+ __esModule: true,
+ casesApi,
+ graphApi: { getCaseAttackPath: vi.fn() },
+ realtimeApi: { ticket: vi.fn().mockRejectedValue(new Error('no ticket')) },
+}));
+
+vi.mock('next/link', () => ({
+ __esModule: true,
+ default: ({ children, href }: { children: React.ReactNode; href: string }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+
+vi.mock('next/navigation', () => ({
+ __esModule: true,
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }),
+ usePathname: () => '/cases/INC-2026-0042',
+ useSearchParams: () => new URLSearchParams(),
+}));
+
+// Both are exercised by their own suites and each opens its own requests.
+vi.mock('./InvestigationLedger', () => ({
+ __esModule: true,
+ InvestigationLedger: () => null,
+}));
+
+vi.mock('@/components/copilot/ContextualActions', () => ({
+ __esModule: true,
+ ContextualActions: () => null,
+}));
+
+import { CaseWorkspace } from './CaseWorkspace';
+
+/** The route param. `buildDemoCase` copied it, so the invention wore this id. */
+const CASE_ID = 'INC-2026-0042';
+
+const SWR_KEY = JSON.stringify(['case', CASE_ID]);
+
+/** Every string `buildDemoCase()` would put on screen. */
+const FABRICATED_CASE_STRINGS = [
+ 'Suspected lateral movement from finance subnet',
+ 'WIN-FIN-DB01',
+ 'BACKUP-SRV-12',
+ 'sasha.lin',
+ 'alert-9012',
+ 'alert-9024',
+ 'T1021.002',
+ 'Auto-investigation completed',
+ 'Rotate svc_backup credentials',
+ 'lateral-movement',
+];
+
+/** Every string the investigate `catch` block would put on screen. */
+const FABRICATED_INVESTIGATION_STRINGS = [
+ '192.168.1.105',
+ 'c2.evil-corp.io',
+ 'Compromised svc_backup service account used for lateral movement.',
+ '88% confidence',
+ 'Isolate WIN-FIN-DB01',
+ 'Block C2 domain at perimeter',
+ 'ReconAgent',
+ 'ForensicAgent',
+];
+
+function expectNoFabrication(names: string[]) {
+ for (const name of names) {
+ expect(
+ document.body.textContent ?? '',
+ `"${name}" is fabricated case data and must not render outside demo mode`,
+ ).not.toContain(name);
+ }
+}
+
+/** A real case, as the API would return it. */
+function realCase(overrides: Partial<Case> = {}): Case {
+ return {
+ id: CASE_ID,
+ title: 'Unusual sign-in from an unrecognised ASN',
+ description: 'One failed conditional-access challenge followed by a success.',
+ status: 'open',
+ severity: 'medium',
+ alertIds: [],
+ alertCount: 0,
+ tags: [],
+ mitre: [],
+ createdBy: 'system',
+ createdAt: '2026-05-06T09:00:00Z',
+ updatedAt: '2026-05-06T09:05:00Z',
+ timeline: [],
+ tasks: [],
+ ...overrides,
+ } as Case;
+}
+
+beforeEach(() => {
+ swrData.clear();
+ swrErrors.clear();
+ swrMutate.mockClear();
+ for (const fn of Object.values(casesApi)) fn.mockReset();
+ __setDemoModeForTests(false);
+});
+
+afterEach(() => {
+ cleanup();
+ __setDemoModeForTests(null);
+});
+
+describe('a failed case load does not invent the case', () => {
+ it('renders an error naming the failure, not a fabricated incident', () => {
+ swrErrors.set(SWR_KEY, new Error('503 Service Unavailable'));
+
+ render(<CaseWorkspace caseId={CASE_ID} />);
+
+ expectNoFabrication(FABRICATED_CASE_STRINGS);
+ expect(screen.getByText(/Couldn't load case/i)).toBeTruthy();
+ expect(screen.getByText(/503 Service Unavailable/i)).toBeTruthy();
+ });
+
+ it('offers a retry that re-issues the request', async () => {
+ swrErrors.set(SWR_KEY, new Error('network down'));
+
+ render(<CaseWorkspace caseId={CASE_ID} />);
+ await userEvent.click(screen.getByRole('button', { name: /retry/i }));
+
+ expect(swrMutate).toHaveBeenCalled();
+ });
+
+ it('still shows the seeded case in the hosted demo', () => {
+ // The gate must not have become "never show sample data anywhere".
+ __setDemoModeForTests(true);
+ swrErrors.set(SWR_KEY, new Error('no backend in the demo'));
+
+ render(<CaseWorkspace caseId={CASE_ID} />);
+
+ expect(screen.getByText('Suspected lateral movement from finance subnet')).toBeTruthy();
+ });
+});
+
+describe('a failed investigation is not reported as a completed one', () => {
+ it('surfaces the failure instead of inventing IOCs and a root cause', async () => {
+ swrData.set(SWR_KEY, realCase());
+ casesApi.investigate.mockRejectedValue(new Error('agents service unreachable'));
+
+ render(<CaseWorkspace caseId={CASE_ID} />);
+ await userEvent.click(screen.getByRole('button', { name: /investigate with agent/i }));
+
+ await waitFor(() => {
+ expect(screen.getByText(/Investigation failed/i)).toBeTruthy();
+ });
+ expectNoFabrication(FABRICATED_INVESTIGATION_STRINGS);
+ expect(screen.getByText(/agents service unreachable/i)).toBeTruthy();
+ });
+
+ it('does not claim the investigation completed', async () => {
+ swrData.set(SWR_KEY, realCase());
+ casesApi.investigate.mockRejectedValue(new Error('502 Bad Gateway'));
+
+ render(<CaseWorkspace caseId={CASE_ID} />);
+ await userEvent.click(screen.getByRole('button', { name: /investigate with agent/i }));
+
+ await waitFor(() => {
+ expect(screen.getByText(/Investigation failed/i)).toBeTruthy();
+ });
+ expect(screen.queryByText(/Investigation complete/i)).toBeNull();
+ expect(screen.queryByText(/View full report/i)).toBeNull();
+ });
+
+ it('writes no report for an investigation that never ran', async () => {
+ swrData.set(SWR_KEY, realCase());
+ casesApi.investigate.mockRejectedValue(new Error('down'));
+
+ render(<CaseWorkspace caseId={CASE_ID} />);
+ await userEvent.click(screen.getByRole('button', { name: /investigate with agent/i }));
+ await waitFor(() => {
+ expect(screen.getByText(/Investigation failed/i)).toBeTruthy();
+ });
+
+ await userEvent.click(screen.getByRole('button', { name: /^report$/i }));
+
+ expect(screen.getByText(/No report yet/i)).toBeTruthy();
+ expect(screen.queryByText(/Incident Report — /i)).toBeNull();
+ });
+});
+
+describe('a rejected status write does not stick in the UI', () => {
+ it('rolls the optimistic mutation back when the API refuses it', async () => {
+ swrData.set(SWR_KEY, realCase({ status: 'open' }));
+ casesApi.update.mockRejectedValue(new Error('403 Forbidden'));
+
+ render(<CaseWorkspace caseId={CASE_ID} />);
+ await userEvent.selectOptions(screen.getByRole('combobox'), 'resolved');
+
+ await waitFor(() => {
+ expect(casesApi.update).toHaveBeenCalled();
+ });
+
+ // The last mutate call has to restore the status the server still holds.
+ // Before the fix the only mutate was the optimistic one, so the workspace
+ // sat on `resolved` for a case the database still had as `open`.
+ await waitFor(() => {
+ const restored = swrMutate.mock.calls.at(-1)?.[0] as Case | undefined;
+ expect(restored?.status, 'the rejected write must be rolled back').toBe('open');
+ });
+ });
+
+ it('keeps the write when the API accepts it', async () => {
+ swrData.set(SWR_KEY, realCase({ status: 'open' }));
+ casesApi.update.mockResolvedValue(realCase({ status: 'resolved' }));
+
+ render(<CaseWorkspace caseId={CASE_ID} />);
+ await userEvent.selectOptions(screen.getByRole('combobox'), 'resolved');
+
+ await waitFor(() => {
+ expect(casesApi.update).toHaveBeenCalled();
+ });
+ const last = swrMutate.mock.calls.at(-1)?.[0] as Case | undefined;
+ expect(last?.status).toBe('resolved');
+ });
+});
diff --git a/apps/web/src/components/cases/CasesView.tsx b/apps/web/src/components/cases/CasesView.tsx
index 7adca068a..ee6abebfe 100644
--- a/apps/web/src/components/cases/CasesView.tsx
+++ b/apps/web/src/components/cases/CasesView.tsx
@@ -154,18 +154,29 @@ export function CasesView({ initialCases }: CasesViewProps = {}) {
const [severityFilter, setSeverityFilter] = useState<Case['severity'] | 'all'>('all');
const [search, setSearch] = useState('');
- const fallback: CasesResponse = initialCases ?? {
+ // Real server-rendered cases are not sample data, and the gate that
+ // withholds one must not withhold the other. Folding both into a single
+ // `fallback` and passing that through `demoFallback` returned `undefined`
+ // outside the hosted demo *regardless of whether SSR data was supplied* —
+ // so the server fetch in `cases/page.tsx` was made, awaited and discarded
+ // on every non-demo deployment, which is the flash of empty content the
+ // prop exists to prevent.
+ const sampleCases = demoFallback<CasesResponse>({
cases: MOCK_CASES,
total: MOCK_CASES.length,
page: 1,
pageSize: MOCK_CASES.length,
- };
+ });
const { data: casesData, isLoading } = useSWR(
['cases', statusFilter, severityFilter],
() => casesApi.list({ status: statusFilter !== 'all' ? statusFilter : undefined }),
{
- fallbackData: demoFallback(fallback),
+ fallbackData: initialCases ?? sampleCases,
+ // Supplying `fallbackData` is enough to stop SWR revalidating on mount,
+ // which would turn the SSR snapshot into what the view permanently
+ // shows rather than its first paint.
+ revalidateOnMount: true,
}
);
diff --git a/apps/web/src/components/cases/CasesViewSsr.test.tsx b/apps/web/src/components/cases/CasesViewSsr.test.tsx
new file mode 100644
index 000000000..8dc7ef4fa
--- /dev/null
+++ b/apps/web/src/components/cases/CasesViewSsr.test.tsx
@@ -0,0 +1,130 @@
+/**
+ * The server fetch in `cases/page.tsx` must survive into the first paint.
+ *
+ * `initialCases` is documented as server-rendered data that avoids a flash of
+ * mock content. It was folded into the same `fallback` object as `MOCK_CASES`
+ * and the whole thing passed through `demoFallback(fallback)` — which returns
+ * `undefined` outside the hosted demo *regardless of whether real SSR data
+ * was supplied*. So on every non-demo deployment the server round-trip was
+ * made, awaited, and then discarded.
+ *
+ * Real SSR data is not sample data, and the gate that withholds one must not
+ * withhold the other.
+ */
+
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+import { cleanup, render, screen } from '@testing-library/react';
+import { __setDemoModeForTests } from '@/lib/demoMode';
+import type { CasesResponse } from '@/lib/api';
+
+const swrData = vi.hoisted(() => new Map<string, unknown>());
+const swrFallbacks = vi.hoisted(() => new Map<string, unknown>());
+
+vi.mock('swr', () => ({
+ __esModule: true,
+ default: (key: unknown, _fetcher: unknown, options?: { fallbackData?: unknown }) => {
+ const k = typeof key === 'string' ? key : JSON.stringify(key);
+ swrFallbacks.set(k, options?.fallbackData);
+ return {
+ data: swrData.get(k) ?? options?.fallbackData,
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ };
+ },
+}));
+
+vi.mock('@/lib/api', () => ({
+ __esModule: true,
+ casesApi: { list: vi.fn() },
+}));
+
+vi.mock('next/link', () => ({
+ __esModule: true,
+ default: ({ children, href }: { children: React.ReactNode; href: string }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+
+vi.mock('@/components/saved-views/SavedViewsBar', () => ({
+ __esModule: true,
+ SavedViewsBar: () => null,
+}));
+
+import { CasesView } from './CasesView';
+
+const SSR_CASES: CasesResponse = {
+ cases: [
+ {
+ id: 'case-ssr-1',
+ title: 'Server-rendered case from the API',
+ status: 'open',
+ severity: 'high',
+ alertCount: 2,
+ createdAt: '2026-05-06T09:00:00Z',
+ updatedAt: '2026-05-06T09:30:00Z',
+ tags: [],
+ },
+ ],
+ total: 1,
+ page: 1,
+ pageSize: 1,
+} as CasesResponse;
+
+/** Titles only `MOCK_CASES` carries. */
+const FABRICATED_TITLES = [
+ 'Ransomware incident on finance workstations',
+ 'Suspected APT lateral movement campaign',
+ 'Cryptominer on dev server cluster',
+];
+
+beforeEach(() => {
+ swrData.clear();
+ swrFallbacks.clear();
+ __setDemoModeForTests(false);
+});
+
+afterEach(() => {
+ cleanup();
+ __setDemoModeForTests(null);
+});
+
+describe('server-rendered cases are not discarded outside demo mode', () => {
+ it('renders the SSR payload on first paint', () => {
+ render(<CasesView initialCases={SSR_CASES} />);
+
+ expect(screen.getByText('Server-rendered case from the API')).toBeTruthy();
+ });
+
+ it('still withholds the fabricated list when no SSR data was supplied', () => {
+ render(<CasesView />);
+
+ for (const title of FABRICATED_TITLES) {
+ expect(
+ screen.queryByText(title),
+ `"${title}" is sample data and must not render outside demo mode`,
+ ).toBeNull();
+ }
+ });
+
+ it('never hands the fabricated list to SWR as real SSR data', () => {
+ render(<CasesView initialCases={SSR_CASES} />);
+
+ const supplied = [...swrFallbacks.values()].find(Boolean) as CasesResponse | undefined;
+ expect(supplied?.cases?.[0]?.title).toBe('Server-rendered case from the API');
+ });
+});
+
+describe('the hosted demo is still populated', () => {
+ it('shows the sample list when the build is the demo and there is no SSR data', () => {
+ __setDemoModeForTests(true);
+
+ render(<CasesView />);
+
+ // The sample list cycles ten titles across eighteen rows, so each one
+ // appears more than once.
+ expect(
+ screen.getAllByText('Ransomware incident on finance workstations').length,
+ ).toBeGreaterThan(0);
+ });
+});
diff --git a/apps/web/src/components/copilot/CopilotDock.tsx b/apps/web/src/components/copilot/CopilotDock.tsx
index d0dce9309..90251bc9b 100644
--- a/apps/web/src/components/copilot/CopilotDock.tsx
+++ b/apps/web/src/components/copilot/CopilotDock.tsx
@@ -18,6 +18,7 @@ import Link from 'next/link';
import { clsx } from 'clsx';
import { motion, AnimatePresence } from 'framer-motion';
import { copilotApi, type CopilotMessage } from '@/lib/api';
+import { canUseDemoData } from '@/lib/demoFallback';
const QUICK_PROMPTS = [
'Summarize critical alerts in the last 24h.',
@@ -25,6 +26,19 @@ const QUICK_PROMPTS = [
'Which detection rules are noisiest this week?',
];
+/** What the dock says when the copilot could not be reached. */
+function unavailableReply(error: unknown): CopilotMessage {
+ const detail = error instanceof Error ? error.message : 'the request did not complete';
+ return {
+ id: `err-${Date.now()}`,
+ role: 'assistant',
+ content:
+ `The copilot could not be reached, so there is no answer to give.\n\n` +
+ `\`${detail}\`\n\nTry again once the service is back.`,
+ createdAt: new Date().toISOString(),
+ };
+}
+
function demoReply(prompt: string, page: string): CopilotMessage {
const content =
`**Demo reply** — the LLM backend is offline, so this is a stub.\n\n` +
@@ -48,7 +62,13 @@ export function CopilotDock() {
const [input, setInput] = useState('');
const [sending, setSending] = useState(false);
const [conversationId, setConversationId] = useState<string | undefined>();
- const [demoMode, setDemoMode] = useState(false);
+ /**
+ * Whether the *last request* failed. Not a demo flag: this was `demoMode`,
+ * local state flipped to `true` by a fetch failure, which let a component
+ * decide for itself that the deployment was a demo. Whether a sample reply
+ * may render is `canUseDemoData()`, a property of the build.
+ */
+ const [offline, setOffline] = useState(false);
const pathname = usePathname() ?? '/';
const scrollerRef = useRef<HTMLDivElement>(null);
@@ -109,10 +129,14 @@ export function CopilotDock() {
});
setConversationId(res.conversationId);
setMessages((prev) => [...prev, res.reply]);
- setDemoMode(false);
- } catch {
- setMessages((prev) => [...prev, demoReply(trimmed, pathname)]);
- setDemoMode(true);
+ setOffline(false);
+ } catch (err) {
+ // The hosted demo has no LLM behind it and says so in the reply body.
+ // Everywhere else the failure is reported as a failure: an assistant
+ // turn that reads like an answer is worse than no answer.
+ const sample = canUseDemoData() ? demoReply(trimmed, pathname) : null;
+ setMessages((prev) => [...prev, sample ?? unavailableReply(err)]);
+ setOffline(true);
} finally {
setSending(false);
}
@@ -170,7 +194,7 @@ export function CopilotDock() {
<div>
<p className="text-sm font-semibold text-white">AI Copilot</p>
<p className="text-[11px] text-slate-400">
- {demoMode ? 'Demo mode (offline)' : 'Connected'}
+ {offline ? 'Copilot unavailable' : 'Connected'}
</p>
</div>
</div>
diff --git a/apps/web/src/components/copilot/InvestigationChat.tsx b/apps/web/src/components/copilot/InvestigationChat.tsx
deleted file mode 100644
index e2c2e7e23..000000000
--- a/apps/web/src/components/copilot/InvestigationChat.tsx
+++ /dev/null
@@ -1,472 +0,0 @@
-'use client';
-
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-type MessageRole = 'user' | 'assistant' | 'system';
-
-interface ChatMessage {
- id: string;
- role: MessageRole;
- content: string;
- timestamp: string;
-}
-
-interface SummaryArtifact {
- artifactId: string;
- summaryMarkdown: string;
- closedAt: string;
-}
-
-const QUICK_ACTIONS = [
- 'Investigate Alert',
- 'Summarize Case',
- 'Find IOCs',
- 'Check Reputation',
-] as const;
-
-const MOCK_RESPONSES: Record<string, string> = {
- 'investigate alert':
- 'Analyzing alert ALT-4092... Identified lateral movement from 10.0.3.17 to DC01. ' +
- 'The source host has 3 prior alerts in the last 48h. ATT&CK mapping: T1021.002 (SMB/Admin Shares). ' +
- 'Recommend isolating the host and resetting credentials for svc-backup.',
- 'summarize case':
- 'Case CS-2187 Summary:\n' +
- '- 7 correlated alerts across 3 hosts\n' +
- '- Timeline: initial access at 02:14 UTC, privilege escalation at 02:31 UTC, exfil attempt at 03:05 UTC\n' +
- '- Affected users: j.harlow, svc-backup\n' +
- '- Current status: containment in progress, 2 hosts isolated',
- 'find iocs':
- 'Found 3 related IOCs across 2 tenants:\n' +
- '1. IP 198.51.100.47 — C2 callback (confidence: 92%)\n' +
- '2. Hash e3b0c442...b855 — LockBit dropper (confidence: 95%)\n' +
- '3. Domain secure-login.example-phish.com — credential harvesting (confidence: 88%)\n\n' +
- 'All three match STIX indicators published in the last 24h.',
- 'check reputation':
- 'Reputation check for 198.51.100.47:\n' +
- '- VirusTotal: 14/87 engines flagged malicious\n' +
- '- AbuseIPDB: reported 23 times, confidence 91%\n' +
- '- First seen: 2025-04-12, Last seen: active\n' +
- '- Associated campaigns: APT-42, Operation ShadowGate\n' +
- '- Recommendation: block at perimeter immediately',
-};
-
-function getMockResponse(input: string): string {
- const lower = input.toLowerCase();
- for (const [key, response] of Object.entries(MOCK_RESPONSES)) {
- if (lower.includes(key)) return response;
- }
- return (
- `Analyzing your query: "${input}"\n\n` +
- 'Found 3 related IOCs across 2 tenants. Cross-referencing with MITRE ATT&CK framework... ' +
- 'Identified techniques T1078.002, T1059.001, and T1071.001. ' +
- 'Risk assessment: HIGH. Recommend reviewing the correlated timeline in the case view.'
- );
-}
-
-const CONTEXT = {
- caseId: 'CS-2187',
- alertCount: 7,
- iocsFound: 3,
- riskLevel: 'High',
-};
-
-interface Props {
- /** Optional live run ID. When provided the Close button calls the real API. */
- runId?: string;
-}
-
-export default function InvestigationChat({ runId }: Props) {
- const [messages, setMessages] = useState<ChatMessage[]>([
- {
- id: 'sys-0',
- role: 'system',
- content: 'Investigation session started. Ask questions or use quick actions below.',
- timestamp: new Date().toISOString(),
- },
- ]);
- const [input, setInput] = useState('');
- const [isTyping, setIsTyping] = useState(false);
- const [isClosed, setIsClosed] = useState(false);
- const [isClosing, setIsClosing] = useState(false);
- const [summary, setSummary] = useState<SummaryArtifact | null>(null);
- const [showSummary, setShowSummary] = useState(false);
- const [analystNote, setAnalystNote] = useState('');
- const [showNoteInput, setShowNoteInput] = useState(false);
- const [pdfLoading, setPdfLoading] = useState(false);
- const scrollRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- const el = scrollRef.current;
- if (el) el.scrollTop = el.scrollHeight;
- }, [messages.length, isTyping]);
-
- const sendMessage = (text: string) => {
- const trimmed = text.trim();
- if (!trimmed || isTyping || isClosed) return;
-
- const userMsg: ChatMessage = {
- id: `u-${Date.now()}`,
- role: 'user',
- content: trimmed,
- timestamp: new Date().toISOString(),
- };
- setMessages((prev) => [...prev, userMsg]);
- setInput('');
- setIsTyping(true);
-
- setTimeout(() => {
- const assistantMsg: ChatMessage = {
- id: `a-${Date.now()}`,
- role: 'assistant',
- content: getMockResponse(trimmed),
- timestamp: new Date().toISOString(),
- };
- setMessages((prev) => [...prev, assistantMsg]);
- setIsTyping(false);
- }, 500);
- };
-
- const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault();
- sendMessage(input);
- }
- };
-
- const handleCloseInvestigation = useCallback(async () => {
- setIsClosing(true);
- try {
- let artifactId: string;
- let summaryMarkdown: string;
-
- if (runId) {
- const res = await fetch(`/api/v1/investigations/${runId}/close`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ analyst_note: analystNote || null }),
- });
- if (!res.ok) {
- throw new Error(`Close failed: ${res.status} ${await res.text()}`);
- }
- const data = await res.json();
- artifactId = data.artifact_id;
- summaryMarkdown = data.summary_markdown;
- } else {
- // Offline / demo mode — build a local summary from message history
- artifactId = `demo-${Date.now()}`;
- const msgLines = messages
- .filter((m) => m.role !== 'system')
- .slice(-10)
- .map((m) => `- [${m.role.toUpperCase()}] ${m.content.slice(0, 120)}`)
- .join('\n');
- summaryMarkdown =
- `# Investigation Summary — ${CONTEXT.caseId}\n\n` +
- `**Status:** closed \n**Case ID:** ${CONTEXT.caseId} \n**Alerts:** ${CONTEXT.alertCount} \n**IOCs:** ${CONTEXT.iocsFound} \n**Risk:** ${CONTEXT.riskLevel} \n\n` +
- `## Conversation (last 10 turns)\n\n${msgLines || '_No messages._'}\n\n` +
- (analystNote ? `## Analyst Note\n\n${analystNote}\n\n` : '') +
- `---\n*Generated by AiSOC — [email protected]*`;
- }
-
- setSummary({
- artifactId,
- summaryMarkdown,
- closedAt: new Date().toLocaleString(),
- });
- setIsClosed(true);
- setShowSummary(true);
- setShowNoteInput(false);
-
- const closedMsg: ChatMessage = {
- id: `sys-close-${Date.now()}`,
- role: 'system',
- content: '✓ Investigation closed. Summary generated and stored as an artifact.',
- timestamp: new Date().toISOString(),
- };
- setMessages((prev) => [...prev, closedMsg]);
- } catch (err) {
- console.error('[InvestigationChat] close error:', err);
- const errMsg: ChatMessage = {
- id: `sys-err-${Date.now()}`,
- role: 'system',
- content: `Failed to close investigation: ${String(err)}`,
- timestamp: new Date().toISOString(),
- };
- setMessages((prev) => [...prev, errMsg]);
- } finally {
- setIsClosing(false);
- }
- }, [runId, messages, analystNote]);
-
- const handleDownloadPdf = useCallback(async () => {
- if (!summary) return;
- setPdfLoading(true);
-
- try {
- if (runId) {
- const res = await fetch(`/api/v1/investigations/${runId}/summary.pdf`);
- if (!res.ok) throw new Error(`PDF fetch failed: ${res.status}`);
- const blob = await res.blob();
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `investigation-${runId}.pdf`;
- a.click();
- URL.revokeObjectURL(url);
- } else {
- // Client-side plain-text fallback when no backend is available
- const blob = new Blob([summary.summaryMarkdown], { type: 'text/plain' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `investigation-${CONTEXT.caseId}.md`;
- a.click();
- URL.revokeObjectURL(url);
- }
- } catch (err) {
- console.error('[InvestigationChat] PDF download error:', err);
- } finally {
- setPdfLoading(false);
- }
- }, [runId, summary]);
-
- return (
- <div className="flex h-[calc(100vh-7rem)] gap-4">
- {/* Main chat area */}
- <div className="flex flex-1 flex-col rounded-xl border border-slate-800/80 bg-slate-900/40">
- {/* Header */}
- <div className="flex items-start justify-between border-b border-slate-800/80 px-4 py-3">
- <div>
- <h1 className="text-base font-semibold text-white">Investigation Chat</h1>
- <p className="text-xs text-slate-400">
- AI-assisted threat investigation — ask about alerts, IOCs, or cases
- </p>
- </div>
-
- {/* Close / Status controls */}
- <div className="flex shrink-0 items-center gap-2">
- {isClosed ? (
- <>
- <span className="rounded-full bg-slate-700/60 px-2.5 py-1 text-xs font-medium text-slate-400">
- Closed
- </span>
- <button
- onClick={() => setShowSummary((s) => !s)}
- className="rounded-lg border border-slate-700/70 bg-slate-800/50 px-3 py-1.5 text-xs text-slate-300 hover:border-blue-500/40 hover:text-white"
- >
- {showSummary ? 'Hide Summary' : 'View Summary'}
- </button>
- {summary && (
- <button
- onClick={handleDownloadPdf}
- disabled={pdfLoading}
- className="rounded-lg bg-blue-700/80 px-3 py-1.5 text-xs font-semibold text-white hover:bg-blue-600 disabled:opacity-50"
- >
- {pdfLoading ? 'Exporting…' : '↓ PDF'}
- </button>
- )}
- </>
- ) : (
- <>
- {showNoteInput ? (
- <div className="flex items-center gap-2">
- <input
- type="text"
- value={analystNote}
- onChange={(e) => setAnalystNote(e.target.value)}
- placeholder="Optional analyst note…"
- className="rounded-lg border border-slate-700/70 bg-slate-950/50 px-2 py-1.5 text-xs text-slate-200 placeholder-slate-500 outline-none focus:border-blue-500/50"
- />
- <button
- onClick={handleCloseInvestigation}
- disabled={isClosing}
- className="rounded-lg bg-red-700/80 px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-600 disabled:opacity-60"
- >
- {isClosing ? 'Closing…' : 'Confirm Close'}
- </button>
- <button
- onClick={() => setShowNoteInput(false)}
- className="rounded-lg border border-slate-700/70 px-2.5 py-1.5 text-xs text-slate-400 hover:text-white"
- >
- Cancel
- </button>
- </div>
- ) : (
- <button
- onClick={() => setShowNoteInput(true)}
- disabled={isTyping}
- className="rounded-lg border border-red-800/60 bg-red-950/30 px-3 py-1.5 text-xs font-semibold text-red-400 transition-colors hover:border-red-600/70 hover:bg-red-900/40 hover:text-red-300 disabled:opacity-50"
- >
- Close Investigation
- </button>
- )}
- </>
- )}
- </div>
- </div>
-
- {/* Summary panel (shown when closed) */}
- {showSummary && summary && (
- <div className="border-b border-slate-800/80 bg-slate-950/60 px-4 py-4">
- <div className="mx-auto max-w-3xl">
- <div className="mb-2 flex items-center justify-between">
- <h3 className="text-sm font-semibold text-white">Investigation Summary</h3>
- <span className="text-[11px] text-slate-500">Closed {summary.closedAt}</span>
- </div>
- <pre className="max-h-64 overflow-y-auto whitespace-pre-wrap rounded-lg border border-slate-800/60 bg-slate-900/80 p-3 text-xs text-slate-300">
- {summary.summaryMarkdown}
- </pre>
- <p className="mt-1.5 text-[11px] text-slate-500">
- Artifact ID: <code className="text-slate-400">{summary.artifactId}</code>
- </p>
- </div>
- </div>
- )}
-
- {/* Messages */}
- <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto p-4">
- <ul className="mx-auto max-w-3xl space-y-3">
- {messages.map((m) => {
- if (m.role === 'system') {
- return (
- <li key={m.id} className="flex justify-center">
- <span className="rounded-full bg-slate-800/50 px-3 py-1 text-xs text-slate-500">
- {m.content}
- </span>
- </li>
- );
- }
- const isUser = m.role === 'user';
- return (
- <li key={m.id} className={`flex ${isUser ? 'justify-end' : 'justify-start'}`}>
- <div
- className={`max-w-[80%] whitespace-pre-wrap rounded-2xl px-4 py-3 text-sm ${
- isUser
- ? 'bg-blue-600/20 text-white ring-1 ring-blue-500/30'
- : 'bg-slate-800/70 text-slate-100 ring-1 ring-slate-700/60'
- }`}
- >
- {m.content}
- </div>
- </li>
- );
- })}
- {isTyping && (
- <li className="flex justify-start">
- <div className="rounded-2xl bg-slate-800/70 px-4 py-3 ring-1 ring-slate-700/60">
- <span className="inline-flex items-center gap-1 text-slate-400">
- <span className="animate-pulse">●</span>
- <span className="animate-pulse" style={{ animationDelay: '0.2s' }}>●</span>
- <span className="animate-pulse" style={{ animationDelay: '0.4s' }}>●</span>
- </span>
- </div>
- </li>
- )}
- </ul>
- </div>
-
- {/* Quick actions + input */}
- <div className="border-t border-slate-800/80 p-3">
- {!isClosed && (
- <div className="mx-auto flex max-w-3xl flex-wrap gap-2 pb-2">
- {QUICK_ACTIONS.map((action) => (
- <button
- key={action}
- onClick={() => sendMessage(action)}
- disabled={isTyping}
- className="rounded-full border border-slate-700/70 bg-slate-800/50 px-3 py-1.5 text-xs text-slate-300 transition-colors hover:border-blue-500/40 hover:bg-slate-700/60 hover:text-white disabled:opacity-50"
- >
- {action}
- </button>
- ))}
- </div>
- )}
-
- {isClosed ? (
- <p className="mx-auto max-w-3xl text-center text-xs text-slate-500">
- This investigation is closed. Open a new session to continue.
- </p>
- ) : (
- <div className="mx-auto flex max-w-3xl items-end gap-2 rounded-xl border border-slate-700/70 bg-slate-950/40 p-2 focus-within:border-blue-500/50">
- <textarea
- value={input}
- onChange={(e) => setInput(e.target.value)}
- onKeyDown={onKeyDown}
- rows={1}
- placeholder="Ask about an alert, IOC, or investigation…"
- className="flex-1 resize-none bg-transparent px-2 py-2 text-sm text-slate-100 placeholder-slate-500 outline-none"
- />
- <button
- onClick={() => sendMessage(input)}
- disabled={!input.trim() || isTyping}
- className={`flex-none rounded-lg px-3 py-2 text-sm font-semibold transition-colors ${
- input.trim() && !isTyping
- ? 'bg-blue-600 text-white hover:bg-blue-500'
- : 'bg-slate-800 text-slate-500'
- }`}
- >
- Send
- </button>
- </div>
- )}
- </div>
- </div>
-
- {/* Context panel */}
- <aside className="hidden w-64 flex-col gap-4 rounded-xl border border-slate-800/80 bg-slate-900/40 p-4 lg:flex">
- <h2 className="text-sm font-semibold text-white">Investigation Context</h2>
-
- <div className="space-y-3">
- <div className="rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
- <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
- Case ID
- </p>
- <p className="mt-1 font-mono text-sm text-white">{CONTEXT.caseId}</p>
- </div>
-
- <div className="rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
- <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
- Alert Count
- </p>
- <p className="mt-1 text-2xl font-bold text-white">{CONTEXT.alertCount}</p>
- </div>
-
- <div className="rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
- <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
- IOCs Found
- </p>
- <p className="mt-1 text-2xl font-bold text-amber-400">{CONTEXT.iocsFound}</p>
- </div>
-
- <div className="rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
- <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
- Risk Level
- </p>
- <p className="mt-1 text-lg font-bold text-red-400">{CONTEXT.riskLevel}</p>
- </div>
-
- {/* Status badge */}
- <div className="rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
- <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
- Status
- </p>
- <p className={`mt-1 text-sm font-semibold ${isClosed ? 'text-slate-400' : 'text-emerald-400'}`}>
- {isClosed ? '⬛ Closed' : '🟢 Active'}
- </p>
- </div>
- </div>
-
- <div className="mt-auto rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
- <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
- Session
- </p>
- <p className="mt-1 text-xs text-slate-400">
- {messages.filter((m) => m.role === 'user').length} messages sent
- </p>
- <p className="text-xs text-slate-400">
- {messages.filter((m) => m.role === 'assistant').length} AI responses
- </p>
- </div>
- </aside>
- </div>
- );
-}
diff --git a/apps/web/src/components/coverage/CoverageAdvisorHonesty.test.tsx b/apps/web/src/components/coverage/CoverageAdvisorHonesty.test.tsx
new file mode 100644
index 000000000..90754048f
--- /dev/null
+++ b/apps/web/src/components/coverage/CoverageAdvisorHonesty.test.tsx
@@ -0,0 +1,251 @@
+/**
+ * Data-honesty gate for the coverage advisor.
+ *
+ * The page was fabricated end to end: no API call at all, and a module-scope
+ * `TECHNIQUES` array of fifteen invented ATT&CK verdicts whose recommendation
+ * column asserted deployment state the component could not know — "Existing
+ * PowerShell & Bash rules active", "Ransomware canary files active". The four
+ * headline cards were computed from that array, so "Coverage 50%" and
+ * "Critical Gaps 5" were byte-identical on every deployment. Its only button
+ * raised `toast.success('Detection rule draft created')` and created nothing.
+ *
+ * It now reads `GET /api/v1/detection/coverage`, the same endpoint the MITRE
+ * heatmap and the operations panel already use, which reports per-technique
+ * rule counts for the tenant's own corpus.
+ *
+ * The endpoint only returns techniques that have at least one rule, so the
+ * page cannot speak about techniques with no rule at all. Saying so is part
+ * of the contract: a "100% covered" headline over a corpus of three rules
+ * would be the same class of false claim the invented table was.
+ */
+
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+import { cleanup, render, screen } from '@testing-library/react';
+import { axe } from 'vitest-axe';
+import { __setDemoModeForTests } from '@/lib/demoMode';
+import type { DetectionCoverage } from '@/lib/api';
+
+const swrData = vi.hoisted(() => new Map<string, unknown>());
+const swrErrors = vi.hoisted(() => new Map<string, unknown>());
+const swrMutate = vi.hoisted(() => vi.fn());
+
+vi.mock('swr', () => ({
+ __esModule: true,
+ default: (key: unknown) => {
+ const k = typeof key === 'string' ? key : JSON.stringify(key);
+ return {
+ data: swrData.get(k),
+ error: swrErrors.get(k),
+ isLoading: false,
+ mutate: swrMutate,
+ };
+ },
+}));
+
+const detectionApi = vi.hoisted(() => ({ coverage: vi.fn() }));
+
+vi.mock('@/lib/api', () => ({
+ __esModule: true,
+ detectionApi,
+}));
+
+vi.mock('next/link', () => ({
+ __esModule: true,
+ default: ({ children, href }: { children: React.ReactNode; href: string }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+
+import CoverageAdvisorView from './CoverageAdvisorView';
+
+const COVERAGE_KEY = 'coverage-advisor';
+
+/** Strings the invented `TECHNIQUES` table would put on screen. */
+const FABRICATED_STRINGS = [
+ 'Existing PowerShell & Bash rules active',
+ 'ScriptBlock logging rule deployed',
+ 'Deploy schtasks / cron anomaly detection',
+ 'Ransomware canary files active',
+ 'Rate-limit rules deployed across tenants',
+ 'Add entropy-based payload analysis',
+ 'Monitor DNS/ICMP tunneling patterns',
+ 'WAF log correlation with CVE feeds',
+];
+
+function expectNoFabrication() {
+ for (const name of FABRICATED_STRINGS) {
+ expect(
+ document.body.textContent ?? '',
+ `"${name}" asserts deployment state the component cannot know`,
+ ).not.toContain(name);
+ }
+}
+
+function coverage(overrides: Partial<DetectionCoverage> = {}): DetectionCoverage {
+ return {
+ tactics: ['Execution', 'Persistence'],
+ cells: [
+ {
+ techniqueId: 'T1059',
+ tactic: 'Execution',
+ techniqueName: null,
+ totalRules: 3,
+ activeRules: 3,
+ inactiveRules: 0,
+ },
+ {
+ techniqueId: 'T1053',
+ tactic: 'Persistence',
+ techniqueName: null,
+ totalRules: 2,
+ activeRules: 0,
+ inactiveRules: 2,
+ },
+ ],
+ summary: {
+ totalRules: 5,
+ activeRules: 3,
+ inactiveRules: 2,
+ techniques: 2,
+ coveredTechniques: 1,
+ },
+ generatedAt: '2026-05-06T12:00:00Z',
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ swrData.clear();
+ swrErrors.clear();
+ swrMutate.mockClear();
+ detectionApi.coverage.mockReset();
+ __setDemoModeForTests(false);
+});
+
+afterEach(() => {
+ cleanup();
+ __setDemoModeForTests(null);
+});
+
+describe('the coverage advisor reads the tenant corpus', () => {
+ it('calls the coverage endpoint rather than rendering a baked-in table', () => {
+ swrData.set(COVERAGE_KEY, coverage());
+
+ render(<CoverageAdvisorView />);
+
+ expectNoFabrication();
+ // The real corpus, not the invented one.
+ expect(screen.getByText('T1059')).toBeTruthy();
+ expect(screen.getByText('T1053')).toBeTruthy();
+ });
+
+ it('derives the headline figures from the API summary', () => {
+ swrData.set(COVERAGE_KEY, coverage());
+
+ render(<CoverageAdvisorView />);
+
+ // 1 of 2 techniques has an enabled rule.
+ expect(screen.getByText('1 / 2')).toBeTruthy();
+ // Neither of the invented headline numbers.
+ expect(screen.queryByText('50%')).toBeNull();
+ expect(screen.queryByText('5')).toBeNull();
+ });
+
+ it('says which techniques the endpoint cannot see', () => {
+ swrData.set(COVERAGE_KEY, coverage());
+
+ render(<CoverageAdvisorView />);
+
+ // A technique with no rule never appears in `cells`, so a coverage
+ // percentage over `cells` is not coverage of ATT&CK.
+ expect(screen.getByText(/no rule at all do not appear/i)).toBeTruthy();
+ });
+});
+
+describe('the coverage advisor is honest when it has nothing', () => {
+ it('publishes no figures before the API has answered', () => {
+ render(<CoverageAdvisorView />);
+
+ expectNoFabrication();
+ expect(screen.queryByText('50%')).toBeNull();
+ });
+
+ it('names the failure and offers a retry that re-issues the request', async () => {
+ const { default: userEvent } = await import('@testing-library/user-event');
+ swrErrors.set(COVERAGE_KEY, new Error('HTTP 503'));
+
+ render(<CoverageAdvisorView />);
+
+ expectNoFabrication();
+ expect(screen.getByText(/HTTP 503/i)).toBeTruthy();
+ await userEvent.click(screen.getByRole('button', { name: /retry/i }));
+ expect(swrMutate).toHaveBeenCalled();
+ });
+
+ it('reads a tenant with no rules as empty', () => {
+ swrData.set(
+ COVERAGE_KEY,
+ coverage({
+ cells: [],
+ tactics: [],
+ summary: {
+ totalRules: 0,
+ activeRules: 0,
+ inactiveRules: 0,
+ techniques: 0,
+ coveredTechniques: 0,
+ },
+ }),
+ );
+
+ render(<CoverageAdvisorView />);
+
+ expectNoFabrication();
+ expect(screen.getByText(/No detection rules/i)).toBeTruthy();
+ });
+});
+
+describe('every control does what it says', () => {
+ it('offers no button that reports work it did not do', () => {
+ swrData.set(COVERAGE_KEY, coverage());
+
+ render(<CoverageAdvisorView />);
+
+ // `toast.success('Detection rule draft created for …')` created nothing.
+ expect(screen.queryAllByRole('button', { name: /generate detection/i })).toHaveLength(0);
+ });
+
+ it('links an unenforced technique to the rules that are switched off', () => {
+ swrData.set(COVERAGE_KEY, coverage());
+
+ render(<CoverageAdvisorView />);
+
+ // T1053 has two rules and none enabled — the actionable case.
+ const link = screen.getByRole('link', { name: /2 rules? disabled/i });
+ expect(link.getAttribute('href')).toContain('/detection');
+ });
+});
+
+describe('accessibility', () => {
+ // The page was rebuilt around new states, and the repo gates WCAG AA with
+ // axe-core. Heading order is the rule most easily broken by adding one:
+ // the error and empty branches sit between the `h1` and the table's `h2`.
+ it.each([
+ ['populated', () => coverage()],
+ ['empty', () => coverage({ cells: [], tactics: [], summary: { totalRules: 0, activeRules: 0, inactiveRules: 0, techniques: 0, coveredTechniques: 0 } })],
+ ])('has no violations in the %s state', async (_label, build) => {
+ swrData.set(COVERAGE_KEY, build());
+
+ const { container } = render(<CoverageAdvisorView />);
+
+ expect(await axe(container, { rules: { 'color-contrast': { enabled: false } } })).toHaveNoViolations();
+ });
+
+ it('has no violations in the error state', async () => {
+ swrErrors.set(COVERAGE_KEY, new Error('HTTP 503'));
+
+ const { container } = render(<CoverageAdvisorView />);
+
+ expect(await axe(container, { rules: { 'color-contrast': { enabled: false } } })).toHaveNoViolations();
+ });
+});
diff --git a/apps/web/src/components/coverage/CoverageAdvisorView.tsx b/apps/web/src/components/coverage/CoverageAdvisorView.tsx
index b436d2a71..8bbe4522a 100644
--- a/apps/web/src/components/coverage/CoverageAdvisorView.tsx
+++ b/apps/web/src/components/coverage/CoverageAdvisorView.tsx
@@ -1,183 +1,294 @@
'use client';
-import { useState } from 'react';
+/**
+ * Coverage gap advisor.
+ *
+ * Reads `GET /api/v1/detection/coverage` — the same endpoint behind the MITRE
+ * rule heatmap and the operations panel — and ranks the tenant's own ATT&CK
+ * techniques by how much enabled coverage they have.
+ *
+ * What this replaced: fifteen invented technique verdicts in a module-scope
+ * `TECHNIQUES` array, no API call anywhere in the file, and a recommendation
+ * column that asserted deployment state the component could not possibly know
+ * ("Existing PowerShell & Bash rules active", "Ransomware canary files
+ * active"). The four headline cards were computed from that array, so
+ * "Coverage 50%" and "Critical Gaps 5" were byte-identical on every
+ * deployment, and the only button raised a success toast and created nothing.
+ *
+ * Two things the wired version is deliberately careful about.
+ *
+ * The endpoint returns a cell per technique **that at least one rule
+ * references**. A technique nobody has written a rule for never appears, so
+ * a percentage computed over `cells` is not coverage of ATT&CK — on a tenant
+ * with three rules it would read 100%. The page therefore reports the
+ * fraction, names its own blind spot, and publishes no coverage score.
+ *
+ * And "covered" means *enabled*. A technique whose only rules are switched
+ * off is the actionable case and gets its own status, because a disabled rule
+ * detects exactly as much as no rule.
+ */
+
+import { useMemo, useState } from 'react';
+import Link from 'next/link';
+import useSWR from 'swr';
import { clsx } from 'clsx';
-import toast from 'react-hot-toast';
+import { detectionApi, type DetectionCoverage, type DetectionCoverageCell } from '@/lib/api';
import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
+import { ErrorState } from '@/components/ui/ErrorState';
+import { Skeleton } from '@/components/ui/Skeleton';
-type CoverageStatus = 'covered' | 'partial' | 'gap';
-type Priority = 'high' | 'medium' | 'low';
-
-interface Technique {
- id: string;
- name: string;
- tactic: string;
- status: CoverageStatus;
- priority: Priority;
- recommendation: string;
-}
-
-const TECHNIQUES: Technique[] = [
- { id: 'T1059', name: 'Command and Scripting Interpreter', tactic: 'Execution', status: 'covered', priority: 'low', recommendation: 'Existing PowerShell & Bash rules active' },
- { id: 'T1059.001', name: 'PowerShell', tactic: 'Execution', status: 'covered', priority: 'low', recommendation: 'ScriptBlock logging rule deployed' },
- { id: 'T1071', name: 'Application Layer Protocol', tactic: 'Command & Control', status: 'partial', priority: 'medium', recommendation: 'Add DNS-over-HTTPS detection rule' },
- { id: 'T1053', name: 'Scheduled Task/Job', tactic: 'Persistence', status: 'gap', priority: 'high', recommendation: 'Deploy schtasks / cron anomaly detection' },
- { id: 'T1078', name: 'Valid Accounts', tactic: 'Initial Access', status: 'partial', priority: 'high', recommendation: 'Correlate impossible-travel with auth logs' },
- { id: 'T1021', name: 'Remote Services', tactic: 'Lateral Movement', status: 'gap', priority: 'high', recommendation: 'Monitor RDP/SSH lateral pivots' },
- { id: 'T1486', name: 'Data Encrypted for Impact', tactic: 'Impact', status: 'covered', priority: 'low', recommendation: 'Ransomware canary files active' },
- { id: 'T1027', name: 'Obfuscated Files or Information', tactic: 'Defense Evasion', status: 'gap', priority: 'high', recommendation: 'Add entropy-based payload analysis' },
- { id: 'T1562', name: 'Impair Defenses', tactic: 'Defense Evasion', status: 'partial', priority: 'medium', recommendation: 'Detect tamper of EDR services' },
- { id: 'T1110', name: 'Brute Force', tactic: 'Credential Access', status: 'covered', priority: 'low', recommendation: 'Rate-limit rules deployed across tenants' },
- { id: 'T1048', name: 'Exfiltration Over Alternative Protocol', tactic: 'Exfiltration', status: 'gap', priority: 'high', recommendation: 'Monitor DNS/ICMP tunneling patterns' },
- { id: 'T1087', name: 'Account Discovery', tactic: 'Discovery', status: 'partial', priority: 'medium', recommendation: 'Alert on bulk LDAP enumeration' },
- { id: 'T1547', name: 'Boot or Logon Autostart Execution',tactic: 'Persistence', status: 'gap', priority: 'medium', recommendation: 'Registry run-key change monitoring' },
- { id: 'T1569', name: 'System Services', tactic: 'Execution', status: 'covered', priority: 'low', recommendation: 'Service creation audit rule active' },
- { id: 'T1190', name: 'Exploit Public-Facing Application',tactic: 'Initial Access', status: 'partial', priority: 'high', recommendation: 'WAF log correlation with CVE feeds' },
-];
+type CoverageStatus = 'covered' | 'unenforced';
+type StatusFilter = CoverageStatus | 'all';
const STATUS_STYLES: Record<CoverageStatus, { bg: string; text: string; label: string }> = {
covered: { bg: 'bg-green-500/20', text: 'text-green-400', label: 'Covered' },
- partial: { bg: 'bg-amber-500/20', text: 'text-amber-400', label: 'Partial' },
- gap: { bg: 'bg-red-500/20', text: 'text-red-400', label: 'Gap' },
+ unenforced: { bg: 'bg-amber-500/20', text: 'text-amber-400', label: 'Unenforced' },
};
-const PRIORITY_STYLES: Record<Priority, { bg: string; text: string }> = {
- high: { bg: 'bg-red-500/20', text: 'text-red-400' },
- medium: { bg: 'bg-amber-500/20', text: 'text-amber-400' },
- low: { bg: 'bg-green-500/20', text: 'text-green-400' },
-};
+const FILTERS: ReadonlyArray<{ id: StatusFilter; label: string }> = [
+ { id: 'all', label: 'All' },
+ { id: 'unenforced', label: 'Unenforced' },
+ { id: 'covered', label: 'Covered' },
+];
+
+function statusOf(cell: DetectionCoverageCell): CoverageStatus {
+ return cell.activeRules > 0 ? 'covered' : 'unenforced';
+}
+
+/** Unenforced first, then the thinnest coverage, then by id for stability. */
+function ranked(cells: DetectionCoverageCell[]): DetectionCoverageCell[] {
+ return [...cells].sort(
+ (a, b) =>
+ a.activeRules - b.activeRules ||
+ b.inactiveRules - a.inactiveRules ||
+ a.techniqueId.localeCompare(b.techniqueId),
+ );
+}
export default function CoverageAdvisorView() {
- const [techniques] = useState(TECHNIQUES);
- const [statusFilter, setStatusFilter] = useState<CoverageStatus | 'all'>('all');
+ const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
- const filteredTechniques = statusFilter === 'all'
- ? techniques
- : techniques.filter((t) => t.status === statusFilter);
+ const { data, error, isLoading, mutate } = useSWR<DetectionCoverage>(
+ 'coverage-advisor',
+ () => detectionApi.coverage(),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
- const covered = techniques.filter((t) => t.status === 'covered').length;
- const partial = techniques.filter((t) => t.status === 'partial').length;
- const gaps = techniques.filter((t) => t.status === 'gap').length;
- const coveragePct = Math.round(((covered + partial * 0.5) / techniques.length) * 100);
+ const cells = useMemo(() => ranked(data?.cells ?? []), [data]);
+ const visible = useMemo(
+ () => (statusFilter === 'all' ? cells : cells.filter((c) => statusOf(c) === statusFilter)),
+ [cells, statusFilter],
+ );
- const summaryCards = [
- { label: 'Techniques Covered', value: covered },
- { label: 'Coverage %', value: `${coveragePct}%` },
- { label: 'Critical Gaps', value: gaps },
- { label: 'Recommended Detections', value: techniques.filter((t) => t.status !== 'covered').length },
- ];
+ const summary = data?.summary;
return (
<div className="space-y-8 p-6 max-w-7xl mx-auto">
<div>
<h1 className="text-2xl font-bold text-white">Coverage Gap Advisor</h1>
<p className="text-gray-400 mt-1">
- Identify MITRE ATT&amp;CK coverage gaps and get actionable detection recommendations
+ MITRE ATT&amp;CK techniques your detection rules reference, ranked by how much enabled
+ coverage each one has.
</p>
</div>
- {/* Summary Cards */}
- <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
- {summaryCards.map((c) => (
- <div key={c.label} className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-4">
- <p className="text-xs text-gray-400 uppercase tracking-wider">{c.label}</p>
- <p className="mt-1 text-2xl font-semibold text-white">{c.value}</p>
- </div>
- ))}
- </div>
-
- {/* Gap Analysis Table */}
- <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 overflow-hidden">
- <div className="px-5 py-4 border-b border-gray-800/60 flex flex-wrap items-center gap-3">
- <h2 className="text-lg font-semibold text-white flex-1 min-w-0">Gap Analysis</h2>
- <div className="flex gap-2">
- {(['all', 'gap', 'partial', 'covered'] as const).map((f) => (
- <button
- key={f}
- onClick={() => setStatusFilter(f)}
- className={clsx(
- 'text-xs px-3 py-1 rounded-lg border transition-colors',
- statusFilter === f
- ? 'bg-blue-600/15 text-blue-300 border-blue-600/30'
- : 'text-gray-400 border-gray-800 hover:border-gray-700',
- )}
+ {isLoading && !data ? (
+ <div className="space-y-4">
+ <Skeleton className="h-24 w-full rounded-xl" />
+ <Skeleton className="h-64 w-full rounded-xl" />
+ </div>
+ ) : error ? (
+ // `ErrorState` and `EmptyState` both open at `h3`, so they need an
+ // `h2` above them or the page jumps h1 → h3 and fails the axe
+ // heading-order rule. The section heading is the honest one anyway:
+ // these branches stand in for the gap-analysis table.
+ <GapAnalysisSection>
+ <ErrorState
+ title="Coverage unavailable"
+ description="The detection service did not answer, so there is nothing to report about your rules."
+ error={error}
+ onRetry={() => {
+ void mutate();
+ }}
+ />
+ </GapAnalysisSection>
+ ) : !summary || summary.techniques === 0 ? (
+ <GapAnalysisSection>
+ <EmptyState
+ icon={EmptyStateIcons.shield}
+ title="No detection rules reference a technique yet"
+ description="Coverage is computed from the rules this tenant has loaded. Add or import rules and their ATT&CK mappings appear here."
+ action={
+ <Link
+ href="/detection"
+ className="rounded-lg bg-gray-800 px-4 py-2 text-sm text-gray-200 hover:bg-gray-700 transition-colors"
>
- {f === 'all' ? 'All' : STATUS_STYLES[f as CoverageStatus].label}
- </button>
- ))}
+ Browse detection rules
+ </Link>
+ }
+ />
+ </GapAnalysisSection>
+ ) : (
+ <>
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
+ <SummaryCard
+ label="Techniques with an enabled rule"
+ value={`${summary.coveredTechniques} / ${summary.techniques}`}
+ />
+ <SummaryCard
+ label="Unenforced techniques"
+ value={`${summary.techniques - summary.coveredTechniques}`}
+ hint="every rule for these is switched off"
+ />
+ <SummaryCard label="Enabled rules" value={summary.activeRules.toLocaleString()} />
+ <SummaryCard
+ label="Disabled rules"
+ value={summary.inactiveRules.toLocaleString()}
+ hint={summary.inactiveRules > 0 ? 'detecting nothing while off' : undefined}
+ />
</div>
- </div>
- <div className="overflow-x-auto">
- <table className="w-full text-sm">
- <thead>
- <tr className="border-b border-gray-800/60 text-left text-gray-400">
- <th className="px-5 py-3 font-medium">Technique</th>
- <th className="px-5 py-3 font-medium">Name</th>
- <th className="px-5 py-3 font-medium">Tactic</th>
- <th className="px-5 py-3 font-medium text-center">Coverage</th>
- <th className="px-5 py-3 font-medium text-center">Priority</th>
- <th className="px-5 py-3 font-medium">Recommendation</th>
- <th className="px-5 py-3 font-medium text-center">Action</th>
- </tr>
- </thead>
- <tbody>
- {filteredTechniques.length === 0 ? (
- <tr>
- <td colSpan={7} className="py-0">
- <EmptyState
- icon={EmptyStateIcons.shield}
- title="No techniques match this filter"
- description="Try selecting a different coverage status or view all techniques."
- action={
- <button
- type="button"
- onClick={() => setStatusFilter('all')}
- className="rounded-lg bg-gray-800 px-4 py-2 text-sm text-gray-200 hover:bg-gray-700 transition-colors"
- >
- Show all techniques
- </button>
- }
- />
- </td>
- </tr>
- ) : (
- filteredTechniques.map((t) => {
- const st = STATUS_STYLES[t.status];
- const pr = PRIORITY_STYLES[t.priority];
- return (
- <tr key={t.id} className="border-b border-gray-800/40 hover:bg-gray-800/30 transition-colors">
- <td className="px-5 py-3 font-mono text-blue-400 text-xs">{t.id}</td>
- <td className="px-5 py-3 text-white">{t.name}</td>
- <td className="px-5 py-3 text-gray-300">{t.tactic}</td>
- <td className="px-5 py-3 text-center">
- <span className={clsx('inline-block px-2.5 py-0.5 rounded-full text-xs font-medium', st.bg, st.text)}>
- {st.label}
- </span>
- </td>
- <td className="px-5 py-3 text-center">
- <span className={clsx('inline-block px-2.5 py-0.5 rounded-full text-xs font-medium capitalize', pr.bg, pr.text)}>
- {t.priority}
- </span>
- </td>
- <td className="px-5 py-3 text-gray-400 max-w-xs truncate">{t.recommendation}</td>
- <td className="px-5 py-3 text-center">
- {t.status !== 'covered' && (
- <button
- onClick={() => toast.success(`Detection rule draft created for ${t.id}`)}
- className="text-xs px-2.5 py-1 rounded-lg bg-blue-600 hover:bg-blue-500 text-white transition-colors whitespace-nowrap"
- >
- Generate Detection
- </button>
- )}
+
+ <p className="text-xs text-gray-500">
+ Scope: this endpoint reports one row per technique at least one of your rules
+ references. Techniques with no rule at all do not appear, so the fraction above is
+ coverage of your own corpus and not of ATT&amp;CK. Generated{' '}
+ {data?.generatedAt ?? 'unknown'}.
+ </p>
+
+ <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 overflow-hidden">
+ <div className="px-5 py-4 border-b border-gray-800/60 flex flex-wrap items-center gap-3">
+ <h2 className="text-lg font-semibold text-white flex-1 min-w-0">Gap analysis</h2>
+ <div className="flex gap-2">
+ {FILTERS.map((f) => (
+ <button
+ key={f.id}
+ onClick={() => setStatusFilter(f.id)}
+ className={clsx(
+ 'text-xs px-3 py-1 rounded-lg border transition-colors',
+ statusFilter === f.id
+ ? 'bg-blue-600/15 text-blue-300 border-blue-600/30'
+ : 'text-gray-400 border-gray-800 hover:border-gray-700',
+ )}
+ aria-pressed={statusFilter === f.id}
+ >
+ {f.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-gray-800/60 text-left text-gray-400">
+ <th className="px-5 py-3 font-medium">Technique</th>
+ <th className="px-5 py-3 font-medium">Tactic</th>
+ <th className="px-5 py-3 font-medium text-center">Enabled rules</th>
+ <th className="px-5 py-3 font-medium text-center">Disabled rules</th>
+ <th className="px-5 py-3 font-medium text-center">Status</th>
+ <th className="px-5 py-3 font-medium">Next step</th>
+ </tr>
+ </thead>
+ <tbody>
+ {visible.length === 0 ? (
+ <tr>
+ <td colSpan={6} className="py-0">
+ <EmptyState
+ icon={EmptyStateIcons.shield}
+ title="No techniques match this filter"
+ description="Try a different coverage status or view all techniques."
+ action={
+ <button
+ type="button"
+ onClick={() => setStatusFilter('all')}
+ className="rounded-lg bg-gray-800 px-4 py-2 text-sm text-gray-200 hover:bg-gray-700 transition-colors"
+ >
+ Show all techniques
+ </button>
+ }
+ />
</td>
</tr>
- );
- })
- )}
- </tbody>
- </table>
- </div>
- </div>
+ ) : (
+ visible.map((cell) => <CoverageRow key={cell.techniqueId} cell={cell} />)
+ )}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
+function GapAnalysisSection({ children }: { children: React.ReactNode }) {
+ return (
+ <section aria-labelledby="coverage-gap-analysis">
+ <h2 id="coverage-gap-analysis" className="sr-only">
+ Gap analysis
+ </h2>
+ {children}
+ </section>
+ );
+}
+
+function SummaryCard({ label, value, hint }: { label: string; value: string; hint?: string }) {
+ return (
+ <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-4">
+ <p className="text-xs text-gray-400 uppercase tracking-wider">{label}</p>
+ <p className="mt-1 text-2xl font-semibold text-white">{value}</p>
+ {hint && <p className="mt-0.5 text-[11px] text-gray-500">{hint}</p>}
</div>
);
}
+
+function CoverageRow({ cell }: { cell: DetectionCoverageCell }) {
+ const status = statusOf(cell);
+ const style = STATUS_STYLES[status];
+
+ return (
+ <tr className="border-b border-gray-800/40 hover:bg-gray-800/30 transition-colors">
+ <td className="px-5 py-3 font-mono text-xs">
+ <a
+ href={`https://attack.mitre.org/techniques/${cell.techniqueId.replace('.', '/')}/`}
+ target="_blank"
+ rel="noreferrer"
+ className="text-blue-400 hover:text-blue-300"
+ >
+ {cell.techniqueId}
+ </a>
+ {cell.techniqueName && <span className="ml-2 text-gray-300">{cell.techniqueName}</span>}
+ </td>
+ <td className="px-5 py-3 text-gray-300">{cell.tactic ?? 'unmapped'}</td>
+ <td className="px-5 py-3 text-center text-gray-200">{cell.activeRules}</td>
+ <td className="px-5 py-3 text-center text-gray-200">{cell.inactiveRules}</td>
+ <td className="px-5 py-3 text-center">
+ <span
+ className={clsx(
+ 'inline-block px-2.5 py-0.5 rounded-full text-xs font-medium',
+ style.bg,
+ style.text,
+ )}
+ >
+ {style.label}
+ </span>
+ </td>
+ <td className="px-5 py-3 text-gray-400">
+ {status === 'unenforced' ? (
+ // A real navigation to the rules that exist and are switched off,
+ // rather than the success toast that used to claim a draft rule had
+ // been created and created nothing.
+ <Link
+ href={`/detection?technique=${encodeURIComponent(cell.techniqueId)}`}
+ className="text-xs text-blue-400 hover:text-blue-300 underline underline-offset-2"
+ >
+ {`Enable one of ${cell.inactiveRules} rule${cell.inactiveRules === 1 ? '' : 's'} disabled`}
+ </Link>
+ ) : (
+ <span className="text-xs text-gray-500">Nothing to do</span>
+ )}
+ </td>
+ </tr>
+ );
+}
diff --git a/apps/web/src/components/dashboard/FunnelKpiBar.tsx b/apps/web/src/components/dashboard/FunnelKpiBar.tsx
index fef03b2f2..c81ec1057 100644
--- a/apps/web/src/components/dashboard/FunnelKpiBar.tsx
+++ b/apps/web/src/components/dashboard/FunnelKpiBar.tsx
@@ -15,8 +15,6 @@
*
* Data source: `GET /api/v1/metrics/funnel?period=…` ({@link metricsApi.getFunnel}).
* Polls every 60 s with stale-while-revalidate.
- *
- * Author: Beenu Arora <[email protected]>
*/
import useSWR from 'swr';
diff --git a/apps/web/src/components/hunt/HuntHonesty.test.tsx b/apps/web/src/components/hunt/HuntHonesty.test.tsx
new file mode 100644
index 000000000..5f08ddbd3
--- /dev/null
+++ b/apps/web/src/components/hunt/HuntHonesty.test.tsx
@@ -0,0 +1,236 @@
+/**
+ * Data-honesty gate for the hunt workspace.
+ *
+ * `HuntView` had no demo gate at all. Its `demoMode` was a local
+ * `useState(false)` flipped by **fetch failure**, so the page fabricated
+ * precisely when the backend was unhealthy — the moment a user is least able
+ * to tell invented telemetry from real telemetry.
+ *
+ * Two fabrications rendered that way: `DEMO_SAVED`, three invented saved
+ * hunts, whenever `listSaved()` failed; and `DEMO_RESULTS`, three detections
+ * on named hosts with encoded-PowerShell command lines and a routable C2 IP,
+ * whenever `search()` failed. The results path also published `took: 42` — a
+ * query latency for a query that never ran, rendered in the same "N hits ·
+ * Nms" line as a real measurement.
+ *
+ * Both paths did disclose, which is better than silence. Disclosure is not
+ * the property under test: fabricated telemetry must not render outside the
+ * hosted demo at all.
+ *
+ * SWR is mocked rather than driven through a rejecting fetcher because the
+ * saved-search key is module-scoped and its error survives `cleanup()`, which
+ * leaks the first test's failure into every later one in this file.
+ */
+
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { __setDemoModeForTests } from '@/lib/demoMode';
+
+const swrData = vi.hoisted(() => new Map<string, unknown>());
+const swrErrors = vi.hoisted(() => new Map<string, unknown>());
+
+vi.mock('swr', () => ({
+ __esModule: true,
+ default: (key: unknown) => {
+ const k = typeof key === 'string' ? key : JSON.stringify(key);
+ return {
+ data: swrData.get(k),
+ error: swrErrors.get(k),
+ isLoading: false,
+ mutate: vi.fn(),
+ };
+ },
+}));
+
+const huntApi = vi.hoisted(() => ({
+ listSaved: vi.fn(),
+ search: vi.fn(),
+ saveSearch: vi.fn(),
+ deleteSaved: vi.fn(),
+}));
+
+const savedHuntsApi = vi.hoisted(() => ({
+ list: vi.fn(),
+ create: vi.fn(),
+ run: vi.fn(),
+ remove: vi.fn(),
+}));
+
+const nlQueryApi = vi.hoisted(() => ({ translate: vi.fn() }));
+
+vi.mock('@/lib/api', () => ({
+ __esModule: true,
+ huntApi,
+ savedHuntsApi,
+ nlQueryApi,
+}));
+
+// Monaco is loaded through `next/dynamic` and needs a real browser.
+vi.mock('next/dynamic', () => ({
+ __esModule: true,
+ default: () => function EditorStub() {
+ return null;
+ },
+}));
+
+import { HuntView } from './HuntView';
+
+const SAVED_SEARCHES_KEY = 'hunt.saved';
+
+/** Every string `DEMO_RESULTS` would put on screen. */
+const FABRICATED_RESULTS = [
+ 'WORKSTATION-042',
+ 'SERVER-DC01',
+ 'WORKSTATION-019',
+ 'svc_admin',
+ '185.220.101.45',
+ 'maria.lin',
+];
+
+/** Every string `DEMO_SAVED` would put on screen. */
+const FABRICATED_SAVED = [
+ 'Encoded PowerShell',
+ 'LSASS access attempts',
+ 'Outbound connections to TOR exits',
+];
+
+function expectNoFabrication(names: string[]) {
+ for (const name of names) {
+ expect(
+ document.body.textContent ?? '',
+ `"${name}" is fabricated telemetry and must not render outside demo mode`,
+ ).not.toContain(name);
+ }
+}
+
+/** Clicking an example pill translates the question and runs the hunt. */
+function runAHunt() {
+ return userEvent.click(
+ screen.getByRole('button', { name: /Did we get any new attacks from Iran\?/i }),
+ );
+}
+
+beforeEach(() => {
+ swrData.clear();
+ swrErrors.clear();
+ huntApi.listSaved.mockReset();
+ huntApi.search.mockReset();
+ savedHuntsApi.list.mockReset().mockResolvedValue([]);
+ nlQueryApi.translate.mockReset().mockResolvedValue({
+ esql: 'FROM events | LIMIT 10',
+ explanation: 'Filters events by source geography.',
+ });
+ __setDemoModeForTests(false);
+});
+
+afterEach(() => {
+ cleanup();
+ __setDemoModeForTests(null);
+});
+
+describe('a failed saved-search load does not invent saved hunts', () => {
+ it('shows the error rather than three hunts nobody saved', () => {
+ swrErrors.set(SAVED_SEARCHES_KEY, new Error('502 Bad Gateway'));
+
+ render(<HuntView />);
+
+ expect(screen.getByText(/Couldn't load saved searches/i)).toBeTruthy();
+ expectNoFabrication(FABRICATED_SAVED);
+ });
+
+ it('reads an empty list as empty', () => {
+ swrData.set(SAVED_SEARCHES_KEY, []);
+
+ render(<HuntView />);
+
+ expect(screen.getByText(/No saved searches yet/i)).toBeTruthy();
+ expectNoFabrication(FABRICATED_SAVED);
+ });
+
+ it('publishes nothing before the request has answered', () => {
+ render(<HuntView />);
+
+ expectNoFabrication(FABRICATED_SAVED);
+ });
+});
+
+describe('a failed hunt does not invent results', () => {
+ it('surfaces the failure instead of three fabricated detections', async () => {
+ huntApi.search.mockRejectedValue(new Error('lake unreachable'));
+
+ render(<HuntView />);
+ await runAHunt();
+
+ await waitFor(() => {
+ expect(huntApi.search).toHaveBeenCalled();
+ });
+ await waitFor(() => {
+ expect(screen.getByText(/lake unreachable/i)).toBeTruthy();
+ });
+ expectNoFabrication(FABRICATED_RESULTS);
+ });
+
+ it('publishes no query latency for a query that never ran', async () => {
+ huntApi.search.mockRejectedValue(new Error('lake unreachable'));
+
+ render(<HuntView />);
+ await runAHunt();
+
+ await waitFor(() => {
+ expect(huntApi.search).toHaveBeenCalled();
+ });
+ // `took: 42` was a fabricated measurement rendered beside a hit count.
+ await waitFor(() => {
+ expect(screen.queryByText(/42ms/)).toBeNull();
+ expect(screen.queryByText(/3 hits/)).toBeNull();
+ });
+ });
+
+ it('renders the real results the backend returned', async () => {
+ huntApi.search.mockResolvedValue({
+ total: 1,
+ took: 7,
+ hits: [
+ {
+ id: 'real-1',
+ timestamp: '2026-05-06T11:48:00Z',
+ source: 'lake',
+ severity: 'low',
+ fields: { host: 'build-agent-3' },
+ },
+ ],
+ });
+
+ render(<HuntView />);
+ await runAHunt();
+
+ await waitFor(() => {
+ expect(screen.getByText(/build-agent-3/)).toBeTruthy();
+ });
+ expectNoFabrication(FABRICATED_RESULTS);
+ });
+});
+
+describe('the hosted demo is still populated', () => {
+ it('shows the sample hunts when the build is the demo', () => {
+ __setDemoModeForTests(true);
+ swrErrors.set(SAVED_SEARCHES_KEY, new Error('no backend in the demo'));
+
+ render(<HuntView />);
+
+ expect(screen.getByText('LSASS access attempts')).toBeTruthy();
+ });
+
+ it('shows the sample results when the build is the demo', async () => {
+ __setDemoModeForTests(true);
+ huntApi.search.mockRejectedValue(new Error('no backend in the demo'));
+
+ render(<HuntView />);
+ await runAHunt();
+
+ await waitFor(() => {
+ expect(screen.getByText(/WORKSTATION-042/)).toBeTruthy();
+ });
+ });
+});
diff --git a/apps/web/src/components/hunt/HuntView.tsx b/apps/web/src/components/hunt/HuntView.tsx
index dee1508f0..1dff8ffb3 100644
--- a/apps/web/src/components/hunt/HuntView.tsx
+++ b/apps/web/src/components/hunt/HuntView.tsx
@@ -43,6 +43,7 @@ import {
import { Skeleton } from '@/components/ui/Skeleton';
import { ErrorState } from '@/components/ui/ErrorState';
import { EmptyState } from '@/components/ui/EmptyState';
+import { demoFallback } from '@/lib/demoFallback';
// Monaco is heavy and SSR-incompatible; load it client-side only.
const MonacoEditor = dynamic(
@@ -635,7 +636,18 @@ export function HuntView() {
const [activeSavedId, setActiveSavedId] = useState<string | null>(null);
const [activeSavedHuntId, setActiveSavedHuntId] = useState<string | null>(null);
const editorRef = useRef<unknown>(null);
- const [demoMode, setDemoMode] = useState(false);
+ /**
+ * Whether the *backend* said these results are illustrative.
+ *
+ * Deliberately not a demo flag. This used to be `demoMode`, a local
+ * `useState(false)` flipped to `true` by a fetch failure, which made the
+ * page substitute invented telemetry precisely when the backend was
+ * unhealthy — the moment a reader is least able to tell. Whether sample
+ * data may render at all is now `canUseDemoData()`, a property of the
+ * build; this only records that a successful response was self-declared
+ * `source: "sample"`.
+ */
+ const [sampleSource, setSampleSource] = useState(false);
// Reason the results are not live, surfaced verbatim from the backend so
// the console never has to guess why it is showing sample data.
const [sampleNotice, setSampleNotice] = useState<string | null>(null);
@@ -655,17 +667,7 @@ export function HuntView() {
const savedState = useSWR<SavedSearch[]>(
'hunt.saved',
- async () => {
- try {
- const res = await huntApi.listSaved();
- return res.searches;
- } catch (err) {
- // First-load fallback to demo so the UI is never empty.
- setDemoMode(true);
- setSampleNotice('Saved searches could not be loaded from the backend.');
- throw err;
- }
- },
+ async () => (await huntApi.listSaved()).searches,
{
revalidateOnFocus: false,
shouldRetryOnError: false,
@@ -681,12 +683,12 @@ export function HuntView() {
},
);
- // If saved-search fetch failed, transparently substitute demo list so the UI
- // is usable.
- const savedItems: SavedSearch[] =
- savedState.data ?? (demoMode ? DEMO_SAVED : []);
- const savedError =
- savedState.error && !demoMode ? savedState.error : undefined;
+ // The hosted demo has no backend, so it substitutes a sample list. Every
+ // other deployment shows the error: three saved hunts nobody saved are
+ // indistinguishable from three the tenant did save.
+ const sampleSaved = demoFallback(DEMO_SAVED);
+ const savedItems: SavedSearch[] = savedState.data ?? sampleSaved ?? [];
+ const savedError = sampleSaved ? undefined : savedState.error;
const savedHuntsItems: SavedHunt[] = savedHuntsState.data ?? [];
const savedHuntsError = savedHuntsState.error;
@@ -732,16 +734,15 @@ export function HuntView() {
setNlExplanation(explanation || null);
} catch (err) {
console.error('NL translate failed', err);
- toast.error('Could not translate the question — using demo results');
+ toast.error('Could not translate the question');
setNlSubmittedQuery(cleaned);
setNlExplanation(null);
} finally {
setNlPending(false);
}
- // Run the hunt regardless of translate outcome — falls back to demo
- // results internally, which is still useful UX (see component
- // docstring).
+ // Run the hunt regardless of translate outcome: the editor holds
+ // whatever the translator managed, and a failed run reports itself.
void runHunt({
languageOverride: 'esql',
queryOverride: translatedEsql || query,
@@ -777,24 +778,31 @@ export function HuntView() {
// generates illustrative events rather than querying the lake, and says
// so with `source: "sample"` — trusting the status code alone is how a
// green "Live backend" pill ended up sitting over fabricated telemetry.
- setDemoMode(
+ setSampleSource(
(res as { source?: string }).source === 'sample' ||
Boolean((res as { notice?: string }).notice),
);
setSampleNotice((res as { notice?: string }).notice ?? null);
} catch (err) {
- // Demo fallback so the page still feels alive without a seeded backend.
- setResults({
- total: DEMO_RESULTS.length,
- took: 42,
- hits: DEMO_RESULTS,
- });
- setDemoMode(true);
- setSampleNotice(
- 'The hunt backend is unreachable, so these are illustrative sample events rather than results from your telemetry.',
- );
setRunError(err);
- toast('Backend unreachable — showing sample results');
+ const sample = demoFallback(DEMO_RESULTS);
+ if (sample) {
+ // The hosted demo has no lake to query.
+ setResults({ total: sample.length, took: 0, hits: sample });
+ setSampleSource(true);
+ setSampleNotice(
+ 'The hunt backend is unreachable, so these are illustrative sample events rather than results from your telemetry.',
+ );
+ return;
+ }
+ // Everywhere else a failed hunt reads as a failed hunt. The old branch
+ // published three detections on named hosts plus `took: 42` — a query
+ // latency for a query that never ran, rendered in the same line as a
+ // real measurement.
+ setResults(null);
+ setSampleSource(false);
+ setSampleNotice(null);
+ toast.error('Hunt failed — no results to show');
} finally {
setRunning(false);
}
@@ -954,7 +962,7 @@ export function HuntView() {
<span
className={clsx(
'inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 ring-1',
- demoMode
+ sampleSource
? 'bg-amber-500/10 text-amber-300 ring-amber-500/30'
: 'bg-emerald-500/10 text-emerald-300 ring-emerald-500/30',
)}
@@ -962,12 +970,12 @@ export function HuntView() {
<span
className={clsx(
'h-1.5 w-1.5 rounded-full',
- demoMode ? 'bg-amber-400' : 'bg-emerald-400 animate-ping-slow',
+ sampleSource ? 'bg-amber-400' : 'bg-emerald-400 animate-ping-slow',
)}
/>
- {demoMode ? 'Sample data' : 'Live backend'}
+ {sampleSource ? 'Sample data' : 'Live backend'}
</span>
- {demoMode && sampleNotice && (
+ {sampleSource && sampleNotice && (
<p className="mt-1 text-[11px] leading-snug text-amber-300/80">{sampleNotice}</p>
)}
</div>
@@ -1172,6 +1180,16 @@ export function HuntView() {
<Skeleton className="h-12 w-full rounded-lg" />
<Skeleton className="h-12 w-full rounded-lg" />
</div>
+ ) : runError && !results ? (
+ // A hunt that did not run has no result, empty or otherwise.
+ // Reporting it as "no matches" would read as a clean estate.
+ <ErrorState
+ title="Hunt failed"
+ description="The query was not executed, so nothing here describes your telemetry."
+ error={runError}
+ onRetry={handleRun}
+ className="m-4"
+ />
) : !results ? (
<EmptyState
title="Press Run to begin"
@@ -1183,11 +1201,9 @@ export function HuntView() {
No matches in the selected window
</p>
<p className="mt-1 text-xs text-slate-500">
- {runError
- ? 'Backend unreachable — but here is the parsed query so you can refine it.'
- : nlSubmittedQuery
- ? 'The translator parsed your question (see editor) but found no events. Try a wider time range.'
- : 'Either the data is clean, or the query is too tight.'}
+ {nlSubmittedQuery
+ ? 'The translator parsed your question (see editor) but found no events. Try a wider time range.'
+ : 'Either the data is clean, or the query is too tight.'}
</p>
</div>
) : (
diff --git a/apps/web/src/components/sla/SLADashboard.tsx b/apps/web/src/components/sla/SLADashboard.tsx
index 1fec60941..29f08c14e 100644
--- a/apps/web/src/components/sla/SLADashboard.tsx
+++ b/apps/web/src/components/sla/SLADashboard.tsx
@@ -438,7 +438,7 @@ export function SLADashboard() {
const [editConfig, setEditConfig] = useState<SLAConfig | null>(null);
const [editKpiTargets, setEditKpiTargets] = useState<KpiBarTargets | null>(null);
- const { data: rawMetrics, error: metricsError } = useSWR<SLAMetrics>(
+ const { data: rawMetrics, error: metricsError, mutate: refetchMetrics } = useSWR<SLAMetrics>(
`/api/v1/sla/metrics?days=${days}`,
fetcher,
{
@@ -454,7 +454,12 @@ export function SLADashboard() {
rawMetrics &&
typeof rawMetrics.overall?.total_alerts === 'number' &&
typeof rawMetrics.per_severity === 'object';
- const metrics = isValidMetrics ? rawMetrics : MOCK_SLA_METRICS;
+ // `fallbackData` above is already gated, and this is where that gate used
+ // to be thrown away: `isValidMetrics ? rawMetrics : MOCK_SLA_METRICS`.
+ // Outside the hosted demo `demoFallback` returns `undefined`, so the test
+ // is falsy on first paint as much as on error — and 847 alerts, 23 breaches
+ // and a 42.5m MTTR rendered in both, on every deployment, identically.
+ const metrics = isValidMetrics ? rawMetrics : undefined;
const { data: configs } = useSWR<SLAConfig[]>('/api/v1/sla/config', fetcher, {
fallbackData: demoFallback(MOCK_SLA_CONFIGS),
@@ -481,6 +486,7 @@ export function SLADashboard() {
<select
value={days}
onChange={(e) => setDays(Number(e.target.value))}
+ aria-label="Reporting period"
className="bg-gray-800 border border-gray-600 text-white text-sm rounded px-3 py-1.5"
>
{[7, 14, 30, 60, 90].map((d) => (
@@ -491,9 +497,32 @@ export function SLADashboard() {
</select>
</div>
- {metricsError && (
- <div className="rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-2 text-xs text-amber-200">
- SLA API unreachable — showing demo metrics so you can explore the dashboard.
+ {!metrics && (
+ <div
+ role="alert"
+ className="rounded-md border border-gray-700 bg-gray-900/40 px-4 py-3 text-sm text-gray-300"
+ >
+ <h2 className="font-medium text-gray-200">
+ {metricsError ? 'SLA metrics unavailable' : 'SLA metrics not measured yet'}
+ </h2>
+ <p className="mt-1 text-xs text-gray-400">
+ {metricsError
+ ? 'The SLA service did not answer, so there is nothing to report for this period.'
+ : 'Waiting for the SLA service. Figures appear once it answers.'}
+ </p>
+ {metricsError != null && (
+ <>
+ <pre className="mt-2 overflow-x-auto rounded bg-black/30 px-2 py-1 font-mono text-xs text-gray-400">
+ {metricsError instanceof Error ? metricsError.message : String(metricsError)}
+ </pre>
+ <button
+ onClick={() => void refetchMetrics()}
+ className="mt-3 rounded border border-gray-600 px-3 py-1 text-xs text-gray-200 hover:bg-gray-800"
+ >
+ Retry
+ </button>
+ </>
+ )}
</div>
)}
diff --git a/apps/web/src/components/sla/SLAHonesty.test.tsx b/apps/web/src/components/sla/SLAHonesty.test.tsx
new file mode 100644
index 000000000..75a78e855
--- /dev/null
+++ b/apps/web/src/components/sla/SLAHonesty.test.tsx
@@ -0,0 +1,204 @@
+/**
+ * Data-honesty gate for the SLA dashboard.
+ *
+ * `fallbackData: demoFallback(MOCK_SLA_METRICS)` was correct. One line later
+ * `const metrics = isValidMetrics ? rawMetrics : MOCK_SLA_METRICS` threw the
+ * gate away: outside the hosted demo `demoFallback` returns `undefined`, so
+ * `isValidMetrics` is falsy on **first paint as well as on error**, and the
+ * fabricated set rendered in both — 847 alerts, 23 breaches, a 2.7% breach
+ * rate and a 42.5m MTTR, identical on every deployment.
+ *
+ * The disclosure banner was wired to `metricsError` alone, so during the
+ * loading window the invented numbers appeared with nothing saying so. That
+ * is why the first-paint case below is the load-bearing one: an error-only
+ * test passes against the broken component.
+ */
+
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+import { cleanup, render, screen } from '@testing-library/react';
+import { axe } from 'vitest-axe';
+import { __setDemoModeForTests } from '@/lib/demoMode';
+
+const swrData = vi.hoisted(() => new Map<string, unknown>());
+const swrErrors = vi.hoisted(() => new Map<string, unknown>());
+
+vi.mock('swr', () => ({
+ __esModule: true,
+ default: (key: unknown) => {
+ const k = typeof key === 'string' ? key : JSON.stringify(key);
+ return {
+ data: swrData.get(k),
+ error: swrErrors.get(k),
+ isLoading: false,
+ mutate: vi.fn(),
+ };
+ },
+ mutate: vi.fn(),
+}));
+
+import { SLADashboard } from './SLADashboard';
+
+const METRICS_KEY = '/api/v1/sla/metrics?days=30';
+
+/** Every figure `MOCK_SLA_METRICS` would put on screen. */
+const FABRICATED_FIGURES = ['847', '23', '2.7%', '42.5m', '186', '312', '307'];
+
+function expectNoFabricatedFigures() {
+ for (const figure of FABRICATED_FIGURES) {
+ expect(
+ screen.queryAllByText(figure),
+ `"${figure}" comes from MOCK_SLA_METRICS and must not render outside demo mode`,
+ ).toHaveLength(0);
+ }
+}
+
+beforeEach(() => {
+ swrData.clear();
+ swrErrors.clear();
+ __setDemoModeForTests(false);
+});
+
+afterEach(() => {
+ cleanup();
+ __setDemoModeForTests(null);
+});
+
+describe('SLADashboard — first paint', () => {
+ /**
+ * The state the error-only test cannot see. No data and no error is what
+ * every non-demo deployment renders for the duration of the first request,
+ * and SWR's `fallbackData` is `undefined` there, so the ternary reached
+ * straight past it into the mock.
+ */
+ it('publishes no SLA figures before the API has answered', () => {
+ render(<SLADashboard />);
+
+ expectNoFabricatedFigures();
+ });
+
+ it('says the metrics have not loaded rather than showing a number', () => {
+ render(<SLADashboard />);
+
+ expect(screen.getByText(/not measured|no SLA data|loading/i)).toBeTruthy();
+ });
+});
+
+describe('SLADashboard — API failure', () => {
+ it('names the failure instead of substituting a baseline', () => {
+ swrErrors.set(METRICS_KEY, new Error('HTTP 503'));
+
+ render(<SLADashboard />);
+
+ expectNoFabricatedFigures();
+ expect(screen.getByText(/HTTP 503/i)).toBeTruthy();
+ });
+
+ it('does not describe fabricated numbers as something to explore', () => {
+ swrErrors.set(METRICS_KEY, new Error('HTTP 500'));
+
+ render(<SLADashboard />);
+
+ // The old banner read "showing demo metrics so you can explore the
+ // dashboard" on a deployment that is not the demo.
+ expect(screen.queryByText(/showing demo metrics/i)).toBeNull();
+ });
+});
+
+describe('SLADashboard — real data', () => {
+ it('renders the tenant figures the API returned', () => {
+ swrData.set(METRICS_KEY, {
+ period_days: 30,
+ computed_at: '2026-05-06T12:00:00Z',
+ overall: {
+ total_alerts: 6,
+ total_breaches: 1,
+ breach_rate: 16.7,
+ mttd_avg: 3.0,
+ mttr_avg: 9.0,
+ mttc_avg: 12.0,
+ },
+ per_severity: {
+ high: {
+ total: 6,
+ breaches: 1,
+ breach_rate: 16.7,
+ mttd_avg: 3.0,
+ mttr_avg: 9.0,
+ mttc_avg: 12.0,
+ mttd_target: 30,
+ mttr_target: 60,
+ mttc_target: 120,
+ },
+ },
+ kpi_bar: null,
+ });
+
+ render(<SLADashboard />);
+
+ expect(screen.getByText('6')).toBeTruthy();
+ expect(screen.getByText('16.7%')).toBeTruthy();
+ expectNoFabricatedFigures();
+ });
+
+ it('reads an empty tenant as empty, not as 847 alerts', () => {
+ swrData.set(METRICS_KEY, {
+ period_days: 30,
+ computed_at: '2026-05-06T12:00:00Z',
+ overall: {
+ total_alerts: 0,
+ total_breaches: 0,
+ breach_rate: 0,
+ mttd_avg: null,
+ mttr_avg: null,
+ mttc_avg: null,
+ },
+ per_severity: {},
+ kpi_bar: null,
+ });
+
+ render(<SLADashboard />);
+
+ expectNoFabricatedFigures();
+ });
+});
+
+describe('SLADashboard — accessibility', () => {
+ // The unavailable/not-measured block is new and sits between the page `h1`
+ // and the per-severity `h2`s, which is exactly where a heading-order
+ // violation appears under the repo's axe gate.
+ it('has no violations while the metrics are unavailable', async () => {
+ swrErrors.set(METRICS_KEY, new Error('HTTP 503'));
+
+ const { container } = render(<SLADashboard />);
+
+ expect(
+ await axe(container, { rules: { 'color-contrast': { enabled: false } } }),
+ ).toHaveNoViolations();
+ });
+});
+
+describe('SLADashboard — hosted demo', () => {
+ it('is still populated when the build is the demo', () => {
+ __setDemoModeForTests(true);
+ // In demo mode `demoFallback` hands the mock to SWR as `fallbackData`,
+ // which the mock above models by seeding the same cache key.
+ swrData.set(METRICS_KEY, {
+ period_days: 30,
+ computed_at: '2026-05-06T12:00:00Z',
+ overall: {
+ total_alerts: 847,
+ total_breaches: 23,
+ breach_rate: 2.7,
+ mttd_avg: 24.4,
+ mttr_avg: 42.5,
+ mttc_avg: 112.0,
+ },
+ per_severity: {},
+ kpi_bar: null,
+ });
+
+ render(<SLADashboard />);
+
+ expect(screen.getByText('847')).toBeTruthy();
+ });
+});
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 62250ae4c..77cafe7ce 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -86,6 +86,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Analysts can hunt the events AiSOC itself ingested | README (hunt surface) | `ci.yml :: api tests` (`test_lake_hunt.py` — the translator IR compiles to parameterised ClickHouse SQL with the tenant predicate generated rather than rewritten in; no question text reaches the SQL string) | GATED | - |
| Business-context rules authored in the console affect triage | `apps/docs/docs/console/` (business context) | `ci.yml` agents tests (`test_business_context_per_tenant.py` — rules resolve per tenant from Postgres, one tenant's suppression cannot affect another, and an outage serves last-known rules rather than silently un-suppressing) | GATED | - |
| Seeded sample data never renders as a tenant's real state | Standing honesty rule (synthetic vs real) | `ci.yml :: python-lint` (`check_mock_data_gated.py` — fails the build on a `fallbackData` receiving sample data un-wrapped, on sample data assigned to state with no demo-mode check, and on a module-scope array of named entities carrying measurements in a component with no demo gate; the reviewed-exception list is checked in both directions so a stale exemption fails) + `tests/test_mock_data_gate.py` | GATED | the first two patterns needed a `MOCK_`/`DEMO_` name *and* a setter or `fallbackData`, so a fabricated table written inline under an ordinary name in a component that never fetched matched nothing — `MSSPDashboardView` and `TeamAnalyticsView` both shipped under a green gate until the third pattern was added; the check remains shape-based and cannot prove a view is honest |
+| No fabricated value is reachable, and no component decides for itself that it is a demo | Standing honesty rule (synthetic vs real) | `ci.yml :: python-lint` (`check_demo_state_gated.py` — every read of a fabricated symbol must have a gate *in scope*, so a ternary, a factory call, or a constant assembled out of a mock all fail; and a `demoMode`-style local `useState` fails outright) + `tests/test_demo_state_gate.py` | GATED | the shape gate above accepts a file that mentions `demoFallback` anywhere — `SLADashboard.tsx` had it on line 446 and an ungated `isValidMetrics ? rawMetrics : MOCK_SLA_METRICS` on line 457, so 847 alerts and a 42.5m MTTR rendered on first paint and on error; this gate is scope-based rather than shape-based but still cannot prove a view is honest |
| Published executable-detection count matches what the engine loads | `docs/detections/truth-table.md` | `validate-detections.yml` (`detection_truth_table.py --check` now derives `executable` from `detection_ruleset.json` membership rather than file path and body keys; the old heuristic published 947 while the engine loaded 825, counted 77 Sigma rules with no evaluator, and would have certified a bulk un-quarantine as a no-op) | GATED | - |
| A detection rule matches on fields that exist in telemetry | (implied by the detection corpus) | `validate-detections.yml` (`check_detection_fields.py` — ratchets rules depending on computed fields such as sliding-window counters and allowlist booleans, which no connector can supply; fixture replay cannot catch these because fixtures are synthesized from the rule under test) | GATED (ratchet) | ratchet to 0 |
| Vendor fields nested under `raw_event` are visible to detections | (implied by the detection corpus) | `ci.yml` fusion tests (`test_detection_field_namespace.py` — 663 of 825 loaded rules referenced an invisible field before this; both the stateless and windowed engines now merge the payload identically) | GATED | - |
@@ -153,7 +154,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- GATED: 134
+- GATED: 135
- PARTIAL: 8
- NO GATE: 0 (**every claim is backed by a failing test.** 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 remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)
diff --git a/scripts/check_demo_state_gated.py b/scripts/check_demo_state_gated.py
new file mode 100644
index 000000000..4cd67ecb6
--- /dev/null
+++ b/scripts/check_demo_state_gated.py
@@ -0,0 +1,480 @@
+#!/usr/bin/env python3
+"""CI gate: one demo gate, and nothing fabricated reachable without it.
+
+`scripts/check_mock_data_gated.py` recognises the *shapes* that carried
+fabricated security data into the console: a bare mock handed to SWR's
+``fallbackData``, a mock assigned through a state setter, a mock reached
+through ``??``/``||``. Every one of those is a specific syntax, and each was
+added after a specific escape. This gate asks the two questions that do not
+depend on guessing which syntax comes next.
+
+**Is the fabricated value reachable at all?**
+ ``SLADashboard.tsx`` passed ``fallbackData: demoFallback(MOCK_SLA_METRICS)``
+ — correct, and the shape gate accepted it — then wrote
+ ``const metrics = isValidMetrics ? rawMetrics : MOCK_SLA_METRICS`` one line
+ later. A ternary is not a ``??``, so nothing matched. Outside the hosted
+ demo ``demoFallback`` returns ``undefined``, which makes ``isValidMetrics``
+ falsy on **first paint as well as on error**, so 847 alerts, 23 breaches
+ and a 42.5-minute MTTR rendered in both states on every deployment.
+
+ So this gate enumerates no syntax. It takes every *read* of a fabricated
+ symbol and asks whether a gate is in scope at that point. ``cond ? x :
+ MOCK`` fails, and so does whatever is written in its place next.
+
+**Does the component decide for itself that it is in demo mode?**
+ ``HuntView.tsx`` held ``const [demoMode, setDemoMode] = useState(false)``
+ and flipped it to ``true`` inside a fetch ``catch``. Demo mode is a
+ property of the *deployment*, so a component that derives it from a failed
+ request fabricates precisely when the backend is unhealthy — which is when
+ a reader is least equipped to notice, and when an operator most needs to
+ know the estate is not being observed. Disclosure copy does not fix it:
+ the same words would appear if the data were real.
+
+ ``NEXT_PUBLIC_DEMO_MODE``, read through ``lib/demoMode.ts``, is the only
+ thing allowed to answer that question.
+
+What counts as a fabricated symbol
+----------------------------------
+Three kinds, because the first alone is trivially side-stepped:
+
+* a constant named by the convention — ``MOCK_*`` / ``DEMO_*`` / ``SAMPLE_*``
+ / ``FALLBACK_*``;
+* a *factory* that builds one — ``buildDemoCase()``, ``makeMockRows()``. The
+ constant check cannot see these: ``CaseWorkspace`` called
+ ``buildDemoCase(caseId)`` and the id came from the route param, so the
+ invention presented as the case the analyst had opened;
+* anything whose own initializer reads one of the above. ``EASMView``
+ declared ``const SUMMARY = { totalAssets: MOCK_ASSETS.length, … }``, which
+ carries the fabrication under a name the convention does not cover.
+
+What counts as a gate being in scope
+------------------------------------
+Gating is not always on the line that reads. All four of these are real and
+correct in this tree, so a per-line check would reject working code and be
+switched off within a week:
+
+* the read's own statement, expanded by bracket balance, so a value handed to
+ a multi-line ``demoFallback({ … })`` is seen as gated;
+* an enclosing block whose condition mentions the gate —
+ ``if (canUseDemoData()) { setRules(MOCK_RULES); }``;
+* an early-return guard in the same block — ``if (!canUseDemoData()) return
+ [];`` followed later by the read, which is how ``LiveFeedPanel`` does it;
+* a local whose initializer mentions the gate, then used at the read —
+ ``const useFallback = !!error && canUseDemoData()``.
+
+What it does *not* accept is a bare mention of the gate somewhere else in the
+file, which is the hole in the older checks: ``SLADashboard`` had
+``demoFallback`` on line 446 and the ungated ternary on line 457.
+
+Deliberately narrow in one direction: it says nothing about whether a view is
+*honest*, only that these two ways of losing the gate cannot reappear.
+
+Usage:
+ python scripts/check_demo_state_gated.py [--root apps/web/src]
+"""
+
+from __future__ import annotations
+
+import argparse
+import pathlib
+import re
+import sys
+
+# `scripts/` is on sys.path when this file is run as a program, but not when a
+# test loads it by path with importlib. gate_toolkit sits beside it either way.
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
+
+from gate_toolkit import self_test_if_requested
+
+self_test_if_requested(__file__)
+
+#: The naming convention a fabricated constant follows in this tree.
+MOCK_NAME = re.compile(r"\b((?:MOCK|DEMO|SAMPLE|FALLBACK)_[A-Z0-9_]+)\b")
+
+#: A factory that builds fabricated data. The constant convention cannot see
+#: these, and they are how the worst instance in this tree was written:
+#: `buildDemoCase(caseId)` took its id from the route param, so the invented
+#: incident presented as the case the analyst had actually opened.
+FACTORY_NAME = re.compile(
+ r"\b(?:(?:build|make|get|create|generate)(?:Mock|Demo|Sample|Fake|Fallback)[A-Za-z0-9_]*"
+ r"|(?:demo|mock|sample|fake|fallback)[A-Z][A-Za-z0-9_]*)\b"
+)
+
+#: The single gate. `demoFallback()` withholds a value outside the hosted
+#: demo; `canUseDemoData()` / `isDemoMode()` answer the same question for
+#: imperative paths.
+GATE = re.compile(r"\b(?:demoFallback|canUseDemoData|isDemoMode)\b")
+
+#: `const NAME = …` / `function name(` — the start of a definition.
+CONST_DECL = re.compile(r"^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]*)?=")
+FUNC_DECL = re.compile(r"^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*[(<]")
+
+#: `const [demoMode, setDemoMode] = useState(…)`. Matched on the *declared*
+#: name so `sampleNotice` — a disclosure string, not a mode — stays in scope
+#: for authors who want one.
+LOCAL_DEMO_STATE = re.compile(
+ r"const\s*\[\s*(demo|demoMode|isDemo|isDemoMode|useDemo|usingDemoData|usingMockData|mockMode|sampleMode|isSample|fallbackMode)\s*,\s*\w+\s*\]\s*=\s*useState",
+)
+
+#: Files exempt by nature: the gate helpers themselves, tests, and stories.
+#: A test *must* be able to name a fabricated constant — that is how it proves
+#: the constant does not render.
+EXEMPT_SUFFIXES = (
+ ".test.ts",
+ ".test.tsx",
+ ".spec.ts",
+ ".spec.tsx",
+ ".stories.tsx",
+ "demoFallback.ts",
+ "demoMode.ts",
+)
+
+#: Constants whose name matches the convention but whose value is editor
+#: placeholder text or an input default, not data presented as tenant state.
+#: Mirrors the list in `check_mock_data_gated.py`; kept separate rather than
+#: imported because that file belongs to a different gate and the two must
+#: stay free to diverge.
+EXEMPT_NAMES = frozenset(
+ """SAMPLE_BODIES SAMPLE_EVENT SAMPLE_SIGMA SAMPLE_KQL SAMPLE_EQL SAMPLE_SPL SAMPLE_ESQL
+ SAMPLE_YAML SAMPLE_QUERY SAMPLE_RULE DEMO_EMAIL DEMO_PASSWORD DEMO_PROVIDERS DEMO_RESULT""".split()
+)
+
+#: Sample data reachable without a gate, each with the reason it is not fixed.
+#:
+#: A ratchet, not an amnesty. Entries are checked in *both* directions: one
+#: that stops matching fails the run, so an exemption cannot outlive the code
+#: it excused and become cover for whatever is written next under that name.
+#: The list may only shrink.
+#:
+#: Empty on purpose. The gate was written alongside the change that closed the
+#: last seven sites, and an allow-list seeded at birth is a gate that has
+#: never been true. Anything added here has to carry a reason a reviewer can
+#: check, and a reason that is "this one is hard" belongs in an issue instead.
+KNOWN_UNGATED: dict[tuple[str, str], str] = {}
+
+
+def _is_comment(line: str) -> bool:
+ return line.lstrip().startswith(("*", "//", "/*", "*/"))
+
+
+def _strip_comment(line: str) -> str:
+ """Drop a trailing `//` comment so prose cannot supply or hide a token."""
+ cut = line.find("//")
+ return line if cut < 0 else line[:cut]
+
+
+def _definition_ranges(lines: list[str]) -> list[tuple[int, int, str]]:
+ """Line spans of every top-level ``const``/``function`` definition.
+
+ Returned as ``(start, end, name)`` with inclusive bounds. Used for two
+ things: a read inside a fabricated definition is part of that definition
+ rather than a render of it, and a definition that reads a fabricated
+ symbol becomes fabricated itself.
+ """
+ spans: list[tuple[int, int, str]] = []
+ index = 0
+ while index < len(lines):
+ line = _strip_comment(lines[index])
+ match = CONST_DECL.match(line) or FUNC_DECL.match(line)
+ if not match:
+ index += 1
+ continue
+
+ depth = 0
+ end = index
+ for cursor in range(index, len(lines)):
+ body = _strip_comment(lines[cursor])
+ depth += sum(body.count(c) for c in "([{") - sum(body.count(c) for c in ")]}")
+ end = cursor
+ if cursor > index or depth <= 0:
+ if depth <= 0:
+ break
+ spans.append((index, end, match.group(1)))
+ index = end + 1
+ return spans
+
+
+def fabricated_symbols(lines: list[str]) -> tuple[set[str], list[tuple[int, int]]]:
+ """Names that carry fabricated data in this file, and where they are defined.
+
+ Resolved to a fixed point so a constant assembled out of another one — the
+ shape that put ``EASMView``'s headline counts beyond the naming convention
+ — is itself treated as fabricated.
+ """
+ spans = _definition_ranges(lines)
+
+ # A *data* declaration: `const NAME … = [` or `= {`. The distinction is
+ # what separates a fabricated record set from a scalar helper —
+ # `const MOCK_BASE = new Date('2026-05-06').getTime()` is a deterministic
+ # timestamp anchor that keeps the mocks from drifting across SSR, not a
+ # named entity with measurements attached, and flagging it teaches authors
+ # that the gate cries wolf.
+ literal = {name for start, _e, name in spans if re.search(r"=\s*[\[{]\s*$", _strip_comment(lines[start]))}
+
+ #: Declarations that hold a value rather than behaviour. A component or a
+ #: helper that *renders* a correctly-gated mock is not itself fabricated,
+ #: and promoting it would flag its own definition line as a read of itself.
+ holds_data = {
+ name
+ for start, _e, name in spans
+ if CONST_DECL.match(_strip_comment(lines[start])) and "=>" not in _strip_comment(lines[start]).split("=", 1)[-1]
+ }
+
+ names = {
+ name
+ for _s, _e, name in spans
+ if name not in EXEMPT_NAMES and (FACTORY_NAME.fullmatch(name) or (MOCK_NAME.fullmatch(name) and name in literal))
+ }
+
+ changed = True
+ while changed:
+ changed = False
+ for start, end, name in spans:
+ if name in names or name in EXEMPT_NAMES or name not in holds_data:
+ continue
+ body = "\n".join(_strip_comment(line) for line in lines[start : end + 1])
+ if any(re.search(rf"\b{re.escape(known)}\b", body) for known in names):
+ names.add(name)
+ changed = True
+
+ ranges = [(s, e) for s, e, name in spans if name in names]
+ return names, ranges
+
+
+def _statement_around(lines: list[str], index: int) -> str:
+ """The bracket-balanced statement containing line ``index``.
+
+ A read can sit several lines below the call that gates it::
+
+ fallbackData: demoFallback({
+ alerts: MOCK_ALERTS,
+ }),
+
+ so judging the matched line alone rejects correct code. Expanding by
+ bracket balance rather than by a fixed window of neighbours is what keeps
+ the opposite error out: an unrelated ``canUseDemoData()`` three lines above
+ must not launder an ungated read below it.
+ """
+ start = index
+ depth = 0
+ while start > 0:
+ body = _strip_comment(lines[start])
+ depth += sum(body.count(c) for c in ")]}") - sum(body.count(c) for c in "([{")
+ if depth <= 0 and (not lines[start - 1].strip() or _strip_comment(lines[start - 1]).rstrip().endswith((";", "{", "}"))):
+ break
+ start -= 1
+
+ end = index
+ depth = 0
+ while end < len(lines) - 1:
+ body = _strip_comment(lines[end])
+ depth += sum(body.count(c) for c in "([{") - sum(body.count(c) for c in ")]}")
+ if depth <= 0 and body.rstrip().endswith((";", ",", "{", "}")):
+ break
+ end += 1
+
+ return "\n".join(lines[start : end + 1])
+
+
+def _guarded_definitions(lines: list[str]) -> list[tuple[int, int]]:
+ """Spans of definitions that return early unless the build is the demo.
+
+ ``EASMView`` and ``ShiftsView`` open with ``if (!canUseDemoData()) return
+ <NotYetWired …>``. Nothing in such a function reaches the DOM on a
+ non-demo build — including a ``useState(MOCK_ITEMS)`` initializer above
+ the guard, which produces no output at all. The guard has to be
+ unconditional to count, so it is only recognised at the top level of the
+ function body rather than nested inside another branch.
+ """
+ guard = re.compile(r"if\s*\(\s*!\s*(?:canUseDemoData|isDemoMode)\s*\(")
+ guarded: list[tuple[int, int]] = []
+
+ for start, end, _name in _definition_ranges(lines):
+ depth = 0
+ for cursor in range(start, end + 1):
+ body = _strip_comment(lines[cursor])
+ if depth == 1 and guard.search(body):
+ block = "\n".join(_strip_comment(line) for line in lines[cursor : min(cursor + 12, end + 1)])
+ if "return" in block:
+ guarded.append((start, end))
+ break
+ depth += body.count("{") - body.count("}")
+ return guarded
+
+
+def _gate_in_scope(lines: list[str], index: int, gated_locals: set[str]) -> bool:
+ """Whether a demo gate governs line ``index``.
+
+ Walks outward from the read: its own statement, then each enclosing block,
+ looking for the gate itself or a local derived from it. Also accepts an
+ early-return guard (``if (!canUseDemoData()) return …``) seen earlier at
+ the read's own depth, which is how a ``useMemo`` body is gated.
+ """
+ tokens = re.compile(rf"\b(?:demoFallback|canUseDemoData|isDemoMode{''.join('|' + re.escape(n) for n in gated_locals)})\b")
+
+ if tokens.search(_statement_around(lines, index)):
+ return True
+
+ # Walk backwards tracking depth relative to the read. A line that leaves
+ # the read's depth negative opened a block the read sits inside; a span
+ # that dips above zero and returns is a *sibling* block the read follows.
+ guard = re.compile(r"if\s*\(\s*!\s*(?:canUseDemoData|isDemoMode)\s*\(")
+ depth = 0
+ sibling: list[str] = []
+ for cursor in range(index - 1, -1, -1):
+ if _is_comment(lines[cursor]):
+ continue
+ body = _strip_comment(lines[cursor])
+ opens = sum(body.count(c) for c in "([{")
+ closes = sum(body.count(c) for c in ")]}")
+
+ if depth == 0 and guard.search(body) and "return" in body:
+ return True
+
+ depth += closes - opens
+ if depth > 0:
+ sibling.append(body)
+ continue
+ if depth < 0:
+ # `cursor` opened an enclosing block; its condition is in scope.
+ if tokens.search(body):
+ return True
+ depth = 0
+ sibling.clear()
+ continue
+ # Back at the read's own depth: `cursor` opened a sibling block. An
+ # `if (!canUseDemoData()) { return … }` above the read returns before
+ # anything below it renders, which is how `EASMView` and `ShiftsView`
+ # withhold their sample inventories.
+ if sibling and guard.search(body) and any("return" in line for line in sibling):
+ return True
+ sibling.clear()
+ return False
+
+
+def _gated_locals(lines: list[str]) -> set[str]:
+ """Locals whose initializer consults the gate, e.g. ``useFallback``."""
+ found: set[str] = set()
+ for line in lines:
+ body = _strip_comment(line)
+ match = CONST_DECL.match(body.strip())
+ if match and GATE.search(body):
+ found.add(match.group(1))
+ return found
+
+
+def _ratchet_key(rel: str, name: str) -> tuple[str, str] | None:
+ for (suffix, const), _reason in KNOWN_UNGATED.items():
+ if rel.endswith(suffix) and const == name:
+ return (suffix, const)
+ return None
+
+
+def findings(root: pathlib.Path) -> tuple[list[str], set[tuple[str, str]]]:
+ """Every ungated read and every self-declared demo mode, plus what matched."""
+ problems: list[str] = []
+ matched: set[tuple[str, str]] = set()
+
+ for path in sorted(root.rglob("*.ts*")):
+ if path.name.endswith(EXEMPT_SUFFIXES):
+ continue
+ lines = path.read_text(encoding="utf-8", errors="replace").split("\n")
+ rel = str(path.relative_to(root.parent.parent.parent))
+
+ names, definitions = fabricated_symbols(lines)
+ gated_locals = _gated_locals(lines)
+ guarded = _guarded_definitions(lines)
+
+ for number, line in enumerate(lines):
+ if _is_comment(line):
+ continue
+ body = _strip_comment(line)
+
+ state = LOCAL_DEMO_STATE.search(body)
+ if state:
+ key = _ratchet_key(rel, state.group(1))
+ if key:
+ matched.add(key)
+ else:
+ problems.append(
+ f"{rel}:{number + 1}: `{state.group(1)}` is component state. Demo mode is a "
+ f"property of the deployment — read it through isDemoMode()/canUseDemoData() in "
+ f"lib/demoMode.ts. State derived from a fetch failure fabricates exactly when "
+ f"the backend is unhealthy."
+ )
+
+ if any(start <= number <= end for start, end in definitions + guarded):
+ continue
+ read = sorted({n for n in names if re.search(rf"\b{re.escape(n)}\b", body)})
+ if not read or _gate_in_scope(lines, number, gated_locals):
+ continue
+
+ ungated = []
+ for name in read:
+ key = _ratchet_key(rel, name)
+ if key:
+ matched.add(key)
+ else:
+ ungated.append(name)
+ if ungated:
+ problems.append(
+ f"{rel}:{number + 1}: `{', '.join(ungated)}` is read with no demo gate in scope. "
+ f"Wrap it in demoFallback(...) or guard it with canUseDemoData(); outside the "
+ f"hosted demo this renders fabricated data as the tenant's own."
+ )
+
+ return problems, matched
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", default="apps/web/src", help="directory to scan")
+ parser.add_argument("--check", action="store_true", help="accepted for symmetry with the other gates")
+ args = parser.parse_args()
+ del args.check
+
+ root = pathlib.Path(args.root)
+ if not root.is_dir():
+ print(
+ f"error: {root} is not a directory — refusing to report a result for a tree I did not open",
+ file=sys.stderr,
+ )
+ return 2
+
+ scanned = sum(1 for path in root.rglob("*.ts*") if not path.name.endswith(EXEMPT_SUFFIXES))
+ if scanned == 0:
+ print(
+ f"error: no TypeScript sources under {root} — refusing to report a result for an empty corpus",
+ file=sys.stderr,
+ )
+ return 2
+
+ problems, matched = findings(root)
+
+ stale = [f"{suffix} :: {const}" for (suffix, const) in KNOWN_UNGATED if (suffix, const) not in matched]
+ if stale:
+ print(f"{len(stale)} stale entry(ies) in KNOWN_UNGATED:\n", file=sys.stderr)
+ for entry in stale:
+ print(f" {entry} — no longer matches anything; remove it", file=sys.stderr)
+ return 1
+
+ if problems:
+ print(f"{len(problems)} ungated demo-data site(s) across {scanned} file(s):\n", file=sys.stderr)
+ for problem in problems:
+ print(f" {problem}", file=sys.stderr)
+ print(
+ "\nSee apps/web/src/lib/demoFallback.ts. Fabricated security data must never render "
+ "as a tenant's real state, and no component may decide for itself that it is a demo.",
+ file=sys.stderr,
+ )
+ return 1
+
+ print(
+ f"OK: {scanned} file(s) scanned; every fabricated symbol is reachable only behind the demo gate "
+ f"({len(KNOWN_UNGATED)} known exception(s) ratcheted)."
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_demo_state_gate.py b/tests/test_demo_state_gate.py
new file mode 100644
index 000000000..4742a26fd
--- /dev/null
+++ b/tests/test_demo_state_gate.py
@@ -0,0 +1,338 @@
+"""Tests for `scripts/check_demo_state_gated.py`.
+
+The gate it replaces recognises *shapes* — `fallbackData:`, `set*(MOCK_…)`,
+`?? MOCK_…`. Each was added after a specific escape, so each only knows the
+syntax that got past it last time. `SLADashboard.tsx` wrote the same defect as
+a ternary and nothing matched: `fallbackData: demoFallback(MOCK_SLA_METRICS)`
+on line 446, correct and accepted, then `const metrics = isValidMetrics ?
+rawMetrics : MOCK_SLA_METRICS` on line 457.
+
+Two properties decide whether this gate is worth keeping, and both are
+asserted here.
+
+It has to catch a read no pattern list anticipated — the ternary, a factory
+call, a constant assembled out of another constant — and it has to catch a
+component that decides for itself that it is a demo.
+
+And it has to stay *quiet* on the four ways this tree legitimately gates:
+the read's own multi-line statement, an enclosing `if`, an early return, and
+a local derived from the gate. A gate that rejects working code is a gate
+somebody switches off, which is worse than the hole it closes. Roughly half
+the cases below are the quiet half for that reason.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+_REPO = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(_REPO / "scripts"))
+
+import check_demo_state_gated as gate # noqa: E402
+
+
+def _tree(tmp_path: Path, relative: str, source: str) -> Path:
+ """A fake `apps/web/src` so findings report real-looking paths."""
+ root = tmp_path / "apps" / "web" / "src"
+ target = root / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(source, encoding="utf-8")
+ return root
+
+
+def _findings(tmp_path: Path, source: str, relative: str = "components/x/View.tsx") -> list[str]:
+ problems, _matched = gate.findings(_tree(tmp_path, relative, source))
+ return problems
+
+
+# ── The reads it must catch ──────────────────────────────────────────────────
+
+#: Verbatim from `SLADashboard.tsx` before the fix.
+TERNARY_BYPASS = """\
+'use client';
+import useSWR from 'swr';
+import { demoFallback } from '@/lib/demoFallback';
+
+const MOCK_SLA_METRICS: SLAMetrics = {
+ overall: { total_alerts: 847, total_breaches: 23, breach_rate: 2.7 },
+};
+
+export function SLADashboard() {
+ const { data: rawMetrics } = useSWR('/api/v1/sla/metrics', fetcher, {
+ fallbackData: demoFallback(MOCK_SLA_METRICS),
+ });
+ const isValidMetrics = rawMetrics && typeof rawMetrics.overall === 'object';
+ const metrics = isValidMetrics ? rawMetrics : MOCK_SLA_METRICS;
+ return <div>{metrics.overall.total_alerts}</div>;
+}
+"""
+
+
+def test_a_correctly_gated_fallback_does_not_excuse_an_ungated_ternary(tmp_path):
+ """The whole point: one gated read in a file is not a gated file.
+
+ Both the older checks ask "does this file mention `canUseDemoData`?" at
+ some point, which this file does.
+ """
+ problems = _findings(tmp_path, TERNARY_BYPASS, "components/sla/SLADashboard.tsx")
+
+ assert len(problems) == 1
+ assert "MOCK_SLA_METRICS" in problems[0]
+ # The ungated ternary, not the gated `fallbackData` three lines above it.
+ assert problems[0].startswith("apps/web/src/components/sla/SLADashboard.tsx:14")
+
+
+#: Verbatim shape from `CaseWorkspace.tsx`. No constant is named anywhere, so
+#: the naming convention cannot see it — and the id comes from the route
+#: param, so the invention wears the id of the case the analyst opened.
+FACTORY_CALL = """\
+'use client';
+
+function buildDemoCase(id: string): Case {
+ return { id, title: 'Suspected lateral movement from finance subnet' };
+}
+
+export function CaseWorkspace({ caseId }: { caseId: string }) {
+ const { data, error } = useSWR(['case', caseId], () => casesApi.get(caseId));
+ const useFallback = !!error;
+ const caseRecord = data ?? (useFallback ? buildDemoCase(caseId) : undefined);
+ return <h1>{caseRecord?.title}</h1>;
+}
+"""
+
+
+def test_it_catches_a_factory_that_no_naming_convention_covers(tmp_path):
+ problems = _findings(tmp_path, FACTORY_CALL, "components/cases/CaseWorkspace.tsx")
+
+ assert len(problems) == 1
+ assert "buildDemoCase" in problems[0]
+
+
+#: `EASMView.tsx` put its headline counts beyond the convention by deriving
+#: them: the fabrication is in `SUMMARY`, which is not a `MOCK_*` name.
+DERIVED_CONSTANT = """\
+const MOCK_ASSETS = [
+ { host: 'vpn.example.com', status: 'critical', ports: 3 },
+];
+
+const SUMMARY = {
+ totalAssets: MOCK_ASSETS.length,
+ riskScore: 72,
+};
+
+export function EASMView() {
+ return <p>{SUMMARY.riskScore}</p>;
+}
+"""
+
+
+def test_it_follows_a_fabrication_into_the_constant_assembled_from_it(tmp_path):
+ problems = _findings(tmp_path, DERIVED_CONSTANT, "components/easm/EASMView.tsx")
+
+ assert len(problems) == 1
+ assert "SUMMARY" in problems[0]
+
+
+#: Verbatim shape from `HuntView.tsx`.
+LOCAL_DEMO_STATE = """\
+export function HuntView() {
+ const [demoMode, setDemoMode] = useState(false);
+ const run = async () => {
+ try {
+ setResults(await huntApi.search(q));
+ } catch {
+ setDemoMode(true);
+ }
+ };
+ return <span>{demoMode ? 'Sample data' : 'Live backend'}</span>;
+}
+"""
+
+
+def test_it_catches_a_component_deciding_for_itself_that_it_is_a_demo(tmp_path):
+ problems = _findings(tmp_path, LOCAL_DEMO_STATE, "components/hunt/HuntView.tsx")
+
+ assert len(problems) == 1
+ assert "demoMode" in problems[0]
+ assert "property of the deployment" in problems[0]
+
+
+def test_a_disclosure_string_is_not_demo_state(tmp_path):
+ """`sampleNotice` holds the backend's own words about why data is sample.
+
+ Banning it would push authors toward showing sample data with no notice
+ at all, which is the failure this whole area exists to prevent.
+ """
+ source = """\
+export function HuntView() {
+ const [sampleNotice, setSampleNotice] = useState<string | null>(null);
+ return <p>{sampleNotice}</p>;
+}
+"""
+ assert _findings(tmp_path, source) == []
+
+
+# ── The four ways this tree legitimately gates ───────────────────────────────
+
+
+ ("label", "source"),
+ [
+ (
+ "the read's own statement, wrapped across lines",
+ """\
+const MOCK_ALERTS = [{ host: 'WIN-DC01', severity: 'high' }];
+
+export function AlertsView() {
+ const { data } = useSWR(['alerts'], () => alertsApi.list(), {
+ fallbackData: demoFallback({
+ alerts: MOCK_ALERTS,
+ total: MOCK_ALERTS.length,
+ }),
+ });
+ return <div>{data?.total}</div>;
+}
+""",
+ ),
+ (
+ "an enclosing block whose condition is the gate",
+ """\
+const MOCK_RULES = [{ name: 'Encoded PowerShell', hits: 4 }];
+
+export function DetectionCatalog() {
+ const load = async () => {
+ try {
+ setRules(await detectionApi.list());
+ } catch (err) {
+ if (canUseDemoData()) {
+ setRules(MOCK_RULES);
+ } else {
+ setRules([]);
+ }
+ }
+ };
+ return <div onClick={load} />;
+}
+""",
+ ),
+ (
+ "an early return that withholds the whole render",
+ """\
+const MOCK_HANDOFF_ITEMS = [{ analyst: 'Sarah Chen', open: 4 }];
+
+export function ShiftsView() {
+ const [items] = useState(MOCK_HANDOFF_ITEMS);
+ if (!canUseDemoData()) {
+ return <NotYetWired title="Shift handoff" />;
+ }
+ return <ul>{items.length}</ul>;
+}
+""",
+ ),
+ (
+ "a local derived from the gate",
+ """\
+const DEMO_CONNECTORS = [{ name: 'CrowdStrike EDR', events: 412 }];
+
+export function SettingsView() {
+ const { data, error } = useSWR('connectors', () => connectorsApi.list());
+ const useFallback = !!error && canUseDemoData();
+ const connectors = data?.connectors ?? (useFallback ? DEMO_CONNECTORS : []);
+ return <div>{connectors.length}</div>;
+}
+""",
+ ),
+ ],
+)
+def test_it_stays_quiet_on_correctly_gated_code(tmp_path, label, source):
+ assert _findings(tmp_path, source) == [], label
+
+
+def test_a_scalar_anchor_is_not_a_fabricated_record(tmp_path):
+ """`MOCK_BASE` pins the mocks to a fixed instant so SSR and the client agree.
+
+ It is a number. Flagging it teaches authors that the gate cries wolf,
+ which is how a gate ends up with a `# noqa` beside every call site.
+ """
+ source = """\
+const MOCK_BASE = new Date('2026-05-06T12:00:00Z').getTime();
+const ago = (mins: number) => new Date(MOCK_BASE - mins * 60 * 1000).toISOString();
+
+export function View() {
+ return <time>{ago(5)}</time>;
+}
+"""
+ assert _findings(tmp_path, source) == []
+
+
+def test_a_component_that_renders_a_gated_mock_is_not_itself_fabricated(tmp_path):
+ """Promoting the component would flag its own definition as a read of itself."""
+ source = """\
+const DEMO_ROWS = [{ host: 'WIN-DC01', hits: 2 }];
+
+export function DashboardView() {
+ const { data } = useSWR('rows', fetcher, { fallbackData: demoFallback(DEMO_ROWS) });
+ return <div>{data?.length}</div>;
+}
+"""
+ assert _findings(tmp_path, source) == []
+
+
+def test_tests_may_name_a_fabricated_constant(tmp_path):
+ """Naming the mock is how a test proves the mock does not render."""
+ source = """\
+const FABRICATED = ['WORKSTATION-042'];
+it('renders none of it', () => {
+ expect(screen.queryByText(FABRICATED[0])).toBeNull();
+});
+"""
+ assert _findings(tmp_path, source, "components/x/View.test.tsx") == []
+
+
+# ── The ratchet, and refusing an empty tree ──────────────────────────────────
+
+
+def test_the_ratchet_is_empty(tmp_path):
+ """A gate seeded with its own exceptions has never been true.
+
+ Not a style preference: `KNOWN_UNGATED` is checked in both directions, so
+ an entry that stops matching fails the build. Starting empty is what makes
+ the first entry a deliberate act somebody has to justify.
+ """
+ assert gate.KNOWN_UNGATED == {}
+
+
+def test_a_stale_ratchet_entry_fails_rather_than_lingering(tmp_path, monkeypatch):
+ monkeypatch.setitem(gate.KNOWN_UNGATED, ("components/gone/Ghost.tsx", "MOCK_GHOST"), "removed last year")
+ root = _tree(tmp_path, "components/x/View.tsx", "export const x = 1;\n")
+
+ monkeypatch.chdir(root.parents[2])
+ monkeypatch.setattr(sys, "argv", ["check_demo_state_gated.py"])
+
+ assert gate.main() == 1
+
+
+def test_it_refuses_a_tree_it_never_opened(tmp_path, monkeypatch):
+ """`found nothing` and `scanned nothing` must not print the same word."""
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(sys, "argv", ["check_demo_state_gated.py"])
+
+ assert gate.main() == 2
+
+
+def test_it_refuses_a_present_but_empty_source_tree(tmp_path, monkeypatch):
+ (tmp_path / "apps" / "web" / "src").mkdir(parents=True)
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(sys, "argv", ["check_demo_state_gated.py"])
+
+ assert gate.main() == 2
+
+
+def test_the_live_console_passes(tmp_path):
+ """The gate is wired into CI, so `main` has to be clean under it."""
+ problems, _matched = gate.findings(_REPO / "apps" / "web" / "src")
+
+ assert problems == [], "\n".join(problems)