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.

Merge pull request #147 from prince30121/v8.0/agentic-soc-foundation

Prince Sinhaa0fc3eb8b6a8
diff --git a/AISOC_V8_PROGRESS.md b/AISOC_V8_PROGRESS.md
deleted file mode 100644
index b991ed936..000000000
--- a/AISOC_V8_PROGRESS.md
+++ /dev/null
@@ -1,179 +0,0 @@
-# AiSOC v8.0 — Parallel Team Kickoff Progress
-
-> Tracking doc for the v8.0 north-star release. Mirrors the convention used by
-> `AI_STACK_PLAN_PROGRESS.md`: `[ ]` → `[~]` (in flight) → `[x]` (shipped).
-> Each task tag (`T1.1` etc.) maps to the v8.0 plan handed to the eng team.
-
-**Branch**: `v8.0/agentic-soc-foundation` (renamed mid-session from `v8.0/parallel-team-kickoff`; rename commit is `20bbb749`)
-**Started**: 2026-05-13
-**Coordinator**: parent agent (this conversation)
-**Mode**: 7-track parallel team, kicked off via background subagents
-**Author**: Prince Sinha · [@prince30121](https://github.com/prince30121) · Senior Director, Innovations at Cyble
-
-### Git remote model
-
-- `origin` → `https://github.com/prince30121/AiSOC.git` (fork — push target)
-- `upstream` → `https://github.com/beenuar/AiSOC.git` (canonical — PR target)
-
-Work lands on the fork; the integration PR is raised against `upstream/main`.
-
-PR compare URL (click to finalise on GitHub):
-`https://github.com/beenuar/AiSOC/compare/main...prince30121:AiSOC:v8.0/agentic-soc-foundation?expand=1`
-
-PR title: `v8.0 wave-1 shipped + wave-2 checkpoint`
-
-PR body: see `.pr-body-wave1.md` (gitignored — local working copy). Paste the full contents into the GitHub web UI when opening the PR.
-
-Status (refreshed 2026-05-14, 17:20 UTC):
-
-- **Wave-1 SHIPPED** — PR [#125](https://github.com/beenuar/AiSOC/pull/125) merged to `upstream/main` at `b854010e` on 2026-05-14T13:47 UTC. All wave-1 deliverables (graph at ingest, four-agent rebrand, `/hunt`, 6 fully-tested connectors, L0–L4 maturity, public scoreboard) are live on `main`.
-- **Post-merge wave** — 12 follow-on PRs landed on `main` after PR #125: critical/high security fixes (#116–#128), CodeQL alert sweep to zero (#133, #136, #137), security smoke + UX cleanup (#132), playbook engine correctness (#129), and the first community contribution (#135 — UEBA env-var alignment, closes #134).
-- **Wave-2** — still tracked here as `[~]` (in flight) for the 10 remaining connectors and the cross-track polish items below. `VERSION` stays at `7.3.1` until wave-2 lands; all v8.0 work is documented under `[Unreleased]` in [`CHANGELOG.md`](CHANGELOG.md).
-- **Original wave-2 background subagents** — errored mid-task; their checkpoint output landed as the 11 per-track `(wip)` commits below, all of which are now on `main` as part of the PR #125 squash-merge.
-
-Wave-2 commits (most recent first, all SSH-signed, attributed Prince Sinha):
-- `ecf2ffe1` T7.3 three anchor blog posts (graph, latency, L0–L4) (wip)
-- `6dba7234` T5.4 public benchmark scoreboard + bench page polish (wip)
-- `700a9452` T5.5 wet-eval weekly CI workflow + secrets doc (wip)
-- `23d92541` T5.3 fidelity benchmark on public datasets (wip)
-- `ee52d642` T4 wave-2 — Cloudflare ZT, Sysdig, Vault, Snowflake, OCI, Sublime, Abnormal, Box, Dropbox, Datadog (wip)
-- `57f93a98` T3.6 Block Kit + Adaptive Cards + email fallback (wip)
-- `0efe3da5` T3.5 business-context rule engine + Monaco editor (wip)
-- `8df637b9` T3.3 attack-chain timeline + ranking (wip)
-- `a6ce3342` T3.2 effective permissions resolver (AWS done, others scaffolded) (wip)
-- `87c151a7` T2.3 LLM input contract — fail-closed validator (wip)
-- `5a0d179f` T1.2 config snapshots — :CONFIGURED_AS {ts} edges (wip)
-- `2c7a66c1` T2.1 pre-fetched ContextBundle
-
-### Commit signing
-
-- Local repo only (workspace rule: no global config touched)
-- SSH-based signing via `~/.ssh/id_rsa.pub` (`commit.gpgsign = true`, `tag.gpgsign = true`)
-- Allowed signers at `.git/allowed_signers` (untracked — local only)
-- All wave-1 commits re-signed via `git rebase --exec 'git commit --amend --no-edit --reset-author -S'` against `upstream/main`
-- New commits also carry `Signed-off-by: Prince Sinha <[email protected]>` (DCO trailer)
-
----
-
-## Track-by-track status
-
-### Track 1 — Graph at ingest
-- [~] T1.1 Ingest-side graph writer (P0, L) — scaffold landed: schema v1.0 + Neo4j writer + extractors for `aws_security_hub` / `github_audit` / `okta_system_log` / `kubernetes_audit` + generic fallback for the other 10 source types + `security.graph_updates` Kafka topic + fan-out wiring (failures NEVER block fusion); 16 Go unit tests green; Python integration test stubbed (`services/agents/tests/test_graph_freshness.py`, `pytest -m integration`). 360-event corpus + remaining connector mappings deferred to T1.2 / T4 wave.
-- [~] T1.2 Config snapshots (P0, M) → T1.1 — partial / wip — `5a0d179f` (`:CONFIGURED_AS {ts}` edges + connector overrides for AWS / GitHub / Okta); **Azure Defender + GCP SCC** now expose `get_resource_config` (Microsoft Graph `alerts_v2` + SCC v1 findings GET) with 401 re-auth retry, `snapshot_freshness: live`, and **respx** coverage in `test_azure_connectors.py` / `test_gcp_connectors.py`. Ingest-time `:CONFIGURED_AS` materialisation for Azure/GCP remains optional follow-up.
-- [x] T1.3 Publish graph schema (P0, S) → T1.1
-- [x] T1.4 Real-time graph-update WebSocket (P1, S) → T1.1 — `services/realtime/src/index.ts` adds the `graph` channel (`/ws/graph` and `/ws/all`), a dedicated `aisoc-realtime-graph` consumer group on `security.graph_updates`, tenant-scoped fan-out of the full `GraphUpdate` envelope, and best-effort start (graph-topic failure never blocks fused-alerts fan-out). Topic name honours `AISOC_GRAPH_UPDATES_TOPIC` / `KAFKA_TOPIC_GRAPH_UPDATES`, defaulting to the same `security.graph_updates` that the Go ingest writer publishes to (`services/ingest/internal/graph/writer.go`). `tsc --noEmit` green.
-
-### Track 2 — Agent reasoning: latency + cost
-- [~] T2.1 Pre-fetched context bundle (P0, M) → T1.1 — partial / wip — `2c7a66c1` (ContextBundle dataclass + parallel pre-fetch from graph/RAG/threat-intel). **Investigator** path: `orchestrator.py` prefetches `context_bundle`, `state.py` carries it, `bundle_prompt.py` + `format_bundle_prompt_append` wire it into recon / forensic / responder / report-writer prompts. Cloud / identity / insider-threat / phishing agents accept optional `bundle` kwarg. Full **LangGraph parallel fan-out + Join** remains **T2.2**.
-- [ ] T2.2 LangGraph parallel topology (P0, M) → T2.1
-- [~] T2.3 LLM-input contract (P0, M) → T2.1 — partial / wip — `87c151a7` (`app/llm/contract.py` + `safe_ainvoke` / `safe_astream`; `test_llm_contract.py` asserts raw OCSF JSON is rejected and `summarize_structure_for_llm` output passes; dict-shaped messages avoid `langchain_core` at test import). **Wired** on contextual chat (`api/contextual.py`), auto-triage, and investigator subgraph agents that call the shared LLM path; remaining non-investigation agents can adopt `safe_ainvoke` incrementally.
-- [x] T2.4 Token + USD eval telemetry (P0, S)
-- [x] T2.5 Four-agent brand consolidation (P0, S)
-
-### Track 3 — UI
-- [x] T3.1 SOC Insights dashboard (P1, M) → T2.4
-- [~] T3.2 Effective Permissions (P0, L) → T1.1 — partial / wip — `4ff1b7f4` (graph schema edge) + `a6ce3342` (resolver — AWS done, Azure / GCP / Okta / Google Workspace scaffolded; Cytoscape UI pending)
-- [~] T3.3 Attack Chains (P0, L) → T1.1 — partial / wip — `8df637b9` (timeline ranking service + `041_attack_chains.sql` migration + `/v1/cases/{id}/attack-chain` endpoint; UI pending)
-- [~] T3.4 /hunt NL surface (P0, S-M) — endpoints/UI/redirect shipped; scheduler is feature-flagged off by default (`AISOC_HUNT_SCHEDULER_ENABLED=0`) with execution stub pending real ES|QL runner wiring
-- [~] T3.5 Business Context Rules (P1, M) — partial / wip — `0efe3da5` (rule engine + Monaco editor scaffold; eval engine + persistence pending)
-- [~] T3.6 Slack/Teams Block Kit approvals (P1, M) — partial / wip — `57f93a98` (Block Kit + Adaptive Cards + email fallback + HMAC verify + audit/timeout services)
-- [~] T3.7 NL → playbook generator (P1, M) → T3.4 — partial / wip (covered alongside T3.5 in `0efe3da5`; schema-validation retry loop pending)
-- [~] T3.8 Design system v2 + Storybook (P1, M) — partial / wip (Storybook scaffold landed with T3.6 commit; full token sweep pending)
-
-### Track 4 — Connector wave (15 new)
-- [~] T4.1 Cloudflare WAF + Zero Trust (M) — partial / wip — landed in `ee52d642` (Zero Trust audit; WAF rules pending)
-- [x] T4.2 Tines (S)
-- [x] T4.3 Torq (S)
-- [~] T4.4 Sublime Security (M) — partial / wip — landed in `ee52d642`
-- [~] T4.5 Abnormal Security (M) — partial / wip — landed in `ee52d642`
-- [~] T4.6 Lacework — policy violations stream (S, extend) — partial / wip — extension landed in `ee52d642` (`_normalize_policy` for policy-violation events)
-- [~] T4.7 Sysdig (M) — partial / wip — landed in `ee52d642`
-- [x] T4.8 Falco (S)
-- [~] T4.9 HashiCorp Vault audit (M) — partial / wip — landed in `ee52d642`
-- [x] T4.10 PagerDuty / Opsgenie (S)
-- [x] T4.11 Atlassian Confluence audit (S)
-- [~] T4.12 Box / Dropbox audit (M) — partial / wip — landed in `ee52d642`
-- [~] T4.13 Datadog logs + APM (M) — partial / wip — landed in `ee52d642` (logs scaffolded; APM trace correlation pending)
-- [~] T4.14 Snowflake audit (M) — partial / wip — landed in `ee52d642`
-- [~] T4.15 OCI (Oracle Cloud) (M) — partial / wip — landed in `ee52d642`
-
-### Track 5 — Public benchmark + eval extensions
-- [x] T5.1 Speed + token + USD published (P0, S) → T2.4
-- [x] T5.2 Methodology page (P0, S) → T5.1
-- [~] T5.3 Public-dataset fidelity benchmark (P1, M) — partial / wip — `23d92541` (CICIDS-2017 micro fixture + fidelity harness scaffold; CTU-13 dataset + benchmark page sweep pending)
-- [~] T5.4 Public scoreboard page (P1, M) → T5.1 — partial / wip — `6dba7234` (`/benchmark-scoreboard` MDX page + scoreboard.json data file + `/benchmark` page polish; live data feed pending)
-- [~] T5.5 Wet-eval weekly CI job (P1, S) → T2.4 — partial / wip — `700a9452` (`.github/workflows/wet-eval.yml` + secrets doc + `wet_eval_check.py`; OPENAI_API_KEY secret needs setting in repo)
-
-### Track 6 — Hosted SaaS + GTM surface
-- [ ] T6.1 app.aisoc.dev managed waitlist (P0, L) → T1.1, T2.2, T3.2, T3.3
-- [x] T6.2 Reference-customer page template (P0, S)
-- [x] T6.3 Sovereign + air-gap landing page (P1, S)
-- [x] T6.4 Demo seeder + screencast polish (P1, S)
-
-### Track 7 — Narrative + IDE-driven SOC
-- [~] T7.1 Cursor extension (P0, M) — scaffold landed at `services/mcp/cursor-extension/`; marketplace publish deferred
-- [x] T7.2 L0–L4 white paper (P1, S)
-- [~] T7.3 Three anchor blog posts (P1, S) → T5.1, T7.1 — partial / wip — `ecf2ffe1` (three drafts: graph-at-ingest, sub-minute latency, L0–L4 maturity; copy edit pass pending)
-
----
-
-## Wave-1 kickoff (parallel — weeks 1–3 from the plan)
-
-These independent tasks fire concurrently as background subagents:
-
-| Subagent | Task | Files |
-|---|---|---|
-| A | T2.5 four-agent rebrand | `services/agents/app/agents/__init__.py`, `apps/docs/docs/architecture/agents.md`, landing copy |
-| B | T2.4 token/USD telemetry | `scripts/run_evals.py`, `scripts/render_eval_charts.py`, `apps/docs/docs/benchmark.md` |
-| C | T3.4 `/hunt` rebrand + saved/scheduled hunts | `apps/web/src/app/(app)/hunt/`, `services/api/app/api/v1/endpoints/hunts.py` |
-| D | T1.1 ingest-side graph writer | `services/ingest/internal/graph/*` |
-| E | T1.3 graph schema publication | `apps/docs/docs/architecture/graph-schema.md`, `schemas/graph-schema.yaml`, `scripts/export_graph_schema.py` |
-| F | T4 wave-1 connectors (Tines, Torq, Falco, PagerDuty, Confluence) | `services/connectors/app/connectors/<id>.py`, `plugins/<id>/plugin.yaml`, `apps/docs/docs/connectors/<id>.md` |
-| G | T7.1 Cursor extension kickoff | `services/mcp/cursor-extension/` |
-| H | T5.1 + T5.2 published benchmark + methodology | `apps/docs/docs/benchmark.md`, `apps/docs/docs/benchmark-methodology.md` |
-| I | T3.1 SOC Insights dashboard | `apps/web/src/app/(app)/dashboards/soc-insights/page.tsx`, `services/api/app/api/v1/endpoints/insights.py` |
-
----
-
-## Coordination notes
-
-- **Branch model**: every subagent commits to `v8.0/agentic-soc-foundation`. Conflicts resolved by the coordinator at merge time.
-- **Push target**: `origin` (fork at `prince30121/AiSOC`).
-- **PR target**: `upstream/main` (`beenuar/AiSOC:main`).
-- **No secrets**: no API keys, tokens, or credentials committed (workspace rule).
-- **No competitor names** in code/docs/comments (workspace rule).
-- **No plan-file edits**: the plan in `plans/` is the source of truth; this file is the progress mirror.
-- **CI gate**: each wave-1 finish must keep `pnpm lint` and `python -m pytest services/agents/tests/` green.
-- **DCO**: all commits sign-off with `Signed-off-by: Prince Sinha <[email protected]>` and SSH-sign via `id_rsa`.
-
-## Wave-1 summary
-
-- **29 commits** on `v8.0/agentic-soc-foundation` since `upstream/main`
-- **12 of 12** subagents finished (10 `[x]` shipped, 2 `[~]` scaffold-landed: T1.1 graph writer foundation, T7.1 IDE extension scaffold)
-- **0 secrets** committed (workspace rule)
-- **0 competitor names** introduced (workspace rule)
-- **Foundation laid for wave-2**: T1.1 unblocks T1.2 / T1.4 / T2.1 / T3.2 / T3.3 / T6.1; T2.4 telemetry unblocks T5.4 / T5.5; T3.4 `/hunt` unblocks T3.7 NL→playbook
-
----
-
-## Changelog
-
-- 2026-05-13 — Wave-1 integration: 29 commits re-signed and re-authored as `Prince Sinha <[email protected]>` via `git rebase --exec '... --reset-author -S'` against `upstream/main`; SSH commit signing configured locally with `~/.ssh/id_rsa.pub`; `Signed-off-by` DCO trailer applied to new commits. Branch ready to push to `origin` (fork) and PR against `upstream/main`.
-- 2026-05-13 — T1.1 ingest-side graph writer scaffold landed (status `[~]`). New package `services/ingest/internal/graph/` with `schema.go` (versioned v1.0 — 17 node labels + 14 relationships matching `schemas/graph-schema.yaml`), `writer.go` (Neo4j Bolt driver, batched UNWIND upserts keyed on `(label, natural_key)` + props_hash, bounded queue with drop-and-metric so failures never block fusion, root-context cancellation for prompt shutdown), and `extractor.go` (real extractors for `aws_security_hub` / `github_audit` / `okta_system_log` / `kubernetes_audit` plus a generic fallback that pulls actor + endpoint nodes from any OCSF event so the other 10 source types still produce a non-empty projection). `services/ingest/internal/handler/handler.go` fan-outs into the writer concurrently with the fusion publish (graph failure never blocks). New `PublishGraphUpdate` on the Kafka publisher emits `{entity_id, change_type, ts, label, rel_type, schema_version}` envelopes to a new `security.graph_updates` topic for T1.4. New env config: `AISOC_GRAPH_ENABLED` (default off), `AISOC_NEO4J_URI` / `AISOC_NEO4J_USER` / `AISOC_NEO4J_PASSWORD` (env-only, never committed), `AISOC_GRAPH_BATCH_SIZE`, `AISOC_GRAPH_FLUSH_INTERVAL_MS`, `AISOC_GRAPH_QUEUE_SIZE`, `AISOC_GRAPH_UPDATES_TOPIC`. 16 Go unit tests at `services/ingest/internal/graph/{writer,extractor}_test.go` green in 1.3s — exercise UNWIND batching, idempotency on natural_key, partial-failure surfacing, queue-full drop, the never-blocks-on-failure contract (blocking fake driver hangs but `WriteEvent` returns immediately), and per-extractor entity/edge shapes. Python integration test at `services/agents/tests/test_graph_freshness.py` (`@pytest.mark.integration`) probes p95 < 2s graph freshness end-to-end, skips cleanly when Kafka or Neo4j aren't available. New `integration` marker registered in `services/agents/pyproject.toml`. `services/ingest/go.mod` adds `github.com/neo4j/neo4j-go-driver/v5 v5.27.0`. T1.2 (config snapshots) and the 360-event synthetic corpus expansion are explicitly deferred — TODO comments call out the connector list and the corpus stub.
-- 2026-05-13 — T2.4 shipped: per-investigation token / USD / latency telemetry now lives in `eval_report.json -> per_investigation`. New stdlib-only module `scripts/eval_telemetry.py` (deterministic 4-chars/token estimator, illustrative 2025-era public rate card mirroring `services/agents/app/core/cost_telemetry.py`, mean/median/p50/p95/p99 across all 200 incidents and per-template). `scripts/run_evals.py` gains `--telemetry-only` / `--telemetry-model` / `--no-telemetry-records` flags so the substrate-walk numbers can run without the agent dependency stack. `scripts/render_eval_charts.py` extended with a hand-rolled SVG emitter (zero new deps) that writes four charts into `apps/docs/docs/benchmark-charts/`: `latency-p50-p95-p99.svg`, `tokens-distribution.svg`, `usd-distribution.svg`, `latency-by-template.svg`. `apps/docs/docs/benchmark.md` gains a clearly-labeled "Deterministic-substrate budget projection (T2.4)" section with the four SVGs inline plus a substrate budget table; the existing wet-eval tables stay as placeholders per workspace rule. Wet eval lives in T5.5; substrate budgets are an upper-bound CI gate, never quoted as live agent performance. New unit tests at `services/agents/tests/test_eval_telemetry.py` (18 cases: rate-card maths, token estimator, aggregate stats, severity scaling, SVG renderer round-trip including the no-records fallback) — all green.
-- 2026-05-13 — Branch created, progress tracker initialised, wave-1 subagents dispatched.
-- 2026-05-13 — T7.2 shipped: L0–L4 automation maturity white paper. Canonical
- docs concept page at `apps/docs/docs/concepts/automation-maturity.md`,
- full-length white paper (~4,400 words) at
- `apps/web/content/papers/l0-l4-automation-maturity.md`, rendered PDF at
- `apps/web/public/papers/l0-l4-automation-maturity.pdf`, render tool at
- `scripts/render_white_paper.py` (WeasyPrint + python-markdown). Sidebar
- wired and `concepts/capabilities.md` cross-linked.
-- 2026-05-13 — T5.1 + T5.2 landed: benchmark.md gains north-star callout, latency/tokens/USD scaffold (T2.4-populates placeholders) + provenance footer; new benchmark-methodology.md (dataset, substrate-vs-wet, rate card, reproduce, limitations); `pnpm eval:public` entry point + `scripts/render_eval_charts.py` renderer; README footer points reproducers at the methodology page.
-- 2026-05-13 — T1.3 shipped: graph schema v1.0 published (`schemas/graph-schema.yaml`, `apps/docs/docs/architecture/graph-schema.md`) with Mermaid ER diagram, 17 labels, 14 relationships, event-edge convention. CI drift gate at `.github/workflows/graph-schema-check.yml` runs `scripts/export_graph_schema.py --check` on PRs touching the schema or `services/ingest/internal/graph/**`.
-- 2026-05-13 — T7.1 IDE extension scaffold landed at `services/mcp/cursor-extension/` (4 MCP-backed commands, typed JSON-RPC client, webview renderer, 19 passing smoke tests; marketplace publish deferred to follow-up).
-- 2026-05-13 — T6.2 + T6.3 shipped: GTM marketing surface live without engineering involvement. New `/customers` index + `/customers/[slug]` MDX-driven case-study template (`apps/web/content/customers/example.mdx` template, `apps/web/src/lib/customers.ts` loader, `next-mdx-remote` + `gray-matter` wired into the web app). New `/sovereign` deployment-flexibility one-pager with deployment-mode matrix and any-cloud × any-region grid citing the air-gap overlay, Helm chart, and Terraform modules. Marketing nav (`LandingNav`) and footer (`Footer`) now surface the two new pages.
-- 2026-05-13 — T2.5 shipped: public agent narrative consolidated to four named agents — Detect / Triage / Hunt / Respond. New facade at `services/agents/app/agents/__init__.py` (DetectAgent, TriageAgent, HuntAgent, RespondAgent + back-compat aliases AutoTriageAgent, PhishingAgent, IdentityAgent, CloudAgent, InsiderThreatAgent, ResponderAgent — sub-agents stay as internal modules but are framed as TriageAgent capabilities). 32 facade tests at `services/agents/tests/test_four_agent_facade.py` lock the contract. New `apps/docs/docs/architecture/agents.md` (added to sidebar) is the public source of truth, including a `Status: in flight` note for `DetectAgent.process` cross-service wiring into `services/fusion/`. Landing-page hero copy at `apps/web/src/components/onboarding/StartHero.tsx` is now "Detect. Triage. Hunt. Respond." with a four-agent strip; the matching Vitest test asserts only the four branded names appear and that sub-agent names are never promoted to the hero.
-- 2026-05-13 — T3.1 shipped: SOC Insights dashboard live at `/dashboards/soc-insights` with seven rolling-window tiles (MTTA, MTTR, FP rate, alerts/day, cases/day, agent cost / investigation, analyst hours saved). New aggregator `GET /v1/insights/soc?window=24h|7d|30d` at `services/api/app/api/v1/endpoints/insights.py` returns a Pydantic-typed payload with current/previous-window values, percentage delta, and a 24-bucket sparkline per tile. "Analyst hours saved" heuristic is documented inline as `MANUAL_INVESTIGATION_MINUTES = 45` and surfaced in the response so the UI can render the assumption beside the tile. Realtime service (`services/realtime/src/index.ts`) gains an `insights` channel + 30-second `insights_updated` tick (`INSIGHTS_TICK_MS`); `case.updated` events also route through the insights channel so analysts see fresh tile values within a second of a case change. Web page (`apps/web/src/app/(app)/dashboards/soc-insights/page.tsx` + view/components under `apps/web/src/components/soc-insights/`) renders the tile grid with skeleton + error states, an inline-SVG sparkline (no new dep), and SWR-driven WebSocket revalidation. Sidebar nav surfaces the new dashboard. Tests: `services/api/tests/test_insights_endpoint.py` (12 cases — delta math, window allowlist, seven-tile shape, hours-saved heuristic, zero-state) + `apps/web/src/components/soc-insights/SOCInsightsView.test.tsx` (loading skeleton, tile labels rendered, error state, Sparkline math). Cost-table read path catches `SQLAlchemyError` and returns 0 so the dashboard renders cleanly until `aisoc_run_costs` deploys — labelled `# TODO(T2.4-followup)` in the code.
-- 2026-05-13 — T3.4 shipped (scheduler scaffolded behind a feature flag): `/hunt` is the canonical natural-language hunt surface and `/investigate` 308-redirects there with query params preserved. New hero block on `/hunt` ("Hunt at the speed of thought" + three example pills covering geo / IAM / GitHub questions) calls `POST /v1/nl-query/translate` and runs the hunt within ~5s. Saved-hunts CRUD lives at `services/api/app/api/v1/endpoints/saved_hunts.py` (`POST/GET/DELETE /v1/saved-hunts`, `GET /v1/saved-hunts/{id}`, `POST /v1/saved-hunts/{id}/run`) backed by a new `SavedHunt` SQLAlchemy model + RLS-aware migration `services/api/migrations/040_saved_hunts.sql`. NL translator gains a 70-country name → ISO-3166 detector (`services/agents/app/nl_query/translator.py`, vendored copy synced) so "attacks from Iran" becomes `WHERE source.geo.country_iso_code == "IR"`. Hunt scheduler worker at `services/api/app/workers/hunt_scheduler.py` (asyncio.Task pattern matching `oauth_refresh`) sweeps `aisoc_saved_hunts`, fires due cron entries, and stamps `last_run_at` — *gated behind* `AISOC_HUNT_SCHEDULER_ENABLED=0` (default off) with the actual ES|QL runner stubbed `# TODO(T3.4-followup)` until the lake executor lands. UI: `HuntView` enhanced with hero, NL pills (auto-submit on click), saved-hunts sidebar with re-run + delete, raw saved-search list preserved alongside; `apps/web/src/lib/api.ts` exposes typed `savedHuntsApi` + `nlQueryApi`; shared types added at `packages/types/src/hunt.ts`. Tests: 38 cases at `services/api/tests/test_saved_hunts_endpoint.py` covering cron validation, CRUD wire shape, run re-translation/timestamp stamping, and a mocked scheduler `run_once` that asserts due hunts fire the executor + case-creation callback. OpenAPI yaml re-exported.
-- 2026-05-13 — T4 wave-1 connectors shipped (T4.2 Tines, T4.3 Torq, T4.8 Falco, T4.10 PagerDuty + Opsgenie, T4.11 Confluence audit). Six new connector modules under `services/connectors/app/connectors/{tines,torq,falco,pagerduty,opsgenie,confluence_audit}.py`, registered in `_CONNECTOR_CLASSES` and surfaced through the marketplace + docs sidebar. Five push/pull SaaS audit-and-incident integrations plus one push-only K8s runtime sensor (Falco via falcosidekick → HTTP webhook); each ships a marketplace manifest in `plugins/<id>/plugin.yaml`, a setup walkthrough in `apps/docs/docs/connectors/<id>.md`, full pytest coverage (`services/connectors/tests/connectors/test_<id>.py` — 78 tests across the six modules, all green) and vendor-doc-sourced fixtures in `services/connectors/tests/fixtures/<id>/sample_event.json`. Wave-1 severity ladder collapses each vendor's native scheme into AiSOC's four-tier (`info | low | medium | high`) per the rules in the task spec; pagination strategies cover offset/limit (PagerDuty incidents, Confluence audit), opaque cursor (PagerDuty audit, Tines, Torq), and absolute-next-URL (Opsgenie). PagerDuty + Opsgenie are accounted as a single wave-1 "slot" since they're paired on-call vendors, so the wave still totals five shipped slots out of T4's longer roadmap.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 450dc7d46..0d37c6147 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -58,410 +58,6 @@ hit. The marketing `/benchmark` page now cross-links to the scoreboard for
the full weekly history. Wet-eval rows arrive automatically once the T5.5
weekly CI workflow lands.
-### Console workbench wave — v1.5 PR-1/-2/-3/-5/-6/-7/-8
-
-Turns the SOC operator surface from a list of pages into a workbench. Seven
-PRs landed in two days and together change what `/alerts`, `/queue`,
-`/detection/tuning`, and the topbar look like end-to-end. (PR-4, the
-Investigation Rail, has its own entry deeper in this section.)
-
-- **PR-1 — Global time-window selector + topbar context.** One selector at
- the top of the console drives every page that accepts a time range
- (Alerts, Cases, Hunts, Funnel KPIs, Pipeline Health, Detection Tuning).
- Backed by a new `TimeWindowProvider` in `apps/web/src/components/time/`
- with persistence in `localStorage` and URL params so any window is
- deep-linkable. Every API client now sends `from`/`to` query params on
- every list endpoint instead of relying on per-page defaults.
-- **PR-2 — Tenant switcher + role badge.** MSSP operators flip tenants from
- the topbar without re-authenticating; the role badge next to the user
- avatar makes it impossible to confuse a `viewer` session with an `admin`
- session. New endpoint `GET /api/v1/tenants/me/identity` returns the
- caller's effective tenant ID, accessible tenants, role, and email so the
- client can render the switcher without leaking other-tenant rows.
-- **PR-3 — Critical severity tier.** The severity ladder is now exactly
- five tiers: `info | low | medium | high | critical`. Vendor-native
- criticals that previously got collapsed into `high` (Azure 5-tier, GCP
- SCC 5-tier, GitHub `critical`, ServiceNow priority 1, AWS GuardDuty
- ≥ 8.0, AuditD identity-destruction events, K8s `cluster-admin` bindings,
- Tailscale tailnet lockdown failures) now map straight through in their
- `normalize()` and surface as `critical` in the UI. Confidence
- (`alert.confidence`, int 0–100 with band `low | medium | high`) is now
- decoupled from severity and emitted by `services/fusion`
- `ConfidenceScorer` — operators can sort/filter by either dimension
- independently.
-- **PR-5 / W7 — Investigation Queue workbench.** New `/queue` page is the
- single surface a Tier-1 analyst lives on: server-anchored SLA countdowns
- (clock starts on the server, not the browser), atomic claim semantics
- (`POST /api/v1/queue/{id}/claim` is transactional — two analysts can't
- claim the same row), one-click triage actions (`acknowledge`, `assign`,
- `escalate`, `defer`, `close-as-fp`). Server-driven; the page makes one
- call to `/api/v1/queue` and one call per action. Docs:
- `apps/docs/docs/console/queue.md`.
-- **PR-6 / W8 — Rule Tuning workbench.** New `/detection/tuning` page ranks
- noisy detection rules by precision impact (`fp_volume * tier_weight`) and
- ships one-click suppression + allow-list edits with full audit trail
- through `audit_logs` (every edit captured with `actor`, `actor_ip`,
- `before`, `after`, and the new H-4-hardened hash chain). Backed by
- `GET /api/v1/detection/tuning/recommendations` +
- `POST /api/v1/detection/tuning/apply`. Docs:
- `apps/docs/docs/console/rule-tuning.md`.
-- **PR-7 — Operations funnel + pipeline health.** Two new endpoints land
- together: `GET /metrics/funnel` returns the Detected → Triaged →
- Investigated → Resolved counts plus per-stage MTTRs, and
- `GET /health/pipeline` returns liveness for Kafka / ingest / fusion /
- agents / connectors. The console renders these as a `FunnelKpiBar` above
- the alerts list and a dedicated Efficiency Report on the home dashboard,
- so SOC leads can answer "where are we losing time?" without a Grafana
- detour. Docs: `apps/docs/docs/console/funnel-kpis.md`.
-- **PR-8 — Zero-prerequisite installer.** `install.sh` (POSIX) and
- `install.ps1` (Windows) now bootstrap from a clean machine: they detect
- and install Docker Engine, Docker Compose, Node.js LTS, pnpm, and Python
- 3.11 if any are missing, then run `docker compose -f docker-compose.dev.yml
- up -d`, wait for health, seed the demo data, and print the URL. Both
- scripts are idempotent — re-running them on a working install is a
- no-op. A new `uninstall.sh` does a graduated teardown (containers →
- volumes → images → installed prerequisites, with `--keep-prereqs` /
- `--keep-data` flags). Surfaced as **Path 0** in
- `apps/docs/docs/quickstart.md` and as the recommended installer path on
- `tryaisoc.com`.
-
-All five PRs ship with full Vitest coverage on the new components
-(`TimeWindowProvider`, `TenantSwitcher`, `RoleBadge`, `FunnelKpiBar`,
-`QueueView`, `RuleTuningView`) and full pytest coverage on the new
-endpoints. Test suite remains green: 1 279 backend + 412 frontend tests
-pass.
-
-### Security hardening — Batch 8: `POST /api/v1/alerts/submit`
-
-The `/alerts/submit` ingestion path was a wide-open seam — any caller with
-a valid (or in dev mode, missing) token could POST arbitrary-sized batches
-of events with arbitrary timestamps and unbounded `raw_event` payloads,
-and re-submit the same batch repeatedly to create duplicate alerts. Five
-defences ship together so the path is safe to expose to connectors and the
-`aisoc submit` CLI in production:
-
-- **Payload caps** — three new environment variables bound the request:
- `AISOC_SUBMIT_MAX_EVENTS` (default 1 000 events), `AISOC_SUBMIT_MAX_EVENT_BYTES`
- (default 256 KiB per event after JSON-encoding), and
- `AISOC_SUBMIT_MAX_TOTAL_BYTES` (default 8 MiB for the whole batch). Each
- is enforced before any DB work; over-cap requests return HTTP 413 with the
- exact limit that fired.
-- **Idempotency** — clients can pass an `Idempotency-Key` header (1–128 chars,
- `^[A-Za-z0-9._:/-]+$`); the resulting alert stores it in a new
- `alerts.idempotency_key` column with a partial unique index scoped per
- tenant. A retry with the same key returns the original alert ID (HTTP 200)
- instead of creating a duplicate. Missing header preserves prior behaviour.
- Migration `044_alerts_idempotency_key.sql` adds the column + index.
-- **`raw_event` redaction** — new module `app/services/event_sanitiser.py`
- walks each event and replaces values for keys matching a recursive
- case-insensitive blocklist (`password`, `token`, `secret`, `api_key`,
- `authorization`, `cookie`, `set-cookie`, `client_secret`, `private_key`,
- `bearer`, `session_id`, `csrf`, `x-api-key`) with the string `"[REDACTED]"`.
- Stats (number of redactions, bytes dropped) are emitted to structured logs
- so SOC operators can see whether their connectors are leaking credentials.
-- **Timestamp bounds** — new module `app/services/timestamp_bounds.py` clamps
- every event timestamp to `[now - AISOC_SUBMIT_MAX_TIMESTAMP_AGE_DAYS,
- now + AISOC_SUBMIT_MAX_FUTURE_SECONDS]` (defaults 90 days and 300 s),
- so connectors cannot back-date alerts past retention or future-date them
- past the SLA clock. Clamped events still ingest, but the alert's
- `metadata.timestamp_clamped` counter records how many were rewritten.
-- **Test stability** — `_synthesise_alert_from_events` now calls
- `timestamp_bounds.now_utc()` for clamping, which makes any test using fixed
- fixture timestamps wall-clock dependent. `test_alerts_submit.py` now
- monkeypatches `now_utc` to a pinned `datetime` so CI runs deterministically
- regardless of the current date.
-
-124 new tests across `tests/test_event_sanitiser.py`,
-`tests/test_timestamp_bounds.py`, and the integration coverage in
-`tests/api/v1/endpoints/test_alerts_submit.py` lock the new behaviour in.
-Full suite remains green: 1 279 tests pass with zero regressions.
-
-### Security — audit log integrity (H-4 + M-12)
-
-Hardens the immutable audit log against three distinct trust-boundary
-failures discovered during the bugfix sweep:
-
-- **Spoofable `actor_ip`.** Previous releases lifted `actor_ip` from
- `X-Forwarded-For` unconditionally. Any client able to reach the API
- without a stripping ingress could attach their own header and write an
- arbitrary source IP into compliance-grade audit rows. The new
- `services/api/app/core/trusted_proxy.py` resolves IPs through an
- explicit operator-configured allow-list (`AISOC_TRUSTED_PROXIES`,
- empty by default). When the env var is empty the header is ignored and
- the direct TCP peer is recorded; when set, only requests whose
- immediate peer falls inside the configured CIDR list consult the
- header, and the chain is walked right-to-left to return the closest
- untrusted hop. Both the `emit_audit()` helper
- (`services/api/app/services/audit.py`) and the auto-audit middleware
- (`services/api/app/middleware/audit_middleware.py`) route through this
- resolver.
-- **Secrets leaking into `changes`.** The `changes` payload is now
- passed through `redact_changes()`
- (`services/api/app/services/audit_redaction.py`) before persistence.
- Keys matching case-insensitive sensitive patterns (`password`,
- `secret`, `token`, `api_key`, `private_key`, `*credential*`,
- `authorization`, `bearer`, `cookie`, `session`, `client_secret`, `*_seed`,
- …) are replaced with `***REDACTED***` recursively across dicts, lists
- and tuples. Serialized payloads larger than
- `AISOC_AUDIT_MAX_CHANGES_BYTES` (default 65,536) are substituted with a
- `{ "_truncated": true, "_size": <bytes> }` marker so a single bad
- caller can't balloon the table. Recursion depth and node count are
- capped to prevent DOS via pathological input.
-- **Trigger-bypass tampering.** The append-only trigger on `audit_log`
- doesn't defend against SQL-level access (disabling triggers,
- `TRUNCATE`, credential theft). Migration
- `043_audit_log_hash_chain.sql` adds `prev_hash` / `entry_hash` columns
- (per-tenant SHA-256 chain), and
- `services/api/app/services/audit_hash.py` provides a pure
- `compute_entry_hash()` + `verify_chain()` pair. Both `emit_audit()`
- and the middleware now stamp every new row with the hash of the
- previous tenant row, so any deletion, reorder, or rewrite is
- detectable at audit time. The verifier accepts plain row dicts (e.g.
- from a CSV export) so internal or external auditors can replay the
- chain without DB access. Legacy unchained rows are tolerated at the
- head of a tenant's history; gaps after the chain has started are
- treated as forgery signals.
-
-New env vars (see `apps/docs/docs/deployment/env-vars.md`):
-
-- `AISOC_TRUSTED_PROXIES` — comma-separated CIDR list. Empty by default.
-- `AISOC_AUDIT_MAX_CHANGES_BYTES` — `65536` by default.
-
-80 new unit tests cover the resolver, redactor, and hash chain
-(`test_trusted_proxy.py`, `test_audit_redaction.py`, `test_audit_hash.py`),
-including tamper-detection scenarios (rewritten row, deleted row,
-reordered rows, `prev_hash` / `entry_hash` tampering) and robustness
-under malformed input. No regressions across the existing 1,283-test
-suite.
-
-### Security — bounded eval / playbook timeouts (H-7, batch 10)
-
-- **`POST /detection-proposals/run-eval`** — tightened Pydantic bounds on
- `RunEvalRequest.timeout_seconds` (`le=900` → `le=600`) and
- `max_regression_pp` (`le=100` → `le=50`). The synthetic benchmark completes
- in under 60s on commodity hardware; a 15-minute cap was indistinguishable
- from "no cap" from a DoS standpoint. 50pp regression tolerance is already
- generous — anything higher silently disables the gate. `EvalAttachRequest`
- receives the same `max_regression_pp` cap.
-- **Playbook step bounds** — added strict Pydantic validation to
- `PlaybookStep.timeout_seconds` (`1 ≤ x ≤ 3600s`) and `retry_max` (`0 ≤ x ≤ 25`)
- in `services/agents/app/playbook/models.py`. The 1-hour ceiling
- accommodates human-approval steps; everything else is bounded at runtime.
-- **Runtime parameter clamp** — new module
- `services/agents/app/playbook/bounds.py` centralises `clamp_timeout()` and
- `clamp_retries()` helpers. `_handle_osquery_live_query()` and other
- handlers that read `step.params["timeout_seconds"]` (an untyped dict that
- bypasses Pydantic) now clamp at runtime against
- `ABSOLUTE_MAX_PARAM_TIMEOUT_SECONDS = 900s`. This is the layered defence:
- field validators cap the typed model, runtime clamps cap the dynamic
- params. Operator overrides via `AISOC_PLAYBOOK_MAX_TIMEOUT_SECONDS` /
- `AISOC_PLAYBOOK_MAX_RETRIES` are themselves bounded by the absolute
- ceilings so a typo can't disable the cap entirely.
-- 67 new tests in `services/agents/tests/test_playbook_bounds.py`,
- `test_playbook_models_bounds.py`, and `test_osquery_live_query_step.py`
- exercise pathological values (86 400s, negatives, `True`, numeric strings,
- env-var overrides). 22 new tests in
- `services/api/tests/api/v1/endpoints/test_detection_proposals_request_bounds.py`
- pin the API-side caps.
-
-### Pydantic v2 configuration migration (H-6)
-
-Eliminates the 63+ `PydanticDeprecatedSince20: Support for class-based
-`config` is deprecated, use ConfigDict instead` warnings that were
-emitted on every API/service boot and during every test run.
-
-- **`BaseSettings` → `SettingsConfigDict`** —
- `services/fusion/app/core/config.py` and
- `services/threatintel/app/config.py` now declare `model_config =
- SettingsConfigDict(env_file=…, extra="ignore")` instead of the
- v1-style `class Config: env_file = …` inner class. Behaviour is
- identical; the migration is purely an API surface fix that prevents
- pydantic-settings from emitting a runtime deprecation each time the
- service starts.
-- **`BaseModel` → `ConfigDict`** — every FastAPI endpoint that exposes
- a Pydantic response model with `from_attributes = True` (so SQLAlchemy
- rows can be returned directly) has been migrated to
- `model_config = ConfigDict(from_attributes=True)`. Touches:
- `services/api/app/api/v1/endpoints/{sla,threat_intel,reports,mssp,remediation,identity_graph,insider_threat,assets,posture}.py`
- and `services/ueba/app/api/routes.py`. No schema or wire-format
- changes — `model_dump()`/`from_orm` continue to work as before.
-- **No more silent warnings in CI** — pytest under
- `-W error::DeprecationWarning` (pydantic only) now imports the full
- API surface clean.
-
-### v8.0 architectural foundation — graph at ingest, four-agent rebrand, `/hunt`, sixteen connectors (PR #125)
-
-The biggest single push of the day. The [`AISOC_V8_PROGRESS.md`](AISOC_V8_PROGRESS.md) doc tracks the wave breakdown; this entry is the user-visible summary.
-
-- **Graph at ingest.** `services/ingest` now writes a Neo4j-backed entity graph (`User`, `Asset`, `Process`, `IP`, `Domain`, `Alert`) as events flow through the normaliser, instead of deferring graph construction to a downstream batch job. The new `services/ingest/internal/graph/` package, the [`architecture/graph-schema`](apps/docs/docs/architecture/graph-schema.md) doc, and the [`Graph at ingest` blog post](apps/web/content/blog/graph-at-ingest.mdx) all describe the schema. Latency budget on the ingest path is unchanged (graph writes are fire-and-forget with a bounded retry queue).
-- **Four-agent rebrand.** The legacy `triage_agent` is split into purpose-built agents — `DetectAgent`, `TriageAgent`, `HuntAgent`, `RespondAgent` — each owning a clear stage of the funnel (detect → triage → hunt → respond). The funnel KPI doc ([`console/funnel-kpis`](apps/docs/docs/console/funnel-kpis.md)) explains how each stage is measured and where the agents plug in. Existing playbooks continue to work via a thin compatibility shim on the orchestrator graph.
-- **`/hunt` natural-language hunting interface.** A new console route lets analysts ask English questions ("which users authenticated from a country they've never logged in from in the past 90 days?") and get a graph-aware answer with `pivotPath` deep-links into the Investigation Rail. Backed by `HuntAgent` plus a curated set of ES|QL / Cypher templates so the LLM never writes raw queries by itself.
-- **Sixteen first-party connectors.** Hardened, marketplace-listed, and individually documented under [`apps/docs/docs/connectors/*`](apps/docs/docs/connectors). All five severity tiers (`info | low | medium | high | critical`) are now preserved end-to-end — see the per-connector docs for the vendor-native → AiSOC severity mapping table.
-- **Automation maturity model.** New [`automation-maturity`](apps/docs/docs/concepts/automation-maturity.md) doc and [companion blog post](apps/web/content/blog/automation-maturity.mdx) define the L0–L4 ladder (manual triage → fully autonomous closure with human sign-off) and how each AiSOC capability maps onto it.
-- **Public weekly benchmark scoreboard.** Already documented above; this is its anchoring release.
-
-`AISOC_V8_PROGRESS.md` lists wave-2 items that are checkpointed but not yet merged. Until the wave-2 work lands, the `VERSION` file stays at `7.3.1` and v8.0 lives entirely under `[Unreleased]`.
-
-### Security hardening — critical/high severity wave
-
-Eight PRs landing the C-1, C-2, P2-A1, P2-W1, P2-W7, H-3, H-8, and M-9 items from the security hardening plan. Each one is small in diff but plugs a class of bug, so they're grouped here for the changelog:
-
-- **C-1 — rule engine `eval()` RCE removed (PR #116).** The detection rule evaluator no longer compiles user-supplied condition strings via `eval()` / `compile()`. Conditions are parsed into an AST with a whitelisted set of operators, attribute accesses, and constants; everything else is rejected at rule-save time, not at evaluation time. Existing rules that used arithmetic, comparisons, `and`/`or`/`not`, and `event.field` lookups continue to work unchanged.
-- **C-2 — hunts tenant isolation (PR #117).** Saved hunts, hunt results, and the `/hunt` natural-language endpoint now all filter by `tenant_id` at the query layer instead of relying on RLS alone, eliminating a class of cross-tenant read bugs that surfaced when service-role keys touched the table directly.
-- **P2-A1 — CORS lockdown across all services (PR #119).** Shared `cors.py` helper, vendored byte-identical into every Python service, refuses to start if `AISOC_CORS_ORIGINS` contains `*` while credentials are enabled and `AISOC_ENV=production`. TypeScript guard in `services/realtime/src/index.ts` enforces the same rule for the WebSocket service. Full rationale is in [`operations/security.md` → CORS](apps/docs/docs/operations/security.md#cors).
-- **P2-W1 — cases tenant isolation (PR #118).** Same shape as C-2 but for the cases service: `case_id` lookups, attachments, comments, and audit events now all go through tenant-scoped queries.
-- **P2-W7 — SSRF guard for playbook `http_request` and `notify` (PR #120).** New `services/agents/app/playbook/ssrf_guard.py` validates every outbound URL: scheme allow-list, no embedded credentials, hostname resolution + IP allow-list with cloud-metadata block list that applies even when private IPs are explicitly allowed. Documented under [`operations/security.md` → Playbook outbound traffic](apps/docs/docs/operations/security.md#playbook-outbound-traffic--ssrf-guard).
-- **H-3 — plugin manager OCI install hardening (PR #121).** Plugin manifests fetched from an OCI registry are now verified against a signed-manifest allow-list before any file lands on disk; image digests are pinned at install time and re-verified on every load. Eliminates the "swap-tag-after-review" supply-chain pattern.
-- **H-8 / P2-A3 — dev-mode unification (PR #127).** Replaces the per-service patchwork of `if DEV_MODE` / `if SKIP_AUTH` / `if AISOC_DEMO_MODE` branches with one canonical helper that returns the dev-mode posture from a single env var (`AISOC_DEV_MODE`). Production deployments where this flag is unset get exactly zero auth-bypass codepaths compiled in. Tested with a new `tests/test_security_defaults.py` that imports every service and asserts no dev-mode shortcut is reachable when the flag is off.
-- **M-9 — LLM input sanitization for untrusted enrichment (PR #128).** Threat-intel enrichment text returned from third-party feeds is run through a prompt-injection filter (boundary markers, control-character stripping, length cap) before being concatenated into any LLM prompt. The filter is centralised in `services/api/app/services/llm_safety.py` and re-used by every prompt builder.
-
-The matching docs under [`apps/docs/docs/operations/security.md`](apps/docs/docs/operations/security.md) were updated as part of each PR so the security model page is the single source of truth.
-
-### Static analysis — Python CodeQL alerts driven to zero on `main` (PRs #133, #136, #137)
-
-A three-PR sweep that resolves every open Python CodeQL alert in the repository and makes the resulting state easy to maintain.
-
-- **PR #133 — 30 alerts in one pass.** Covers `py/log-injection` (alerts #396, #401, #402, #412), `py/uninitialized-local-variable` (#414, #415), `py/side-effect-in-assert` (#435), `py/incomplete-url-substring-sanitization` (#411), `py/ineffectual-statement` for `...`-only `Protocol` stubs and bare `await task` statements (#418–#434, #422, #424, #425, #429), `py/unnecessary-lambda` (#439), `py/mixed-returns` (#438), `py/unused-global-variable` (#408, #416, #417), and `py/unused-import` (#436). Sanitisation, where applied, is now inline at the call site (`.replace("\r", "").replace("\n", " ")[:N]`) so the taint tracker recognises it without needing a `nosec`/`noqa` hint.
-- **PR #136 — final two stubborn alerts.** CodeQL flagged `#440` (`py/import-and-import-from` in `services/connectors/tests/connectors/test_confluence_audit.py`) and `#441` (`py/log-injection` in `services/api/app/api/v1/endpoints/waitlist.py`) even after PR #133 because (a) the taint tracker didn't follow our `_log_safe` helper through the call site, and (b) the test file used a module alias _and_ a from-import for the same module. Fix: drop the helper, inline the sanitisation, and use `pytest.MonkeyPatch.setattr` instead of a module alias.
-- **PR #137 — newly-introduced alert #442.** Once #441 was resolved, CodeQL surfaced a new log-injection alert on `entry_id` and `user.user_id` in the same waitlist endpoint, even though both are `uuid.UUID`-typed. Made the cleansing explicit at the call site (`str(entry_id).replace("\r", "").replace("\n", " ")[:36]`) so future readers — and CodeQL — see the guarantee, even though the underlying values are safe by type.
-
-After PR #137 merged, the [CodeQL dashboard](https://github.com/beenuar/AiSOC/security/code-scanning) reports zero open Python alerts on `main`. The full sanitisation pattern is documented in [`operations/security.md` → Static analysis (CodeQL)](apps/docs/docs/operations/security.md#static-analysis-codeql).
-
-### UEBA service environment variable alignment (PR #135, first community contribution)
-
-Resolves [Issue #134](https://github.com/beenuar/AiSOC/issues/134) — the `ueba` service was the only Python service that required a `UEBA_` prefix on every env var, which broke the `DATABASE_URL` / `KAFKA_BOOTSTRAP_SERVERS` / `REDIS_URL` exports in `docker-compose.yml` (and silently fell back to defaults).
-
-- **`services/ueba/app/core/config.py`** — `model_config` drops `env_prefix="UEBA_"` and adds `populate_by_name=True`. Every field is now declared with `Field(default=…, validation_alias=AliasChoices("UNPREFIXED", "UEBA_PREFIXED"))`, so both names work and the unprefixed form wins when both are set. Pattern matches the `services/fusion/app/core/config.py` already used elsewhere in the repo.
-- **`services/ueba/alembic/env.py`** — `os.environ.get("DATABASE_URL") or os.environ.get("UEBA_DATABASE_URL", default)`, so `alembic upgrade head` picks up the same DSN the running service sees.
-- **`services/ueba/tests/test_config.py`** — new test file with a `_clean_env` autouse fixture that scrubs both prefixed and unprefixed names, then asserts the four cases (unprefixed-only / prefixed-only / both-with-unprefixed-winning / neither-with-default-fallback) for both `DATABASE_URL` and `KAFKA_BOOTSTRAP_SERVERS`. All four tests pass under `pytest services/ueba/tests/test_config.py`.
-
-[`deployment/env-vars.md` → UEBA service](apps/docs/docs/deployment/env-vars.md#ueba-service-servicesueba) now documents the dual-alias behaviour and lists the unprefixed names as canonical.
-
-### Issues #131 and #130 — security smoke + UX cleanup (PR #132)
-
-Two reported issues, one combined fix.
-
-- **#131 — security smoke test.** New test in `services/api/tests/test_security_defaults.py` walks every API endpoint and asserts that no dev-mode auth bypass is reachable when `AISOC_DEV_MODE` is unset. Catches regressions from the dev-mode unification (H-8) above.
-- **#130 — UX cleanup.** `idempotency_key`, `payload.connector_type`, and `provider` no longer leak unsanitised user input into structured logs; the inline sanitisation pattern (`replace("\r", "").replace("\n", " ")[:N]`) is now used uniformly across the alerts, effective-permissions, and waitlist endpoints. Also fixes the duplicated `[Unreleased]` heading in CHANGELOG that #130 reported.
-
-### Playbook engine — correctness pass (PR #129)
-
-Tightens the playbook engine so failures stay local instead of cascading.
-
-- **Bounded eval / playbook timeouts (H-7).** Already documented above as a separate `[Unreleased]` entry; this PR is the implementation.
-- **Saga-style error handling.** `services/agents/app/playbook/runner.py` now wraps each step in an explicit try/except that captures `asyncio.CancelledError` separately from playbook-level errors, so an operator-issued cancel doesn't masquerade as a step failure in the audit log.
-- **Tests.** Twelve new tests in `services/agents/tests/test_playbook_runner.py` cover happy path, single-step failure, cascading failure with rollback, cancellation, and the three SSRF guard rejection paths.
-
-## [7.3.1] — 2026-05-14
-
-### Smoke-test hotfix — `/api/v1/alerts` works on a fresh clone
-
-Tail end of the v7.3.0 founder-flow smoke test on a clean machine revealed
-three latent issues that broke the "open the console, see your alert"
-moment in the demo. This patch closes all three.
-
-- **Alerts table schema drift** — the `Alert` ORM model
- (`services/api/app/models/alert.py`) declared eleven columns that no
- migration had ever added to the database: `affected_ips`,
- `affected_hosts`, `affected_users`, `affected_assets`,
- `parent_alert_id`, `child_alert_ids`, `is_merged`, `assigned_to_id`,
- `assigned_at`, `enrichment_data`, `tags`. Result: a fresh stack
- returned HTTP 500 from `GET /api/v1/alerts` with
- `column alerts.affected_ips does not exist`. New idempotent migration
- `042_alerts_schema_drift_fix.sql` adds all eleven with sensible
- defaults (`'[]'::jsonb`, `'{}'::jsonb`, `FALSE`, `NULL`).
-- **Migration idempotency** — `005_compliance.sql` and
- `025_connectors_click_and_connect.sql` failed re-application on
- partially-migrated DBs (a `CREATE POLICY` that didn't check for
- existence, and a chain of `ALTER TABLE … RENAME COLUMN` calls that
- threw when the source columns were already renamed). Both now wrap
- the offending statements in `DO $$ … END $$` blocks gated on
- `pg_policies` / `information_schema.columns` lookups, so
- `aisoc db upgrade` is fully idempotent.
-- **`aisoc submit` → console wiring** — the v7.3.0 CLI POSTed to
- `services/ingest`'s `/v1/ingest/batch`, which only emits to Kafka. With
- the detection / correlation pipeline still wiring up in the demo
- environment, accepted events never became `Alert` rows, so the web
- console stayed empty. New endpoint
- `POST /api/v1/alerts/submit` in `services/api/app/api/v1/endpoints/alerts.py`
- synthesises one `Alert` row directly from the event batch (severity
- normalised across the canonical five-tier ladder, MITRE / affected
- entities derived from the OCSF payload) and persists it. The CLI
- (`packages/aisoc-cli/src/aisoc_cli/main.py`) now targets that endpoint,
- with the same `--tenant` / `--connector-id` / `--source-format`
- overrides, plus dev-mode auth bypass when no `Authorization` header is
- supplied. 16 CLI tests + 48 API tests cover request shape, severity
- mapping, timestamp coercion (`@timestamp` / `time` / Okta `published`),
- affected-user deduplication, and JSONB column defaults.
-
-After this hotfix, the recorded demo runs end-to-end on a fresh clone:
-`docker compose up`, `aisoc db upgrade` (clean — no failures),
-`aisoc submit examples/alerts/lateral-movement.json` (201, `alert_id`
-returned), and the Web console at `http://127.0.0.1:3000/alerts` lists
-the new alert with no 500s.
-
-## [7.3.0] — 2026-05-14
-
-### Founder-flow series — codebase aligned to the screen-recording demo (PR1–PR7)
-
-The recorded "fresh-clone to first alert" demo now runs verbatim on `main`.
-Seven dependency-ordered PRs landed the missing surface area the script
-walked through, plus the docs path that mirrors it.
-
-- **PR1 — `docker-compose.dev.yml`** (`docker-compose.dev.yml`): new alias
- file that `include`s `docker-compose.yml` via the Compose Spec, so the
- `docker compose -f docker-compose.dev.yml up -d` step in the demo no
- longer 404s on a fresh clone.
-- **PR2 — `.env.example` cleanup** (`.env.example`, `docker-compose.yml`,
- `services/api/app/core/config.py`): standalone `POSTGRES_PASSWORD`,
- pre-filled `AISOC_CREDENTIAL_KEY` (Fernet), explicit required-vars
- header. `DATABASE_URL` and the Postgres service now share the same
- default secret so first-run no longer hits a password mismatch.
-- **PR3 — `scripts/run_evals.py` CLI contract** (`scripts/run_evals.py`,
- `scripts/tests/test_run_evals_cli.py`): real `--suite` flag with
- per-suite runners, `PASS/FAIL` banners, and a graceful `ImportError`
- hint when the eval substrate isn't installed. The video step
- `python scripts/run_evals.py --suite all` now does what the voice-over
- claims.
-- **PR4 — `aisoc serve` / `aisoc db upgrade` / `aisoc mcp serve` /
- `aisoc mcp install`** (`packages/aisoc-cli/src/aisoc_cli/main.py`,
- `packages/aisoc-cli/tests/test_ops_commands.py`): four new operator
- subcommands that wrap `docker compose`, the SQL migration runner, and
- the MCP Node entrypoint. `aisoc mcp install` writes the right config
- block for `cursor`, `claude`, or `continue`. 12 CLI surface tests
- cover argv construction, exit-code propagation, missing-Docker handling,
- local-`dist` vs. `npx @aisoc/mcp` fallback, and host-choice validation.
-- **PR5 — `aisoc submit` + lateral-movement fixture**
- (`packages/aisoc-cli/src/aisoc_cli/main.py`,
- `packages/aisoc-cli/tests/test_submit_command.py`,
- `examples/alerts/lateral-movement.json`): POSTs a JSON fixture to the
- ingest service's `/v1/ingest/batch` with the `X-Tenant-ID` header that
- `services/ingest/internal/handler/handler.go` requires. Fixture-level
- `connector_id` / `connector_type` / `source_format` overrides are
- honored; CLI flags + env vars (`AISOC_INGEST_URL`, `AISOC_TENANT_ID`)
- override the fixture. The shipped fixture is an Okta System Log
- impossible-travel scenario (NYC → St. Petersburg, 8 minutes apart) that
- routes through the `okta_system_log` profile (OCSF class_uid 3002).
- 14 CLI tests use `httpx.MockTransport` for the full request/response
- matrix including 400/500, transport errors, and malformed JSON.
-- **PR6 — quickstart Path C** (`apps/docs/docs/quickstart.md`): the
- founder-style CLI walkthrough the demo follows, with a single-screen
- cheat sheet. Path A (`pnpm aisoc:demo`) and Path B (raw `docker compose`)
- are unchanged.
-- **PR7 — version bump** (this commit): `VERSION` file at repo root +
- `apps/web/package.json` bumped 7.2.0 → 7.3.0. CHANGELOG section
- promoted from `[Unreleased]` to `[7.3.0]`.
-
-### Alerts console — Investigation Rail & correlation narrative (v1.5 W6 / PR-4)
-
-The `/alerts` queue is now a two-pane workbench: the existing queue on the left and an **Investigation Rail** on the right. Selecting a row hydrates narrative, related entities (with pivot links), a six-event mini-timeline, and structured recommended actions — no drawer hop for first-pass triage.
-
-- **`services/fusion`** — `fusion_engine` emits a deterministic **correlation narrative** at fuse time; `narrative.py` mirrors the vendored builder shared with the API.
-- **`services/api`** — `alert_rail.py` builds the rail payload; `narrative_projection.py` + `narrative_loader.py` back-fill legacy alerts on first `GET /api/v1/alerts/{id}`; migration `041_alert_correlation_narrative.sql` stores cached narrative on the alert row; OpenAPI + tests extended for the detail envelope.
-- **`apps/web`** — `InvestigationRail.tsx` + `AlertsView.tsx` integration; Vitest coverage in `InvestigationRail.test.tsx`.
-- **`apps/docs/docs/console/investigation-rail.md`** — operator/analyst guide; sidebar entry under Console.
-- **`scripts/sync_vendored_narrative.py`** — keeps `services/api/app/_vendor/narrative.py` aligned with fusion.
-
### Connectors — Wazuh Indexer ingest (Stage 2)
New first-class endpoint connector for Wazuh deployments. AiSOC now polls the
diff --git a/README.md b/README.md
index 5bbef25ce..bb6ffb9a8 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@ An open-source, self-hostable AI SOC. The agent's prompts, tool calls, and ratio
[![License: MIT](https://img.shields.io/badge/License-MIT-22c55e.svg?style=flat-square)](https://opensource.org/licenses/MIT)
[![Public eval harness: CI-gated](https://img.shields.io/badge/eval%20harness-CI--gated-2563eb?style=flat-square)](apps/docs/docs/benchmark.md)
[![PRs welcome](https://img.shields.io/badge/PRs-welcome-8b5cf6?style=flat-square)](CONTRIBUTING.md)
-[![Version](https://img.shields.io/badge/version-7.3.1-f59e0b?style=flat-square)](CHANGELOG.md)
+[![Version](https://img.shields.io/badge/version-7.1.0-f59e0b?style=flat-square)](CHANGELOG.md)
[![Live demo on Fly.io (v8.0 launch)](https://img.shields.io/badge/Live%20demo-Fly.io-7b2bbe?style=flat-square&logo=fly-dot-io&logoColor=white)](https://demo.aisoc.dev)
[![Render demo (one-click)](https://img.shields.io/badge/Render%20demo-one%20click-46e3b7?style=flat-square&logo=render&logoColor=white)](https://render.com/deploy?repo=https://github.com/beenuar/AiSOC)
diff --git a/apps/docs/docs/operations/managed-instance.md b/apps/docs/docs/operations/managed-instance.md
new file mode 100644
index 000000000..4b14a4b34
--- /dev/null
+++ b/apps/docs/docs/operations/managed-instance.md
@@ -0,0 +1,205 @@
+---
+sidebar_position: 13
+title: Managed instance (app.aisoc.dev)
+description: How the AiSOC managed beta works — what's deployed, how a customer is onboarded, SLAs, and billing.
+---
+
+# Managed instance (`app.aisoc.dev`)
+
+AiSOC is open source and self-hostable, but for teams who want a SOC up
+and running today — without owning the infrastructure — we run a
+**managed beta** at [`app.aisoc.dev`](https://app.aisoc.dev). This page
+documents how it works, who it's for, and the operational shape of the
+offering.
+
+> **Status: invite-only beta.** Capacity is rationed deliberately so we
+> can keep response times tight and feedback loops short with each
+> customer. To join the queue, submit the form at
+> [`app.aisoc.dev/waitlist`](https://app.aisoc.dev/waitlist).
+
+## At a glance
+
+| Property | Value |
+|---|---|
+| **Hostname** | `app.aisoc.dev` (TLS terminated at Cloudflare) |
+| **Hosted on** | Fly.io (single app, multi-process) |
+| **Database** | Fly managed Postgres — primary + standby, PITR enabled |
+| **Cache / pubsub** | Fly managed Redis (Upstash-backed) |
+| **Region** | `iad` (US-East) by default; bespoke regions available on request |
+| **Tenancy model** | Multi-tenant; each customer is a row in `tenants` with row-level isolation |
+| **Identity** | Email + magic-link invites; SSO available on the higher tiers |
+| **Source of truth** | This repository (`apps/`, `services/`, `detections/`) |
+| **Bootstrap stack** | [`infra/terraform/environments/managed/`](https://github.com/beenuar/AiSOC/tree/main/infra/terraform/environments/managed) |
+
+## Why a managed offering at all
+
+The same code runs in three places:
+
+1. **Self-hosted** — `docker compose up`, fully air-gappable, you own the
+ keys and the data. This is the canonical AiSOC deployment.
+2. **BYOC** — Terraform stack in `infra/terraform/byoc/` provisions
+ AiSOC into the customer's own AWS account.
+3. **Managed (`app.aisoc.dev`)** — same code, hosted by the AiSOC
+ community on Fly.io. This is where the waitlist points.
+
+The managed offering exists for one reason: **letting a team try a
+real SOC before they own the operational burden**. Once they've
+validated the workflow they can graduate to BYOC or self-hosted
+without touching any code — the migration is a `pg_dump` and a
+`fly secrets export`.
+
+## Architecture
+
+Each managed AiSOC deployment is a single Fly.io application with five
+process groups defined in `fly.toml`:
+
+| Process group | Source | Role |
+| ------------- | ----------------------- | ---------------------------------------------------------- |
+| `web` | `apps/web` | Next.js console |
+| `api` | `services/api` | FastAPI control plane (auth, RBAC, REST + GraphQL surface) |
+| `agents` | `services/agents` | Investigator orchestrator (LangGraph) |
+| `realtime` | `services/realtime` | WebSocket fan-out for live dashboards |
+| `connectors` | `services/connectors` | Connector polling scheduler |
+
+All five processes share the same Postgres + Redis. Tenant isolation is
+enforced at the application layer (every query is scoped by
+`tenant_id`) and at the database layer (`ROW LEVEL SECURITY` policies
+on tenant-scoped tables, set by `app.current_tenant`).
+
+The Cloudflare edge in front of Fly.io handles:
+
+- TLS termination (managed certificate)
+- DDoS protection
+- The basic WAF ruleset (we explicitly do **not** block AI-agent
+ traffic — many customers integrate via the SDK)
+
+## How a customer is onboarded
+
+End-to-end this is a five-step flow. Every step has an audit-log entry.
+
+1. **Customer fills the waitlist form** at
+ [`app.aisoc.dev/waitlist`](https://app.aisoc.dev/waitlist). The POST
+ hits `/v1/waitlist/signup`, rate-limited per IP, and the entry lands
+ in `aisoc_waitlist_entries` with status `new`.
+2. **The waitlist Slack notification** fires to the sales channel via
+ `AISOC_WAITLIST_SLACK_WEBHOOK`. The Slack message links straight to
+ `/admin/waitlist` for triage.
+3. **An operator reviews the entry** in
+ [`/admin/waitlist`](https://app.aisoc.dev/admin/waitlist) and
+ transitions the status from `new` → `contacted` once they've reached
+ out, then `contacted` → `onboarded` (or `declined`) once the
+ conversation has closed.
+4. **Promote to tenant.** The operator clicks "Promote to tenant" on
+ the entry, which calls `POST /v1/admin/tenants/provision`. The
+ provisioner (`services/api/app/services/tenant_provision/`):
+ - Allocates a unique tenant slug derived from the company name.
+ - Generates a fresh Fernet `aisoc_credential_key` for that tenant
+ and stores the **fingerprint** in `tenants.settings`. The
+ plaintext key is never persisted; the operator copies it into
+ `fly secrets set` as part of the bootstrap.
+ - Seeds the default RBAC roles, starter detections, and seed
+ playbooks from
+ `services/api/app/services/tenant_provision/templates.py`.
+ - Seeds the demo investigations from `app/scripts/seed_demo.py`
+ so the first login lands on a populated dashboard.
+ - Creates an admin user record for the customer's primary contact
+ and returns a magic-link invite URL.
+5. **Customer signs in** via the invite link and is dropped on a
+ pre-populated dashboard. From there they configure connectors,
+ invite teammates, and start running real investigations.
+
+The waitlist entry stays linked to the tenant (`tenants.provisioned_from_waitlist_id`)
+so support can always trace a live tenant back to the original
+conversation.
+
+## What's *not* part of the managed offering
+
+A few capabilities are intentionally **only** available in self-hosted
+or BYOC deployments:
+
+- **Bring-your-own LLM credentials with full per-call attribution.**
+ The managed beta uses a shared LLM pool, so per-tenant cost
+ attribution is best-effort, not exact. Customers who need
+ audit-grade attribution should graduate to BYOC where the LLM keys
+ live in their account and every call is in their CloudTrail.
+- **Air-gapped deployments.** The managed beta is internet-facing by
+ definition. The [air-gap runbook](/docs/operations/air-gapped) applies to
+ self-hosted deployments only.
+- **Custom data residency.** Region selection on the managed plan is
+ limited to whatever Fly.io supports; if you need data residency
+ outside that list, BYOC is the answer.
+
+## SLAs
+
+The managed beta runs on a best-effort basis. Specifically:
+
+| Metric | Beta target |
+| ---------------------------- | ---------------------- |
+| Console availability | 99.0% / 30-day window |
+| API availability | 99.0% / 30-day window |
+| First-touch waitlist response| 5 business days |
+| Critical security incident response | < 24 hours |
+
+These are **targets, not contractual SLAs**. Customers who need a
+written SLA should engage about BYOC or a paid managed tier — the
+contact form for that lives at the bottom of
+[`tryaisoc.com`](https://tryaisoc.com).
+
+## Billing and cost transparency
+
+The managed beta is free during the beta period. We're not running a
+land-grab pricing experiment — we're trying to figure out what an
+honest unit economic looks like for a SOC product, and we'd rather do
+that with a small cohort of design partners than with a public price
+sheet that we have to walk back later.
+
+What we **do** care about is making LLM cost visible from day one. The
+[LLM cost dashboard](https://app.aisoc.dev/costs) (rolled out as WS-H1 of
+the v1.0 buyer-value plan) tracks every model call with token counts,
+provider, and run cost, scoped per tenant. When the beta exits and
+pricing lands, that dashboard is what we'll bill against — so
+customers can see the bill being built in real-time today.
+
+## Operator runbook (for the AiSOC community)
+
+If you're operating the managed instance yourself, the relevant
+runbooks live here:
+
+- **Bootstrapping new infrastructure** —
+ [`infra/terraform/environments/managed/README.md`](https://github.com/beenuar/AiSOC/blob/main/infra/terraform/environments/managed/README.md)
+ walks through `terraform init` / `plan` / `apply`, the `fly attach`
+ /`fly secrets` / `fly deploy` sequence, and the post-apply
+ smoke-test commands.
+- **Rotating the credential vault key** —
+ [`/operations/credentials`](/docs/operations/credentials) documents the
+ `MultiFernet` rotation procedure. Run this once per quarter and
+ always before offboarding an operator who had access to the
+ current key.
+- **Air-gap parity** — the same code runs air-gapped (see
+ [`/operations/air-gapped`](/docs/operations/air-gapped)). Every feature
+ that ships to the managed instance is regression-tested against
+ the air-gapped overlay so a customer can leave the managed
+ offering at any time without re-validating the security story.
+- **Audit log export for compliance** — `POST /v1/audit/export`
+ generates a signed CSV + HTML bundle for any 24h window. Run this
+ monthly as part of the managed-instance compliance cadence.
+
+## When to graduate
+
+The managed beta is a great starting point, but it's not where most
+serious AiSOC deployments live in steady state. Move to BYOC or
+self-hosted when **any** of the following becomes true:
+
+- You need a contractual SLA, not a target.
+- Your alerts touch PII or regulated data that can't leave your VPC.
+- You want exact per-call LLM cost attribution against your own
+ provider account.
+- You want air-gapped deployment with the local-LLM overlay.
+- You want to fork the codebase for tenant-specific detection
+ content.
+
+The migration is mechanical: `pg_dump` your tenant's data, run the
+matching `pg_restore` against your BYOC Postgres, point the BYOC
+control plane at the same Fernet key, and update your DNS. The
+managed instance does nothing exotic that wouldn't survive the
+round trip.
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index d26ac7bc7..54447cb9c 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -116,6 +116,7 @@ const sidebars: SidebarsConfig = {
"operations/troubleshooting",
"operations/faq",
"operations/adoption-questions",
+ "operations/managed-instance",
],
},
{
diff --git a/apps/web/package.json b/apps/web/package.json
index b85eeb114..345a3392d 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -33,6 +33,7 @@
"react-hot-toast": "^2.4.1",
"recharts": "^2.10.3",
"swr": "^2.2.4",
+ "tailwind-merge": "^3.6.0",
"zustand": "^5.0.13"
},
"devDependencies": {
diff --git a/apps/web/src/app/(app)/dashboards/soc-insights/page.tsx b/apps/web/src/app/(app)/dashboards/soc-insights/page.tsx
index 70c888f88..2efdc4c99 100644
--- a/apps/web/src/app/(app)/dashboards/soc-insights/page.tsx
+++ b/apps/web/src/app/(app)/dashboards/soc-insights/page.tsx
@@ -23,7 +23,7 @@
import { SOCInsightsView } from '@/components/soc-insights/SOCInsightsView';
export const metadata = {
- title: 'SOC Insights',
+ title: 'SOC Insights | AiSOC',
};
export default function SOCInsightsPage() {
diff --git a/apps/web/src/app/(app)/identity/permissions/page.tsx b/apps/web/src/app/(app)/identity/permissions/page.tsx
index 0f40ec417..532e68eab 100644
--- a/apps/web/src/app/(app)/identity/permissions/page.tsx
+++ b/apps/web/src/app/(app)/identity/permissions/page.tsx
@@ -11,7 +11,7 @@
import EffectivePermissionsClient from './EffectivePermissionsClient';
export const metadata = {
- title: 'Effective Permissions',
+ title: 'Effective Permissions | AiSOC',
};
export default function EffectivePermissionsPage() {
diff --git a/apps/web/src/app/(app)/investigate/page.tsx b/apps/web/src/app/(app)/investigate/page.tsx
index 302da47b6..90baa5658 100644
--- a/apps/web/src/app/(app)/investigate/page.tsx
+++ b/apps/web/src/app/(app)/investigate/page.tsx
@@ -16,7 +16,7 @@
import { permanentRedirect } from "next/navigation";
export const metadata = {
- title: "Investigate",
+ title: "Investigate | AiSOC",
};
interface InvestigatePageProps {
diff --git a/apps/web/src/app/(app)/settings/business-context/page.tsx b/apps/web/src/app/(app)/settings/business-context/page.tsx
index c4c622ed9..b7420b4ec 100644
--- a/apps/web/src/app/(app)/settings/business-context/page.tsx
+++ b/apps/web/src/app/(app)/settings/business-context/page.tsx
@@ -20,7 +20,7 @@ import type { Metadata } from "next";
import { BusinessContextSettings } from "./BusinessContextSettings";
export const metadata: Metadata = {
- title: "Business Context Rules | Settings",
+ title: "Business Context Rules | Settings | AiSOC",
};
export default function BusinessContextSettingsPage() {
diff --git a/apps/web/src/app/(marketing)/blog/[slug]/page.tsx b/apps/web/src/app/(marketing)/blog/[slug]/page.tsx
index bdbe5fb04..16f4699af 100644
--- a/apps/web/src/app/(marketing)/blog/[slug]/page.tsx
+++ b/apps/web/src/app/(marketing)/blog/[slug]/page.tsx
@@ -34,10 +34,10 @@ export async function generateMetadata({
}): Promise<Metadata> {
const { slug } = await params;
const post = getPostBySlug(slug);
- if (!post) return { title: 'Post not found' };
+ if (!post) return { title: 'Post not found — AiSOC' };
const fm = post.frontmatter;
return {
- title: fm.title,
+ title: `${fm.title} — AiSOC blog`,
description: fm.description,
alternates: { canonical: `/blog/${slug}` },
openGraph: {
diff --git a/apps/web/src/app/(marketing)/blog/page.tsx b/apps/web/src/app/(marketing)/blog/page.tsx
index 53c3bc725..2d6f86f5d 100644
--- a/apps/web/src/app/(marketing)/blog/page.tsx
+++ b/apps/web/src/app/(marketing)/blog/page.tsx
@@ -15,7 +15,7 @@ import { formatPostDate, listPosts } from '@/lib/blog';
*/
export const metadata: Metadata = {
- title: 'Engineering blog',
+ title: 'Engineering blog — AiSOC',
description:
'Long-form, technical writing from the team building AiSOC: graph-at-ingest, sub-minute investigation latency, the L0–L4 SOC automation maturity model.',
alternates: { canonical: '/blog' },
@@ -58,12 +58,10 @@ export default function BlogIndexPage() {
<div className="mx-auto max-w-5xl">
{hasPosts ? (
<ul className="grid gap-4 md:grid-cols-2">
- {posts.map((p) => {
- const safeSlug = encodeURIComponent(p.slug);
- return (
- <li key={safeSlug}>
+ {posts.map((p) => (
+ <li key={p.slug}>
<Link
- href={`/blog/${safeSlug}`}
+ href={`/blog/${p.slug}`}
className="group flex h-full flex-col rounded-2xl border border-white/10 bg-white/[0.02] p-6 transition hover:border-white/20 hover:bg-white/[0.04]"
>
<div className="flex flex-wrap items-center gap-2">
@@ -102,8 +100,7 @@ export default function BlogIndexPage() {
</div>
</Link>
</li>
- );
- })}
+ ))}
</ul>
) : (
<div className="rounded-2xl border border-white/10 bg-white/[0.02] p-10 text-center">
diff --git a/apps/web/src/app/(marketing)/customers/[slug]/page.tsx b/apps/web/src/app/(marketing)/customers/[slug]/page.tsx
index ee056efc9..af5547420 100644
--- a/apps/web/src/app/(marketing)/customers/[slug]/page.tsx
+++ b/apps/web/src/app/(marketing)/customers/[slug]/page.tsx
@@ -39,11 +39,11 @@ export async function generateMetadata({
const { slug } = await params;
const study = getCustomerBySlug(slug);
if (!study) {
- return { title: 'Customer not found' };
+ return { title: 'Customer not found — AiSOC' };
}
const fm = study.frontmatter;
return {
- title: `${fm.title} — customer story`,
+ title: `${fm.title} — AiSOC customer story`,
description: fm.challenge,
alternates: { canonical: `/customers/${slug}` },
openGraph: {
diff --git a/apps/web/src/app/(marketing)/customers/page.tsx b/apps/web/src/app/(marketing)/customers/page.tsx
index 7085b4085..2fca83ff2 100644
--- a/apps/web/src/app/(marketing)/customers/page.tsx
+++ b/apps/web/src/app/(marketing)/customers/page.tsx
@@ -12,7 +12,7 @@ import { listCustomers } from '@/lib/customers';
*/
export const metadata: Metadata = {
- title: 'Customers',
+ title: 'Customers — AiSOC',
description:
'Reference customers running AiSOC in production: who they are, the security challenge, and the measurable outcome.',
alternates: { canonical: '/customers' },
@@ -58,11 +58,10 @@ export default function CustomersIndexPage() {
<div className="grid gap-4 md:grid-cols-2">
{studies.map((s) => {
const stats = s.frontmatter.result_numbers ?? [];
- const safeSlug = encodeURIComponent(s.slug);
return (
<Link
- key={safeSlug}
- href={`/customers/${safeSlug}`}
+ key={s.slug}
+ href={`/customers/${s.slug}`}
className="group flex h-full flex-col rounded-2xl border border-white/10 bg-white/[0.02] p-6 transition hover:border-white/20 hover:bg-white/[0.04]"
>
<div className="flex items-center gap-3">
diff --git a/apps/web/src/app/(marketing)/sovereign/page.tsx b/apps/web/src/app/(marketing)/sovereign/page.tsx
index 93fac2be9..e0567b0d5 100644
--- a/apps/web/src/app/(marketing)/sovereign/page.tsx
+++ b/apps/web/src/app/(marketing)/sovereign/page.tsx
@@ -21,7 +21,7 @@ import { Footer } from '@/components/landing/Footer';
*/
export const metadata: Metadata = {
- title: 'Sovereign + air-gap deployment',
+ title: 'Sovereign + air-gap deployment — AiSOC',
description:
'AiSOC runs anywhere: air-gapped, on-prem, hybrid, public cloud, or managed SaaS — with cloud LLM APIs, a local Ollama sidecar, or a bring-your-own LLM endpoint. EU, US, India, or custom data residency.',
alternates: { canonical: '/sovereign' },
diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css
index 9fa3087bc..0cb040a7e 100644
--- a/apps/web/src/app/globals.css
+++ b/apps/web/src/app/globals.css
@@ -34,6 +34,14 @@
--surface-hover: #1a2030;
--surface-subtle: #0d1119;
+ /* Landing-only gradient stops (T6.5). Mirrors
+ `docs/design/landing-page-design-tokens.md` §2.4. Hex stops match the
+ existing `brand.*` palette so a buyer-to-product transition keeps the
+ same hue family across the marketing site and the console. */
+ --landing-grad-hero: linear-gradient(to bottom right, #1d4ed8 0%, #0a0d14 80%);
+ --landing-grad-pillars: linear-gradient(to right, #3b82f6 0%, #8b5cf6 100%);
+ --landing-grad-cta: linear-gradient(to bottom right, #3b82f6 0%, #1d4ed8 100%);
+
/* Borders / dividers — slate-400 with low alpha so they tint the surface
instead of cutting hard lines. */
--surface-border: rgba(148, 163, 184, 0.12);
@@ -197,3 +205,138 @@ code {
scroll-behavior: auto !important;
}
}
+
+/* ─────────────────────── Landing page (T6.5) ────────────────────────
+ *
+ * Keyframes + utilities used by the marketing landing components under
+ * `apps/web/src/components/landing/` and the Aceternity/MagicUI primitives
+ * vendored at `apps/web/src/components/{aceternity,magicui}/`. Defined as
+ * raw CSS rather than via a Tailwind v4 plugin so we don't depend on
+ * `tailwindcss-animate` (which still targets the v3 config schema and
+ * doesn't compose cleanly with the `@import "tailwindcss"` + `@config`
+ * hybrid we run here). Every loop respects `prefers-reduced-motion` via
+ * the global rule above.
+ */
+
+@keyframes marquee {
+ from {
+ transform: translateX(0);
+ }
+ to {
+ transform: translateX(calc(-100% - var(--gap, 1rem)));
+ }
+}
+
+@keyframes marquee-vertical {
+ from {
+ transform: translateY(0);
+ }
+ to {
+ transform: translateY(calc(-100% - var(--gap, 1rem)));
+ }
+}
+
+@keyframes meteor {
+ 0% {
+ transform: rotate(var(--angle, 215deg)) translateX(0);
+ opacity: 1;
+ }
+ 70% {
+ opacity: 1;
+ }
+ 100% {
+ transform: rotate(var(--angle, 215deg)) translateX(-500px);
+ opacity: 0;
+ }
+}
+
+@keyframes border-beam {
+ 100% {
+ offset-distance: 100%;
+ }
+}
+
+@keyframes shimmer-slide {
+ 0% {
+ transform: translate(-50%, -50%) rotate(0deg);
+ }
+ 100% {
+ transform: translate(-50%, -50%) rotate(360deg);
+ }
+}
+
+@keyframes aurora-shift {
+ 0% {
+ background-position: 0% 50%;
+ }
+ 50% {
+ background-position: 100% 50%;
+ }
+ 100% {
+ background-position: 0% 50%;
+ }
+}
+
+@keyframes graph-pulse {
+ 0%,
+ 100% {
+ opacity: 0.35;
+ transform: scale(1);
+ }
+ 50% {
+ opacity: 0.75;
+ transform: scale(1.04);
+ }
+}
+
+@keyframes graph-flow {
+ to {
+ stroke-dashoffset: -24;
+ }
+}
+
+@keyframes fade-in-up {
+ from {
+ opacity: 0;
+ transform: translateY(16px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+.animate-marquee {
+ animation: marquee var(--duration, 40s) linear infinite;
+}
+
+.animate-marquee-vertical {
+ animation: marquee-vertical var(--duration, 40s) linear infinite;
+}
+
+.animate-meteor {
+ animation: meteor var(--duration, 5s) linear infinite;
+}
+
+.animate-graph-pulse {
+ animation: graph-pulse 4s cubic-bezier(0.16, 1, 0.3, 1) infinite;
+}
+
+.animate-graph-flow {
+ stroke-dasharray: 4 8;
+ animation: graph-flow 2.4s linear infinite;
+}
+
+.animate-fade-in-up {
+ animation: fade-in-up 480ms cubic-bezier(0.16, 1, 0.3, 1) both;
+}
+
+.animate-aurora-shift {
+ animation: aurora-shift var(--aurora-duration, 12s) ease-in-out infinite;
+}
+
+/* Pause infinite marquees on hover or focus so users can read the strip. */
+.marquee-pausable:hover [class*="animate-marquee"],
+.marquee-pausable:focus-within [class*="animate-marquee"] {
+ animation-play-state: paused;
+}
diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx
index 48860a93b..52ace15ea 100644
--- a/apps/web/src/app/page.tsx
+++ b/apps/web/src/app/page.tsx
@@ -1,56 +1,237 @@
import type { Metadata } from 'next';
-import { LandingNav } from '@/components/landing/LandingNav';
-import { Features } from '@/components/landing/Features';
-import { Architecture } from '@/components/landing/Architecture';
-import { MitreStrip } from '@/components/landing/MitreStrip';
-import { OpenSource } from '@/components/landing/OpenSource';
-import { Footer } from '@/components/landing/Footer';
-import { StartHero } from '@/components/onboarding/StartHero';
+import dynamic from 'next/dynamic';
+import { getPublicSiteUrl } from '@/lib/site';
+import { StickyNav } from '@/components/landing/sections/StickyNav';
+import { Hero } from '@/components/landing/sections/Hero';
+import { ProofStrip } from '@/components/landing/sections/ProofStrip';
+import { Problem } from '@/components/landing/sections/Problem';
/**
- * AiSOC root (`/`) — onboarding-first landing page (WS-A2).
+ * AiSOC root (`/`) — marketing landing page (T6.5).
*
- * The plan asks the root to be an onboarding surface, not a marketing page:
- * three CTAs (Try the demo / Connect first source / Skip & explore) live
- * above the fold, with platform context (features, architecture, MITRE,
- * open-source pitch) reused below for visitors who want to read more before
- * clicking. The legacy hero/CTA strip is intentionally retired — buyers
- * shouldn't have to choose between "open the demo" and "open console" without
- * context. The new hero collapses both into a single primary path.
+ * 16-section narrative for the v8.0 GTM push. Above-the-fold sections
+ * (StickyNav, Hero, ProofStrip, Problem) are eagerly imported because
+ * they sit inside the LCP window. Everything below the fold is loaded
+ * via `next/dynamic` so the initial JS chunk shipped to the browser
+ * stays well under the 180 kB gzipped budget in §12 of the brief.
+ *
+ * SSR is preserved for every section (`ssr: true` is the default of
+ * `next/dynamic`); we only code-split the client-side bundle. That
+ * keeps the SEO crawl path intact and lets the JSON-LD payload below
+ * render the same copy a human visitor sees.
+ *
+ * The page is dark-locked via a nested `data-theme="dark"` boundary,
+ * same pattern the previous root used — every gradient, glow, and
+ * tinted overlay in the section components was tuned against the dark
+ * palette and migrating each to themable tokens would balloon T6.5 for
+ * no buyer-visible win. The console chrome (TopBar / Sidebar / etc.)
+ * still honours the toggle, which is what AGENTS.md WS-F1 promised.
*/
+const SolutionAgents = dynamic(
+ () => import('@/components/landing/sections/SolutionAgents').then((m) => m.SolutionAgents),
+);
+const DemoEmbed = dynamic(
+ () => import('@/components/landing/sections/DemoEmbed').then((m) => m.DemoEmbed),
+);
+const Pillars = dynamic(
+ () => import('@/components/landing/sections/Pillars').then((m) => m.Pillars),
+);
+const FeatureGrid = dynamic(
+ () => import('@/components/landing/sections/FeatureGrid').then((m) => m.FeatureGrid),
+);
+const ConnectorsMarquee = dynamic(
+ () => import('@/components/landing/sections/ConnectorsMarquee').then((m) => m.ConnectorsMarquee),
+);
+const BenchmarkBand = dynamic(
+ () => import('@/components/landing/sections/BenchmarkBand').then((m) => m.BenchmarkBand),
+);
+const DeployOptions = dynamic(
+ () => import('@/components/landing/sections/DeployOptions').then((m) => m.DeployOptions),
+);
+const OpenSourceMoment = dynamic(
+ () => import('@/components/landing/sections/OpenSourceMoment').then((m) => m.OpenSourceMoment),
+);
+const Testimonials = dynamic(
+ () => import('@/components/landing/sections/Testimonials').then((m) => m.Testimonials),
+);
+const PricingTeaser = dynamic(
+ () => import('@/components/landing/sections/PricingTeaser').then((m) => m.PricingTeaser),
+);
+const Faq = dynamic(
+ () => import('@/components/landing/sections/Faq').then((m) => m.Faq),
+);
+const FinalCta = dynamic(
+ () => import('@/components/landing/sections/FinalCta').then((m) => m.FinalCta),
+);
+const Footer = dynamic(
+ () => import('@/components/landing/sections/Footer').then((m) => m.Footer),
+);
+
+const siteUrl = getPublicSiteUrl();
+
export const metadata: Metadata = {
- // Use `absolute` so the root layout's `template: '%s | AiSOC'` doesn't
+ // Use `absolute` so the root layout's `template: '%s | AiSOC'` does not
// append a redundant " | AiSOC" to a title that already leads with the
- // brand. Without this, the homepage tab renders
- // `AiSOC — open-source AI Security Operations Center | AiSOC`.
+ // brand.
title: { absolute: 'AiSOC — open-source AI Security Operations Center' },
description:
- 'Open-source AI SOC: 200-incident eval harness, 26 click-and-connect security sources, MITRE ATT&CK-mapped autonomous investigation. Try the live demo or self-host in under 5 minutes.',
+ 'AiSOC is an MIT-licensed, agentic SOC: four specialised agents (Detect, Triage, Hunt, Respond), 69 first-party connectors, a 200-incident benchmark harness, and air-gap deploy on a single flag. Self-host in five minutes or join the managed waitlist.',
alternates: { canonical: '/' },
+ openGraph: {
+ title: 'AiSOC — open-source AI Security Operations Center',
+ description:
+ 'Four agents, 69 connectors, a public benchmark, and air-gap on a flag. Self-host the full stack under MIT, or join the managed waitlist at app.aisoc.dev.',
+ url: siteUrl,
+ siteName: 'AiSOC',
+ type: 'website',
+ locale: 'en_US',
+ images: [
+ {
+ url: '/og-image.svg',
+ width: 1200,
+ height: 630,
+ alt: 'AiSOC — open-source AI SOC with four specialised agents and 69 connectors',
+ },
+ ],
+ },
+ twitter: {
+ card: 'summary_large_image',
+ title: 'AiSOC — open-source AI Security Operations Center',
+ description:
+ 'Four agents. 69 connectors. A public benchmark. Air-gap on a flag. MIT-licensed.',
+ images: ['/og-image.svg'],
+ },
+};
+
+const productJsonLd = {
+ '@context': 'https://schema.org',
+ '@type': 'SoftwareApplication',
+ name: 'AiSOC',
+ alternateName: ['AI SOC', 'AiSOC Platform', 'Agentic SOC'],
+ applicationCategory: 'SecurityApplication',
+ applicationSubCategory: 'Security Operations Center',
+ operatingSystem: 'Linux, macOS, Docker',
+ license: 'https://opensource.org/licenses/MIT',
+ url: siteUrl,
+ downloadUrl: 'https://github.com/beenuar/AiSOC',
+ installUrl: 'https://github.com/beenuar/AiSOC#quick-start',
+ releaseNotes: 'https://github.com/beenuar/AiSOC/releases',
+ description:
+ 'AiSOC is an MIT-licensed agentic Security Operations Center: four specialised agents (Detect, Triage, Hunt, Respond), 69 first-party connectors, a public 200-incident benchmark, and air-gap deploy on a single environment flag.',
+ featureList: [
+ 'Four specialised agents: Detect, Triage, Hunt, Respond',
+ '69 first-party connectors across EDR, SIEM, cloud, IAM, SaaS, VCS, network',
+ 'Public 200-incident benchmark harness with substrate self-consistency gates',
+ 'Air-gap mode (AISOC_AIRGAPPED=true) with local Ollama sidecar',
+ 'L0–L4 automation maturity ladder for human-in-the-loop guardrails',
+ 'Encrypted connector vault (Fernet AES-128-CBC + HMAC-SHA256)',
+ 'Self-host on Render, Docker Compose, Fly.io, Helm, or AWS Terraform',
+ ],
+ offers: {
+ '@type': 'Offer',
+ price: '0',
+ priceCurrency: 'USD',
+ description: 'Free, MIT-licensed, self-hostable. Paid managed tier on waitlist.',
+ },
+};
+
+const faqJsonLd = {
+ '@context': 'https://schema.org',
+ '@type': 'FAQPage',
+ mainEntity: [
+ {
+ '@type': 'Question',
+ name: 'Is AiSOC really open source?',
+ acceptedAnswer: {
+ '@type': 'Answer',
+ text:
+ 'Yes — the agent, the connectors, the detection rules, the benchmark dataset, and every piece of infrastructure code are MIT-licensed. There is no private fork.',
+ },
+ },
+ {
+ '@type': 'Question',
+ name: 'What does the agent need to call out to?',
+ acceptedAnswer: {
+ '@type': 'Answer',
+ text:
+ 'By default the Triage and Hunt agents call an LLM provider you configure (OpenAI, Anthropic, Azure, Bedrock, or a private LiteLLM gateway). Set AISOC_AIRGAPPED=true and the platform refuses every outbound call; an Ollama sidecar runs a local model in-cluster.',
+ },
+ },
+ {
+ '@type': 'Question',
+ name: 'Where does my data live?',
+ acceptedAnswer: {
+ '@type': 'Answer',
+ text:
+ 'Self-host: wherever you point Postgres, ClickHouse, and Redis. Managed: EU, US, or India region you pick at signup. Sovereign: a single-tenant VPC you control. The connector vault encrypts secrets with Fernet AES-128-CBC + HMAC-SHA256.',
+ },
+ },
+ {
+ '@type': 'Question',
+ name: 'Can the agent take real-world action without a human?',
+ acceptedAnswer: {
+ '@type': 'Answer',
+ text:
+ 'Only inside the maturity tier you configure. L0 keeps the agent advisory only; L2 (the production default) lets it run reversible containment actions; L4 allows whitelisted closed-loop actions. Every action class is gated against blast radius.',
+ },
+ },
+ {
+ '@type': 'Question',
+ name: 'How is this benchmarked?',
+ acceptedAnswer: {
+ '@type': 'Answer',
+ text:
+ 'Five pytest suites in services/agents/tests/ run on every PR. Three are substrate self-consistency gates; the fourth is a real measurement against a fixed 1,000-alert noisy stream; the fifth is a coverage gate on the synthetic telemetry corpus. The methodology page documents what each suite measures and what it does not.',
+ },
+ },
+ {
+ '@type': 'Question',
+ name: 'How do connectors work?',
+ acceptedAnswer: {
+ '@type': 'Answer',
+ text:
+ 'Each connector is a Python class that declares a schema, tests its credentials, polls on a schedule, and normalises events into OCSF. 69 ship in the box. The plugin SDKs (Python, TypeScript, Go) let you author your own in roughly 50 lines.',
+ },
+ },
+ ],
};
export default function HomePage() {
- // The marketing landing is intentionally locked to the dark palette via a
- // nested `data-theme="dark"` boundary. The hero is built around fixed dark
- // gradient overlays (see `StartHero`, `Architecture`, `Features`) and the
- // copy was tuned against that backdrop. Migrating every decorative layer
- // to themable tokens would balloon the WS-F1 diff for negligible buyer
- // value. The console chrome (TopBar / Sidebar / AppShell) — i.e. the
- // surfaces a buyer actually inhabits — *does* honour the toggle, which is
- // the buyer-visible promise. See apps/docs/docs/operations/theming.md.
return (
- <main
- data-theme="dark"
- className="relative min-h-screen overflow-x-hidden bg-surface-base text-fg-primary"
- >
- <LandingNav />
- <StartHero />
- <Features />
- <Architecture />
- <MitreStrip />
- <OpenSource />
- <Footer />
- </main>
+ <>
+ <script
+ type="application/ld+json"
+ // eslint-disable-next-line react/no-danger -- JSON-LD payload for crawlers
+ dangerouslySetInnerHTML={{ __html: JSON.stringify(productJsonLd) }}
+ />
+ <script
+ type="application/ld+json"
+ // eslint-disable-next-line react/no-danger -- JSON-LD FAQ payload for crawlers
+ dangerouslySetInnerHTML={{ __html: JSON.stringify(faqJsonLd) }}
+ />
+ <main
+ data-theme="dark"
+ className="relative min-h-screen overflow-x-hidden bg-surface-base text-fg-primary"
+ >
+ <StickyNav />
+ <Hero />
+ <ProofStrip />
+ <Problem />
+ <SolutionAgents />
+ <DemoEmbed />
+ <Pillars />
+ <FeatureGrid />
+ <ConnectorsMarquee />
+ <BenchmarkBand />
+ <DeployOptions />
+ <OpenSourceMoment />
+ <Testimonials />
+ <PricingTeaser />
+ <Faq />
+ <FinalCta />
+ <Footer />
+ </main>
+ </>
);
}
diff --git a/apps/web/src/components/aceternity/AnimatedTooltip.tsx b/apps/web/src/components/aceternity/AnimatedTooltip.tsx
new file mode 100644
index 000000000..deeee878c
--- /dev/null
+++ b/apps/web/src/components/aceternity/AnimatedTooltip.tsx
@@ -0,0 +1,47 @@
+// Source: https://ui.aceternity.com/components/animated-tooltip
+// Licensed under MIT. Lightweight wrapper that shows a hover tooltip with
+// a framer-motion fade + 6 px translate. Falls back to instant-visible
+// under `prefers-reduced-motion`.
+'use client';
+
+import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
+import { type ReactNode, useId, useState } from 'react';
+import { cn } from '@/lib/utils';
+
+interface AnimatedTooltipProps {
+ label: string;
+ children: ReactNode;
+ className?: string;
+}
+
+export function AnimatedTooltip({ label, children, className }: AnimatedTooltipProps) {
+ const [open, setOpen] = useState(false);
+ const tooltipId = useId();
+ const prefersReducedMotion = useReducedMotion();
+ return (
+ <span
+ className={cn('relative inline-flex items-center', className)}
+ onMouseEnter={() => setOpen(true)}
+ onMouseLeave={() => setOpen(false)}
+ onFocus={() => setOpen(true)}
+ onBlur={() => setOpen(false)}
+ >
+ <span aria-describedby={open ? tooltipId : undefined}>{children}</span>
+ <AnimatePresence>
+ {open && (
+ <motion.span
+ id={tooltipId}
+ role="tooltip"
+ initial={{ opacity: 0, y: prefersReducedMotion ? 0 : 6 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: prefersReducedMotion ? 0 : 6 }}
+ transition={{ duration: prefersReducedMotion ? 0 : 0.2, ease: [0.16, 1, 0.3, 1] }}
+ className="pointer-events-none absolute left-1/2 top-full z-50 mt-2 w-max max-w-[14rem] -translate-x-1/2 rounded-md border border-surface-border bg-surface-raised px-3 py-2 text-xs leading-relaxed text-fg-secondary shadow-[0_8px_24px_-12px_rgba(0,0,0,0.5)]"
+ >
+ {label}
+ </motion.span>
+ )}
+ </AnimatePresence>
+ </span>
+ );
+}
diff --git a/apps/web/src/components/aceternity/BackgroundBeams.tsx b/apps/web/src/components/aceternity/BackgroundBeams.tsx
new file mode 100644
index 000000000..a40f19be9
--- /dev/null
+++ b/apps/web/src/components/aceternity/BackgroundBeams.tsx
@@ -0,0 +1,48 @@
+// Source: https://ui.aceternity.com/components/background-beams
+// Licensed under MIT. Vendored implementation. Renders a static SVG of
+// soft beams; the upstream version animates them via path tracing, but
+// here they fade in with a single `animate-fade-in-up` on the wrapper —
+// cheaper and the visual signal is identical at the rendered scale.
+'use client';
+
+import { cn } from '@/lib/utils';
+
+interface BackgroundBeamsProps {
+ className?: string;
+}
+
+export function BackgroundBeams({ className }: BackgroundBeamsProps) {
+ return (
+ <svg
+ aria-hidden="true"
+ className={cn(
+ 'pointer-events-none absolute inset-0 h-full w-full opacity-60 animate-fade-in-up',
+ '[mask-image:radial-gradient(circle_at_50%_40%,white,transparent_75%)]',
+ className,
+ )}
+ style={{ animationDelay: '120ms', animationDuration: '900ms' }}
+ width="100%"
+ height="100%"
+ viewBox="0 0 696 316"
+ preserveAspectRatio="none"
+ fill="none"
+ >
+ {[
+ ['M-380 -189C-380 -189 -312 216 152 343 616 470 684 875 684 875', '#3b82f6'],
+ ['M-373 -197C-373 -197 -305 208 159 335 623 462 691 867 691 867', '#1d4ed8'],
+ ['M-366 -205C-366 -205 -298 200 166 327 630 454 698 859 698 859', '#8b5cf6'],
+ ['M-359 -213C-359 -213 -291 192 173 319 637 446 705 851 705 851', '#3b82f6'],
+ ['M-352 -221C-352 -221 -284 184 180 311 644 438 712 843 712 843', '#1d4ed8'],
+ ].map(([d, stroke], idx) => (
+ <path
+ key={idx}
+ d={d}
+ stroke={stroke}
+ strokeOpacity={0.22}
+ strokeWidth="0.8"
+ fill="none"
+ />
+ ))}
+ </svg>
+ );
+}
diff --git a/apps/web/src/components/aceternity/BentoGrid.tsx b/apps/web/src/components/aceternity/BentoGrid.tsx
new file mode 100644
index 000000000..bbc04fdc5
--- /dev/null
+++ b/apps/web/src/components/aceternity/BentoGrid.tsx
@@ -0,0 +1,67 @@
+// Source: https://ui.aceternity.com/components/bento-grid
+// Licensed under MIT. Vendored implementation, trimmed to the two pieces
+// the landing page needs: a 3-column responsive grid and a card primitive
+// that hover-lifts and exposes the standard `header / icon / title /
+// description` slots that the feature-grid section consumes.
+'use client';
+
+import { motion, useReducedMotion } from 'framer-motion';
+import type { ReactNode } from 'react';
+import { cn } from '@/lib/utils';
+
+interface BentoGridProps {
+ className?: string;
+ children: ReactNode;
+}
+
+export function BentoGrid({ className, children }: BentoGridProps) {
+ return (
+ <div
+ className={cn(
+ 'mx-auto grid w-full max-w-7xl auto-rows-[18rem] grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3',
+ className,
+ )}
+ >
+ {children}
+ </div>
+ );
+}
+
+interface BentoGridItemProps {
+ className?: string;
+ header?: ReactNode;
+ icon?: ReactNode;
+ title: ReactNode;
+ description?: ReactNode;
+}
+
+export function BentoGridItem({
+ className,
+ header,
+ icon,
+ title,
+ description,
+}: BentoGridItemProps) {
+ const prefersReducedMotion = useReducedMotion();
+ return (
+ <motion.div
+ whileHover={prefersReducedMotion ? undefined : { y: -2 }}
+ transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}
+ className={cn(
+ 'group/bento relative row-span-1 flex flex-col justify-between space-y-4 overflow-hidden rounded-xl border border-surface-border bg-surface-raised/70 p-5 shadow-[0_1px_2px_rgba(0,0,0,0.4)] transition-colors duration-200 ease-landing-out-quart hover:border-brand-500/40',
+ className,
+ )}
+ >
+ {header && <div className="relative">{header}</div>}
+ <div className="flex flex-col gap-2">
+ {icon && <div className="text-brand-300">{icon}</div>}
+ <h3 className="font-display text-base font-semibold leading-snug text-fg-primary">
+ {title}
+ </h3>
+ {description && (
+ <p className="text-sm leading-relaxed text-fg-secondary">{description}</p>
+ )}
+ </div>
+ </motion.div>
+ );
+}
diff --git a/apps/web/src/components/aceternity/CardHoverEffect.tsx b/apps/web/src/components/aceternity/CardHoverEffect.tsx
new file mode 100644
index 000000000..3b914637f
--- /dev/null
+++ b/apps/web/src/components/aceternity/CardHoverEffect.tsx
@@ -0,0 +1,49 @@
+// Source: https://ui.aceternity.com/components/card-hover-effect
+// Licensed under MIT. Trimmed down to a hover-state overlay that any card
+// can opt into via `<CardHoverEffect />` as a sibling. The lift transform
+// is dropped under `prefers-reduced-motion` while the colour shift stays.
+'use client';
+
+import { motion, useReducedMotion } from 'framer-motion';
+import { cn } from '@/lib/utils';
+
+interface CardHoverEffectProps {
+ isActive: boolean;
+ className?: string;
+ /** Tailwind background-color class to swap in on hover. */
+ activeClassName?: string;
+}
+
+/**
+ * Renders the hover overlay for a parent card. Parent must:
+ *
+ * 1. Be `position: relative` and have `onMouseEnter` / `onMouseLeave`
+ * handlers wired into `isActive`.
+ * 2. Render `<CardHoverEffect isActive={…} />` as its first child.
+ *
+ * `framer-motion` keeps `opacity` cheap (compositor-only) so no layout
+ * thrash on hover.
+ */
+export function CardHoverEffect({
+ isActive,
+ className,
+ activeClassName = 'bg-brand-500/8',
+}: CardHoverEffectProps) {
+ const prefersReducedMotion = useReducedMotion();
+ return (
+ <motion.span
+ aria-hidden="true"
+ className={cn(
+ 'pointer-events-none absolute inset-0 rounded-[inherit]',
+ activeClassName,
+ className,
+ )}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: isActive ? 1 : 0 }}
+ transition={{
+ duration: prefersReducedMotion ? 0 : isActive ? 0.25 : 0.15,
+ ease: [0.45, 0, 0.55, 1],
+ }}
+ />
+ );
+}
diff --git a/apps/web/src/components/aceternity/GlowingEffect.tsx b/apps/web/src/components/aceternity/GlowingEffect.tsx
new file mode 100644
index 000000000..776d84c1a
--- /dev/null
+++ b/apps/web/src/components/aceternity/GlowingEffect.tsx
@@ -0,0 +1,80 @@
+// Source: https://ui.aceternity.com/components/glowing-effect
+// Licensed under MIT. Vendored implementation. Tracks the pointer position
+// relative to the wrapped card and renders a conic-gradient halo that
+// brightens as the cursor approaches. Honours `prefers-reduced-motion`
+// per `docs/design/landing-page-motion-spec.md` §2.4.
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { useReducedMotion } from 'framer-motion';
+import { cn } from '@/lib/utils';
+
+interface GlowingEffectProps {
+ className?: string;
+ /** When false, the halo is hidden entirely. */
+ enabled?: boolean;
+ /** Distance in px at which the halo starts to fade in. */
+ proximity?: number;
+ /** Fractional inner radius where the halo stays at max intensity. */
+ inactiveZone?: number;
+}
+
+/**
+ * Drop-in halo wrapper. Place inside a `relative` parent — the halo lives
+ * underneath the card content via `pointer-events-none`. Renders nothing
+ * when reduced-motion is on or `enabled={false}`.
+ */
+export function GlowingEffect({
+ className,
+ enabled = true,
+ proximity = 80,
+ inactiveZone = 0.4,
+}: GlowingEffectProps) {
+ const ref = useRef<HTMLDivElement | null>(null);
+ const prefersReducedMotion = useReducedMotion();
+ const [intensity, setIntensity] = useState(0);
+
+ useEffect(() => {
+ if (!enabled || prefersReducedMotion) return;
+ const onMove = (event: MouseEvent) => {
+ const node = ref.current;
+ if (!node) return;
+ const rect = node.getBoundingClientRect();
+ const cx = event.clientX - rect.left - rect.width / 2;
+ const cy = event.clientY - rect.top - rect.height / 2;
+ const distance = Math.hypot(cx, cy);
+ const radius = Math.max(rect.width, rect.height) / 2;
+ const inner = radius * inactiveZone;
+ if (distance <= inner) {
+ setIntensity(1);
+ } else if (distance <= radius + proximity) {
+ setIntensity(1 - (distance - inner) / (radius + proximity - inner));
+ } else {
+ setIntensity(0);
+ }
+ };
+ window.addEventListener('mousemove', onMove);
+ return () => window.removeEventListener('mousemove', onMove);
+ }, [enabled, inactiveZone, prefersReducedMotion, proximity]);
+
+ if (!enabled || prefersReducedMotion) {
+ return null;
+ }
+
+ return (
+ <div
+ ref={ref}
+ aria-hidden="true"
+ className={cn(
+ 'pointer-events-none absolute inset-0 rounded-[inherit] transition-opacity duration-300 ease-out',
+ className,
+ )}
+ style={{
+ opacity: intensity,
+ background:
+ 'conic-gradient(from 0deg at 50% 50%, rgba(59,130,246,0.18) 0deg, rgba(139,92,246,0.32) 120deg, rgba(59,130,246,0.18) 240deg, rgba(59,130,246,0) 360deg)',
+ filter: 'blur(24px)',
+ }}
+ />
+ );
+}
diff --git a/apps/web/src/components/aceternity/Spotlight.tsx b/apps/web/src/components/aceternity/Spotlight.tsx
new file mode 100644
index 000000000..c7b3242df
--- /dev/null
+++ b/apps/web/src/components/aceternity/Spotlight.tsx
@@ -0,0 +1,46 @@
+// Source: https://ui.aceternity.com/components/spotlight
+// Licensed under MIT — Aceternity UI is a copy-into-your-codebase library
+// (no npm package), so this file is the vendored implementation. Rewritten
+// in plain Tailwind 4 + framer-motion 11 to fit the AiSOC landing tokens.
+'use client';
+
+import type { CSSProperties } from 'react';
+import { cn } from '@/lib/utils';
+
+interface SpotlightProps {
+ className?: string;
+ /** CSS color string for the spotlight fill. Defaults to brand-500 with alpha. */
+ fill?: string;
+ /** Use `style` to override the `top` / `left` positioning of the glow. */
+ style?: CSSProperties;
+}
+
+/**
+ * Corner radial glow that sits behind the hero / demo frame and softens
+ * the otherwise hard surface-base. Pure SVG — no JS at runtime, so it
+ * costs nothing on hydration and degrades to "nothing visible" if CSS
+ * filters are blocked.
+ */
+export function Spotlight({ className, fill = 'rgb(59 130 246 / 0.55)', style }: SpotlightProps) {
+ return (
+ <svg
+ className={cn('pointer-events-none absolute z-0 h-[169%] w-[138%] opacity-0 animate-fade-in-up lg:w-[84%]', className)}
+ style={{ animationDelay: '120ms', animationDuration: '900ms', ...style }}
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 3787 2842"
+ fill="none"
+ aria-hidden="true"
+ >
+ <g filter="url(#aisoc-spotlight-filter)">
+ <ellipse cx="1924.71" cy="273.501" rx="1924.71" ry="273.501" transform="matrix(-0.822377 -0.568943 -0.568943 0.822377 3631.88 2291.09)" fill={fill} fillOpacity="0.21" />
+ </g>
+ <defs>
+ <filter id="aisoc-spotlight-filter" x="0.860352" y="0.838989" width="3785.16" height="2840.26" filterUnits="userSpaceOnUse" colorInterpolationFilters="sRGB">
+ <feFlood floodOpacity="0" result="BackgroundImageFix" />
+ <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
+ <feGaussianBlur stdDeviation="151" result="effect1_foregroundBlur_1065_8" />
+ </filter>
+ </defs>
+ </svg>
+ );
+}
diff --git a/apps/web/src/components/aceternity/TextGenerateEffect.tsx b/apps/web/src/components/aceternity/TextGenerateEffect.tsx
new file mode 100644
index 000000000..7ffae3229
--- /dev/null
+++ b/apps/web/src/components/aceternity/TextGenerateEffect.tsx
@@ -0,0 +1,54 @@
+// Source: https://ui.aceternity.com/components/text-generate-effect
+// Licensed under MIT. Vendored implementation tuned for the AiSOC hero H1:
+// per-word framer-motion reveal with a 30 ms stagger and the `out-expo`
+// easing curve from `docs/design/landing-page-design-tokens.md` §7.
+'use client';
+
+import { motion, useReducedMotion } from 'framer-motion';
+import { useMemo } from 'react';
+import { cn } from '@/lib/utils';
+
+interface TextGenerateEffectProps {
+ words: string;
+ className?: string;
+ /** Per-word stagger in seconds. */
+ staggerDelay?: number;
+ /** Total per-word fade duration in seconds. */
+ duration?: number;
+ /** Apply a 4 px blur during reveal. Defaults to `false` — at 56 px display the blur reads as a mistake. */
+ filter?: boolean;
+}
+
+const OUT_EXPO = [0.16, 1, 0.3, 1] as const;
+
+export function TextGenerateEffect({
+ words,
+ className,
+ staggerDelay = 0.03,
+ duration = 0.55,
+ filter = false,
+}: TextGenerateEffectProps) {
+ const prefersReducedMotion = useReducedMotion();
+ const tokens = useMemo(() => words.split(' '), [words]);
+
+ if (prefersReducedMotion) {
+ return <span className={className}>{words}</span>;
+ }
+
+ return (
+ <span className={cn('inline-flex flex-wrap gap-x-[0.28em]', className)} aria-label={words}>
+ {tokens.map((word, idx) => (
+ <motion.span
+ key={`${word}-${idx}`}
+ initial={{ opacity: 0, y: '0.35em', filter: filter ? 'blur(4px)' : 'blur(0px)' }}
+ animate={{ opacity: 1, y: '0em', filter: 'blur(0px)' }}
+ transition={{ duration, delay: idx * staggerDelay, ease: OUT_EXPO }}
+ className="inline-block will-change-transform"
+ aria-hidden="true"
+ >
+ {word}
+ </motion.span>
+ ))}
+ </span>
+ );
+}
diff --git a/apps/web/src/components/aceternity/WavyBackground.tsx b/apps/web/src/components/aceternity/WavyBackground.tsx
new file mode 100644
index 000000000..f74e3a579
--- /dev/null
+++ b/apps/web/src/components/aceternity/WavyBackground.tsx
@@ -0,0 +1,66 @@
+// Source: https://ui.aceternity.com/components/wavy-background
+// Licensed under MIT. Vendored implementation. Renders three sine-wave
+// SVG paths layered over a brand gradient; cheaper than the canvas version
+// in the upstream library, so it stays under the perf budget when the
+// final-cta band enters the viewport. Falls back to a flat
+// `landing.gradient.cta` background under `prefers-reduced-motion`.
+'use client';
+
+import { motion, useReducedMotion } from 'framer-motion';
+import type { ReactNode } from 'react';
+import { cn } from '@/lib/utils';
+
+interface WavyBackgroundProps {
+ children?: ReactNode;
+ className?: string;
+ containerClassName?: string;
+ /** Stroke opacity for each wave layer. */
+ waveOpacity?: number;
+}
+
+const WAVE_STROKES = ['#1d4ed8', '#3b82f6', '#8b5cf6'] as const;
+
+export function WavyBackground({
+ children,
+ className,
+ containerClassName,
+ waveOpacity = 0.35,
+}: WavyBackgroundProps) {
+ const prefersReducedMotion = useReducedMotion();
+ return (
+ <div
+ className={cn(
+ 'relative isolate overflow-hidden bg-landing-grad-cta',
+ containerClassName,
+ )}
+ >
+ {!prefersReducedMotion && (
+ <svg
+ className="pointer-events-none absolute inset-0 h-full w-full"
+ viewBox="0 0 1440 600"
+ preserveAspectRatio="none"
+ aria-hidden="true"
+ >
+ {WAVE_STROKES.map((stroke, idx) => (
+ <motion.path
+ key={stroke}
+ d="M0 320 C 240 220 480 420 720 320 S 1200 220 1440 320 V 600 H 0 Z"
+ fill={stroke}
+ fillOpacity={waveOpacity / (idx + 1)}
+ initial={{ x: 0 }}
+ animate={{ x: [0, -120, 0] }}
+ transition={{
+ duration: 18 + idx * 4,
+ repeat: Infinity,
+ ease: 'easeInOut',
+ delay: idx * -3,
+ }}
+ style={{ filter: 'blur(2px)' }}
+ />
+ ))}
+ </svg>
+ )}
+ <div className={cn('relative z-10', className)}>{children}</div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/graph/RealtimeGraph.tsx b/apps/web/src/components/graph/RealtimeGraph.tsx
new file mode 100644
index 000000000..c881cc7a8
--- /dev/null
+++ b/apps/web/src/components/graph/RealtimeGraph.tsx
@@ -0,0 +1,400 @@
+'use client';
+
+/**
+ * RealtimeGraph — live Cytoscape view fed by ``useGraphWebSocket`` (T1.4 — v8.0).
+ *
+ * End-to-end:
+ *
+ * Neo4j writer ──► Kafka ``security.graph_updates``
+ * │
+ * ▼
+ * services/ingest/internal/graph_ws/Broadcaster
+ * │ (RFC6455 frames, tenant-scoped)
+ * ▼
+ * services/api .../v1/graph_ws/stream (auth + tenant rebind)
+ * │
+ * ▼ same-origin /api/v1/graph_ws/stream
+ * apps/web useGraphWebSocket hook ─► RealtimeGraph (THIS file)
+ *
+ * Latency budget — Kafka publish to first paint — is ≤ 1s. The
+ * component therefore patches the existing Cytoscape instance in place
+ * rather than recomputing layout on every event: a full ``cy.layout()``
+ * run on a 200-node graph easily crosses 200 ms on a mid-range laptop
+ * and the budget evaporates after two or three rapid envelopes. We
+ * relayout only on demand (the analyst clicks the relayout button) or
+ * the first time we receive a non-empty graph.
+ *
+ * Visual encoding mirrors ``AttackGraphView`` so the two views feel
+ * like the same graph rendered with two clocks: a polled SWR snapshot
+ * on one tab, a live tail on another.
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import cytoscape, {
+ type Core,
+ type ElementDefinition,
+ type LayoutOptions,
+ type StylesheetStyle,
+} from 'cytoscape';
+import fcose from 'cytoscape-fcose';
+
+import {
+ type GraphUpdateEnvelope,
+ useGraphWebSocket,
+ type GraphWebSocketStatus,
+} from '@/hooks/useGraphWebSocket';
+
+if (typeof window !== 'undefined') {
+ try {
+ cytoscape.use(fcose as unknown as cytoscape.Ext);
+ } catch {
+ /* already registered — Next.js fast-refresh re-runs this module */
+ }
+}
+
+const NODE_COLORS: Record<string, string> = {
+ Host: '#60a5fa',
+ Asset: '#22d3ee',
+ User: '#a78bfa',
+ Identity: '#a78bfa',
+ IP: '#f59e0b',
+ Domain: '#fbbf24',
+ Process: '#34d399',
+ Technique: '#f87171',
+ Tactic: '#fb7185',
+ Alert: '#ef4444',
+ Default: '#94a3b8',
+};
+
+const NODE_SHAPES: Record<string, cytoscape.Css.NodeShape> = {
+ Host: 'round-rectangle',
+ Asset: 'round-rectangle',
+ User: 'ellipse',
+ Identity: 'ellipse',
+ IP: 'diamond',
+ Domain: 'diamond',
+ Process: 'tag',
+ Technique: 'star',
+ Tactic: 'star',
+ Alert: 'octagon',
+ Default: 'ellipse',
+};
+
+const FCOSE_LAYOUT: LayoutOptions = {
+ name: 'fcose',
+ animate: true,
+ animationDuration: 400,
+ randomize: false,
+ fit: true,
+ padding: 30,
+ // The library types lag the runtime API; cast through unknown so
+ // the extra-options ride along without disabling TS for the file.
+ nodeRepulsion: 6000,
+ idealEdgeLength: 80,
+ gravity: 0.2,
+} as unknown as LayoutOptions;
+
+const STYLE: StylesheetStyle[] = [
+ {
+ selector: 'node',
+ style: {
+ 'background-color': 'data(color)',
+ shape: 'data(shape)' as cytoscape.Css.NodeShape,
+ label: 'data(label)',
+ color: '#e2e8f0',
+ 'font-size': 10,
+ 'text-valign': 'bottom',
+ 'text-margin-y': 4,
+ 'text-outline-color': '#0b1220',
+ 'text-outline-width': 2,
+ width: 28,
+ height: 28,
+ 'border-color': '#0f172a',
+ 'border-width': 2,
+ },
+ },
+ {
+ selector: 'node.flash',
+ style: {
+ 'border-color': '#fbbf24',
+ 'border-width': 4,
+ },
+ },
+ {
+ selector: 'edge',
+ style: {
+ width: 1.5,
+ 'line-color': '#475569',
+ 'target-arrow-color': '#475569',
+ 'target-arrow-shape': 'triangle',
+ 'curve-style': 'bezier',
+ label: 'data(label)',
+ 'font-size': 8,
+ color: '#94a3b8',
+ 'text-rotation': 'autorotate',
+ },
+ },
+ {
+ selector: 'edge.flash',
+ style: {
+ 'line-color': '#fbbf24',
+ 'target-arrow-color': '#fbbf24',
+ width: 2.5,
+ },
+ },
+];
+
+/**
+ * Convert a single envelope into one or two Cytoscape element ops.
+ *
+ * Node ops carry colour + shape from the envelope ``label``.
+ * Edge ops use the natural-key string ``"<from>->-<to>"`` as the
+ * Cytoscape element id so re-upserts collapse correctly.
+ */
+function envelopeToElements(env: GraphUpdateEnvelope): ElementDefinition[] {
+ const colour = (env.label && NODE_COLORS[env.label]) || NODE_COLORS.Default;
+ const shape = (env.label && NODE_SHAPES[env.label]) || NODE_SHAPES.Default;
+ switch (env.change_type) {
+ case 'upsert_node':
+ return [
+ {
+ group: 'nodes',
+ data: {
+ id: env.entity_id,
+ label: shortLabel(env),
+ kind: env.label ?? 'Default',
+ color: colour,
+ shape,
+ },
+ },
+ ];
+ case 'upsert_edge': {
+ if (!env.from || !env.to) return [];
+ const id = `${env.from}->-${env.to}`;
+ return [
+ {
+ group: 'edges',
+ data: {
+ id,
+ source: env.from,
+ target: env.to,
+ label: env.rel_type ?? '',
+ },
+ },
+ ];
+ }
+ default:
+ return [];
+ }
+}
+
+function shortLabel(env: GraphUpdateEnvelope): string {
+ // Show the last segment of the entity id (after the last ``:`` or
+ // ``/``) so the canvas isn't blanketed with full ARNs.
+ const id = env.entity_id;
+ const tail = id.split(/[/:]/).pop();
+ return tail && tail.length > 0 ? tail : id;
+}
+
+interface RealtimeGraphProps {
+ /**
+ * Override the WebSocket URL — primarily for Storybook / tests that
+ * point at a local mock. Production callers leave this undefined and
+ * the hook composes the same-origin proxy URL.
+ */
+ url?: string;
+ /** Disable the upgrade entirely. */
+ enabled?: boolean;
+ /**
+ * Optional initial elements — useful when seeding the canvas from a
+ * SWR-fetched snapshot before the live tail catches up. The first
+ * envelope still triggers a relayout.
+ */
+ initialElements?: ElementDefinition[];
+ className?: string;
+}
+
+export function RealtimeGraph({
+ url,
+ enabled = true,
+ initialElements,
+ className,
+}: RealtimeGraphProps) {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const cyRef = useRef<Core | null>(null);
+ const hasLaidOutRef = useRef(false);
+ const [stats, setStats] = useState({ nodes: 0, edges: 0 });
+
+ const { status, last, events, clear } = useGraphWebSocket({ url, enabled });
+
+ // Initialise Cytoscape exactly once per mount.
+ useEffect(() => {
+ if (!containerRef.current) return;
+ const cy = cytoscape({
+ container: containerRef.current,
+ elements: initialElements ?? [],
+ style: STYLE,
+ wheelSensitivity: 0.25,
+ layout:
+ initialElements && initialElements.length > 0
+ ? FCOSE_LAYOUT
+ : { name: 'preset' },
+ });
+ cyRef.current = cy;
+ hasLaidOutRef.current = Boolean(
+ initialElements && initialElements.length > 0,
+ );
+ setStats({ nodes: cy.nodes().length, edges: cy.edges().length });
+
+ return () => {
+ cy.destroy();
+ cyRef.current = null;
+ };
+ // initialElements changes are not supported after mount — callers
+ // who need to swap seed data should remount the component.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // Apply each incoming envelope. We patch the graph in place and
+ // only relayout the first time we ingest data; subsequent
+ // updates animate from their nearest existing neighbour, which
+ // is cheaper and far less jarring than re-running fcose on
+ // every envelope.
+ useEffect(() => {
+ if (!last) return;
+ const cy = cyRef.current;
+ if (!cy) return;
+ const elements = envelopeToElements(last);
+ if (elements.length === 0) return;
+
+ cy.batch(() => {
+ for (const el of elements) {
+ const id = el.data?.id as string | undefined;
+ if (!id) continue;
+ const existing = cy.getElementById(id);
+ if (existing && existing.length > 0) {
+ existing.data(el.data ?? {});
+ existing.addClass('flash');
+ } else {
+ const added = cy.add(el);
+ added.addClass('flash');
+ }
+ }
+ });
+
+ // Drop the flash highlight after a brief delay; the ``flash``
+ // class is purely cosmetic.
+ const handle = window.setTimeout(() => {
+ cy.elements('.flash').removeClass('flash');
+ }, 800);
+
+ if (!hasLaidOutRef.current && cy.elements().length > 0) {
+ hasLaidOutRef.current = true;
+ cy.layout(FCOSE_LAYOUT).run();
+ }
+
+ setStats({ nodes: cy.nodes().length, edges: cy.edges().length });
+ return () => window.clearTimeout(handle);
+ }, [last]);
+
+ const onRelayout = useCallback(() => {
+ const cy = cyRef.current;
+ if (!cy || cy.elements().length === 0) return;
+ cy.layout(FCOSE_LAYOUT).run();
+ }, []);
+
+ const onClear = useCallback(() => {
+ clear();
+ const cy = cyRef.current;
+ if (cy) {
+ cy.elements().remove();
+ setStats({ nodes: 0, edges: 0 });
+ hasLaidOutRef.current = false;
+ }
+ }, [clear]);
+
+ const statusLabel = useMemo(() => describeStatus(status), [status]);
+
+ return (
+ <div
+ className={
+ className ??
+ 'flex h-full w-full flex-col rounded-xl border border-white/5 bg-slate-900/60'
+ }
+ >
+ <header className="flex items-center justify-between gap-3 border-b border-white/5 px-4 py-2 text-xs text-slate-300">
+ <div className="flex items-center gap-2">
+ <StatusDot status={status} />
+ <span>{statusLabel}</span>
+ <span className="text-slate-500">·</span>
+ <span>
+ {stats.nodes} node{stats.nodes === 1 ? '' : 's'}
+ </span>
+ <span className="text-slate-500">·</span>
+ <span>
+ {stats.edges} edge{stats.edges === 1 ? '' : 's'}
+ </span>
+ <span className="text-slate-500">·</span>
+ <span>
+ {events.length} event{events.length === 1 ? '' : 's'} buffered
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={onRelayout}
+ className="rounded border border-white/10 px-2 py-1 text-[10px] uppercase tracking-wider text-slate-300 hover:border-white/30"
+ >
+ Re-layout
+ </button>
+ <button
+ type="button"
+ onClick={onClear}
+ className="rounded border border-white/10 px-2 py-1 text-[10px] uppercase tracking-wider text-slate-300 hover:border-white/30"
+ >
+ Clear
+ </button>
+ </div>
+ </header>
+ <div ref={containerRef} className="relative h-full min-h-[400px] flex-1 bg-[#0a1120]" />
+ </div>
+ );
+}
+
+function describeStatus(status: GraphWebSocketStatus): string {
+ switch (status) {
+ case 'idle':
+ return 'idle';
+ case 'connecting':
+ return 'connecting…';
+ case 'open':
+ return 'live';
+ case 'closing':
+ return 'closing…';
+ case 'closed':
+ return 'reconnecting…';
+ case 'error':
+ return 'error — retrying';
+ default:
+ return status;
+ }
+}
+
+function StatusDot({ status }: { status: GraphWebSocketStatus }) {
+ const color =
+ status === 'open'
+ ? 'bg-emerald-400'
+ : status === 'connecting' || status === 'closed'
+ ? 'bg-amber-400'
+ : status === 'error'
+ ? 'bg-rose-500'
+ : 'bg-slate-500';
+ return (
+ <span
+ className={`inline-block h-2 w-2 rounded-full ${color}`}
+ aria-hidden="true"
+ />
+ );
+}
+
+export default RealtimeGraph;
diff --git a/apps/web/src/components/landing/sections/BenchmarkBand.tsx b/apps/web/src/components/landing/sections/BenchmarkBand.tsx
new file mode 100644
index 000000000..caf57aed9
--- /dev/null
+++ b/apps/web/src/components/landing/sections/BenchmarkBand.tsx
@@ -0,0 +1,148 @@
+'use client';
+
+/**
+ * "Benchmarked, not vibes" — `benchmark` section from §6.9 of the
+ * brief.
+ *
+ * Renders a three-up band of `NumberTicker`-driven metrics over a
+ * brand-tinted gradient. Each tile shows:
+ * - A big mono metric (animated count-up from 0 when the band enters
+ * the viewport; suppressed under `prefers-reduced-motion`).
+ * - A caption labelling the metric source (substrate / wet-eval) so
+ * the page never claims a "real" number for a substrate gate. This
+ * matches the v1.4 eval-harness honesty contract from AGENTS.md.
+ *
+ * Two CTAs sit below the tiles: read the methodology, open the public
+ * scoreboard. Both deep-link to /benchmark routes that already exist.
+ */
+
+import Link from 'next/link';
+import { motion, useReducedMotion } from 'framer-motion';
+import { ArrowRight, ExternalLink, GitCompare } from 'lucide-react';
+import { NumberTicker } from '@/components/magicui/NumberTicker';
+
+interface Metric {
+ /**
+ * If `value` is set, the tile animates a 0→value count-up. Otherwise
+ * `label` is the visible metric (e.g. "Sub-minute p50").
+ */
+ value?: number;
+ suffix?: string;
+ label: string;
+ caption: string;
+}
+
+const METRICS: ReadonlyArray<Metric> = [
+ {
+ value: 97,
+ suffix: '%',
+ label: '97.0%',
+ caption: 'MITRE-tactic accuracy · substrate · per-case',
+ },
+ {
+ value: undefined,
+ label: 'Sub-minute p50',
+ caption: 'End-to-end investigation latency · wet-eval target',
+ },
+ {
+ value: 35,
+ suffix: ' ms',
+ label: '35 ms',
+ caption: 'Full substrate suite runtime on a laptop',
+ },
+];
+
+export function BenchmarkBand() {
+ const prefersReducedMotion = useReducedMotion();
+ const initial = prefersReducedMotion ? false : { opacity: 0, y: 16 };
+
+ return (
+ <section
+ id="benchmark"
+ aria-labelledby="benchmark-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <div className="mx-auto max-w-3xl text-center">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ Reproducible by anyone
+ </p>
+ <h2
+ id="benchmark-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ Benchmarked, not vibes.
+ </h2>
+ <p className="mt-4 text-base leading-relaxed text-fg-secondary sm:text-lg">
+ Five pytest suites gate every PR. 200 synthetic incidents drawn
+ from 55 templates plus a 361-event telemetry corpus across 14
+ log sources. Per-template macros catch the regression the
+ per-case mean hides. Every figure is labelled — substrate
+ (gated per-PR) or wet-eval (weekly job).
+ </p>
+ </div>
+
+ <div className="relative mt-12 overflow-hidden rounded-3xl border border-surface-border bg-surface-card/60 shadow-[0_30px_80px_-32px_rgba(15,23,42,0.7)] lg:mt-16">
+ <div
+ aria-hidden="true"
+ className="absolute inset-0 bg-landing-grad-pillars opacity-[0.08]"
+ />
+ <ul className="relative grid grid-cols-1 divide-y divide-surface-border md:grid-cols-3 md:divide-x md:divide-y-0">
+ {METRICS.map((metric, idx) => (
+ <motion.li
+ key={metric.label}
+ initial={initial}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{
+ duration: 0.55,
+ ease: [0.16, 1, 0.3, 1],
+ delay: idx * 0.08,
+ }}
+ className="flex flex-col items-center gap-2 px-6 py-10 text-center"
+ >
+ <p className="font-mono text-4xl font-semibold leading-none tracking-tight text-fg-primary tabular-nums sm:text-5xl lg:text-[56px]">
+ {metric.value !== undefined ? (
+ <>
+ <NumberTicker
+ value={metric.value}
+ decimalPlaces={metric.value < 100 && metric.value !== 35 ? 1 : 0}
+ />
+ {metric.suffix ?? ''}
+ </>
+ ) : (
+ metric.label
+ )}
+ </p>
+ <p className="max-w-[20ch] text-xs leading-relaxed text-fg-muted">
+ {metric.caption}
+ </p>
+ </motion.li>
+ ))}
+ </ul>
+ </div>
+
+ <div className="mx-auto mt-10 flex max-w-3xl flex-col items-center justify-center gap-3 text-center sm:flex-row sm:gap-5">
+ <Link
+ href="/benchmark"
+ className="group inline-flex h-11 items-center gap-2 rounded-md bg-gradient-to-br from-brand-500 to-brand-700 px-6 text-sm font-semibold text-white shadow-[0_1px_0_rgba(255,255,255,0.18)_inset] transition-shadow duration-200 ease-landing-out-quart hover:shadow-[0_12px_32px_-12px_rgba(59,130,246,0.65)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ <GitCompare className="h-4 w-4" aria-hidden="true" />
+ Read the methodology
+ <ArrowRight
+ className="h-4 w-4 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ <Link
+ href="https://docs.aisoc.dev/benchmark-scoreboard"
+ className="inline-flex items-center gap-1 text-sm font-medium text-fg-muted transition-colors duration-200 hover:text-fg-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ Open the public scoreboard
+ <ExternalLink className="h-3.5 w-3.5" aria-hidden="true" />
+ </Link>
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/ConnectorsMarquee.tsx b/apps/web/src/components/landing/sections/ConnectorsMarquee.tsx
new file mode 100644
index 000000000..8ab44c47f
--- /dev/null
+++ b/apps/web/src/components/landing/sections/ConnectorsMarquee.tsx
@@ -0,0 +1,227 @@
+'use client';
+
+/**
+ * "Plug in everything" — `connectors` section from §6.8 of the brief.
+ *
+ * Layout:
+ * - Section header (eyebrow + H2 + sub-head + category chips)
+ * - Two stacked `Marquee` rows of connector pills (top: left-to-right,
+ * bottom: right-to-left). The pills are drawn from a 24-name sample
+ * of the real `_CONNECTOR_CLASSES` registry; the full catalogue is
+ * 69 today.
+ * - Code callout with a "Write a connector in 50 lines" snippet
+ * mirroring the BaseConnector pattern used in the registry.
+ *
+ * Connectors are decorative; the marquees pause on hover/focus and
+ * collapse to a static row under `prefers-reduced-motion`.
+ */
+
+import Link from 'next/link';
+import { ArrowRight } from 'lucide-react';
+import { Marquee } from '@/components/magicui/Marquee';
+import { cn } from '@/lib/utils';
+
+interface ConnectorPill {
+ name: string;
+ category: 'EDR' | 'SIEM' | 'Cloud' | 'IAM' | 'SaaS' | 'VCS' | 'Network';
+}
+
+const CONNECTOR_SAMPLE: ReadonlyArray<ConnectorPill> = [
+ { name: 'CrowdStrike Falcon', category: 'EDR' },
+ { name: 'SentinelOne', category: 'EDR' },
+ { name: 'Microsoft Defender', category: 'EDR' },
+ { name: 'Cortex XDR', category: 'EDR' },
+ { name: 'Splunk', category: 'SIEM' },
+ { name: 'Microsoft Sentinel', category: 'SIEM' },
+ { name: 'Elastic', category: 'SIEM' },
+ { name: 'Sumo Logic', category: 'SIEM' },
+ { name: 'AWS CloudTrail', category: 'Cloud' },
+ { name: 'AWS GuardDuty', category: 'Cloud' },
+ { name: 'Azure Activity', category: 'Cloud' },
+ { name: 'GCP SCC', category: 'Cloud' },
+ { name: 'Okta', category: 'IAM' },
+ { name: 'Azure Entra', category: 'IAM' },
+ { name: 'Duo Security', category: 'IAM' },
+ { name: 'OnePassword', category: 'IAM' },
+ { name: 'Google Workspace', category: 'SaaS' },
+ { name: 'M365 Audit', category: 'SaaS' },
+ { name: 'Slack', category: 'SaaS' },
+ { name: 'Salesforce', category: 'SaaS' },
+ { name: 'GitHub', category: 'VCS' },
+ { name: 'GitLab', category: 'VCS' },
+ { name: 'Cloudflare', category: 'Network' },
+ { name: 'Cisco Umbrella', category: 'Network' },
+];
+
+const TOP_ROW = CONNECTOR_SAMPLE.slice(0, 12);
+const BOTTOM_ROW = CONNECTOR_SAMPLE.slice(12);
+
+const CATEGORY_LABELS: ReadonlyArray<ConnectorPill['category']> = [
+ 'EDR',
+ 'SIEM',
+ 'Cloud',
+ 'IAM',
+ 'SaaS',
+ 'VCS',
+ 'Network',
+];
+
+const CATEGORY_COLOR: Record<ConnectorPill['category'], string> = {
+ EDR: 'bg-severity-critical/10 text-severity-critical ring-severity-critical/30',
+ SIEM: 'bg-brand-500/10 text-brand-300 ring-brand-500/30',
+ Cloud: 'bg-status-live/10 text-status-live ring-status-live/30',
+ IAM: 'bg-landing-accent-violet/10 text-landing-accent-violet ring-landing-accent-violet/30',
+ SaaS: 'bg-severity-medium/10 text-severity-medium ring-severity-medium/30',
+ VCS: 'bg-landing-accent-ember/10 text-landing-accent-ember ring-landing-accent-ember/30',
+ Network: 'bg-fg-muted/10 text-fg-secondary ring-surface-border',
+};
+
+function Pill({ pill }: { pill: ConnectorPill }) {
+ return (
+ <span
+ className={cn(
+ 'inline-flex items-center gap-2 rounded-full border border-surface-border bg-surface-card/70 px-3 py-1.5 text-xs font-medium text-fg-primary backdrop-blur-sm shadow-[0_1px_0_rgba(255,255,255,0.04)_inset]',
+ 'transition-colors duration-200 ease-landing-out-quart hover:border-brand-500/40',
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'inline-flex h-1.5 w-1.5 rounded-full',
+ CATEGORY_COLOR[pill.category].replace(/text-[^\s]+/g, '').replace(/ring-[^\s]+/g, '').replace(/\/\d+/g, ''),
+ )}
+ />
+ {pill.name}
+ <span
+ className={cn(
+ 'rounded-full px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.06em] ring-1 ring-inset',
+ CATEGORY_COLOR[pill.category],
+ )}
+ >
+ {pill.category}
+ </span>
+ </span>
+ );
+}
+
+const SNIPPET = `from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+class MyConnector(BaseConnector):
+ connector_id = "my-saas"
+ connector_category = "saas"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ name=cls.connector_id,
+ label="My SaaS",
+ category=cls.connector_category,
+ fields=[
+ Field("api_url", "text", required=True),
+ Field("api_token", "secret", required=True, secret=True),
+ ],
+ default_poll_interval_seconds=300,
+ )`;
+
+export function ConnectorsMarquee() {
+ return (
+ <section
+ id="connectors"
+ aria-labelledby="connectors-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <div className="mx-auto max-w-3xl text-center">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ Plug in everything
+ </p>
+ <h2
+ id="connectors-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ 69 connectors. 6,998 detections. 62 playbook packs.
+ </h2>
+ <p className="mt-4 text-base leading-relaxed text-fg-secondary sm:text-lg">
+ Every connector renders a schema-driven form, encrypts its
+ secrets at the application layer, and starts polling on a
+ per-instance schedule. When the catalogue doesn&apos;t have what
+ you need, write your own — the plugin SDKs are MIT and the
+ marketplace ships your manifest on the next index build.
+ </p>
+ </div>
+
+ <ul className="mx-auto mt-8 flex max-w-3xl flex-wrap items-center justify-center gap-2">
+ {CATEGORY_LABELS.map((category) => (
+ <li key={category}>
+ <span
+ className={cn(
+ 'inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.1em] ring-1 ring-inset',
+ CATEGORY_COLOR[category],
+ )}
+ >
+ {category}
+ </span>
+ </li>
+ ))}
+ </ul>
+
+ <p className="mt-10 text-center text-xs font-semibold uppercase tracking-[0.18em] text-fg-subtle">
+ A small sample
+ </p>
+
+ <div className="relative mt-4 space-y-3">
+ <div
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-y-0 left-0 z-10 w-12 bg-gradient-to-r from-surface-base to-transparent sm:w-24"
+ />
+ <div
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-y-0 right-0 z-10 w-12 bg-gradient-to-l from-surface-base to-transparent sm:w-24"
+ />
+ <Marquee>
+ {TOP_ROW.map((pill) => (
+ <Pill key={pill.name} pill={pill} />
+ ))}
+ </Marquee>
+ <Marquee reverse>
+ {BOTTOM_ROW.map((pill) => (
+ <Pill key={pill.name} pill={pill} />
+ ))}
+ </Marquee>
+ </div>
+
+ <div className="mx-auto mt-16 max-w-5xl">
+ <div className="grid gap-6 lg:grid-cols-[1fr_1.5fr] lg:items-center">
+ <div>
+ <h3 className="text-2xl font-bold tracking-tight text-fg-primary sm:text-3xl">
+ Write a connector in 50 lines.
+ </h3>
+ <p className="mt-3 text-sm leading-relaxed text-fg-secondary">
+ Each connector is a Python class that declares a schema,
+ tests its credentials, polls on a schedule, and normalises
+ events into OCSF. The plugin SDKs ship for Python,
+ TypeScript, and Go.
+ </p>
+ <Link
+ href="https://docs.aisoc.dev/connectors/sdk"
+ className="group mt-5 inline-flex items-center gap-1 text-sm font-semibold text-brand-300 transition-colors duration-200 hover:text-brand-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ Read the connector SDK
+ <ArrowRight
+ className="h-3.5 w-3.5 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ </div>
+ <pre
+ aria-label="Example Python connector"
+ className="overflow-x-auto rounded-2xl border border-surface-border bg-surface-card/80 p-5 font-mono text-[12px] leading-relaxed text-fg-secondary shadow-[0_18px_48px_-32px_rgba(15,23,42,0.7)]"
+ >
+ <code>{SNIPPET}</code>
+ </pre>
+ </div>
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/DemoEmbed.tsx b/apps/web/src/components/landing/sections/DemoEmbed.tsx
new file mode 100644
index 000000000..22fdc25fc
--- /dev/null
+++ b/apps/web/src/components/landing/sections/DemoEmbed.tsx
@@ -0,0 +1,301 @@
+'use client';
+
+/**
+ * "See it work" — `demo` section from §6.5 of the brief.
+ *
+ * Renders a stylised mock of the Investigation Ledger panel as it
+ * appears in the console mid-investigation (INC-RT-001 / LockBit 3.0,
+ * step 14 of 32). This is intentionally a mock — not a real Cytoscape
+ * embed — so the section can be statically rendered, parses no JSON at
+ * load, and adds zero JS to the landing route's First Load bundle.
+ *
+ * The actual live demo lives at `/dashboard` (per the existing
+ * onboarding-first surface). When/if the buyer-facing tour wants the
+ * real Cytoscape mount, swap this component for a `next/dynamic` lazy
+ * import of `RealtimeGraph` gated behind an `IntersectionObserver`, per
+ * §12 of the brief.
+ *
+ * Animation: ledger rows fade-in-up with 60 ms stagger when the panel
+ * enters the viewport; the cursor blinks at 1 Hz on the active step
+ * with a single CSS `step-end` animation; `BorderBeam` traces the
+ * panel chrome on a 14 s loop. All three respect `prefers-reduced-motion`.
+ */
+
+import Link from 'next/link';
+import { motion, useReducedMotion } from 'framer-motion';
+import { ArrowRight, Clock, Cpu, Database } from 'lucide-react';
+import { BorderBeam } from '@/components/magicui/BorderBeam';
+import { cn } from '@/lib/utils';
+
+interface LedgerStep {
+ step: number;
+ agent: 'Detect' | 'Triage' | 'Hunt' | 'Respond';
+ action: string;
+ result: string;
+ state: 'complete' | 'active' | 'queued';
+}
+
+const STEPS: ReadonlyArray<LedgerStep> = [
+ {
+ step: 11,
+ agent: 'Detect',
+ action: 'fuse_signals(host=WS-RT-014)',
+ result: '4 alerts → INC-RT-001',
+ state: 'complete',
+ },
+ {
+ step: 12,
+ agent: 'Triage',
+ action: 'classify(family="LockBit 3.0")',
+ result: 'confidence 0.93',
+ state: 'complete',
+ },
+ {
+ step: 13,
+ agent: 'Triage',
+ action: 'enrich(user=oliver.tan, asset=WS-RT-014)',
+ result: 'priv=admin · last login 03:21',
+ state: 'complete',
+ },
+ {
+ step: 14,
+ agent: 'Hunt',
+ action: 'kql("SecurityEvent EventID=4688 …")',
+ result: '38 process events · 7 lateral',
+ state: 'active',
+ },
+ {
+ step: 15,
+ agent: 'Respond',
+ action: 'plan(containment, dry_run=true)',
+ result: 'pending L2 approval',
+ state: 'queued',
+ },
+];
+
+const AGENT_COLOR: Record<LedgerStep['agent'], string> = {
+ Detect: 'text-brand-300 bg-brand-500/10 ring-brand-500/30',
+ Triage:
+ 'text-landing-accent-violet bg-landing-accent-violet/10 ring-landing-accent-violet/30',
+ Hunt: 'text-brand-300 bg-brand-500/15 ring-brand-300/30',
+ Respond:
+ 'text-landing-accent-ember bg-landing-accent-ember/10 ring-landing-accent-ember/30',
+};
+
+const STATE_DOT: Record<LedgerStep['state'], string> = {
+ complete: 'bg-status-live',
+ active: 'bg-brand-400 animate-pulse',
+ queued: 'bg-status-idle',
+};
+
+export function DemoEmbed() {
+ const prefersReducedMotion = useReducedMotion();
+ const initial = prefersReducedMotion ? false : { opacity: 0, y: 12 };
+
+ return (
+ <section
+ id="demo"
+ aria-labelledby="demo-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <div className="mx-auto max-w-3xl text-center">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ See it work
+ </p>
+ <h2
+ id="demo-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ Watch AiSOC investigate a live ransomware incident.
+ </h2>
+ <p className="mt-4 text-base leading-relaxed text-fg-secondary sm:text-lg">
+ INC-RT-001 is a LockBit 3.0 case that ships with every install.
+ The ledger streams every prompt, tool call, and decision the
+ agent made. Scrub the timeline, pause on any step, fork the
+ rationale into a ticket.
+ </p>
+ </div>
+
+ <motion.figure
+ initial={initial}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{ duration: 0.6, ease: [0.16, 1, 0.3, 1] }}
+ className="relative mx-auto mt-12 max-w-5xl lg:mt-16"
+ >
+ <div className="relative overflow-hidden rounded-2xl border border-surface-border bg-surface-card/80 shadow-[0_30px_80px_-32px_rgba(15,23,42,0.8)] backdrop-blur-sm">
+ <header className="flex items-center justify-between gap-3 border-b border-surface-border px-4 py-3 sm:px-6">
+ <div className="flex items-center gap-2">
+ <span
+ aria-hidden="true"
+ className="inline-flex h-2.5 w-2.5 rounded-full bg-severity-critical"
+ />
+ <span
+ aria-hidden="true"
+ className="inline-flex h-2.5 w-2.5 rounded-full bg-status-warn"
+ />
+ <span
+ aria-hidden="true"
+ className="inline-flex h-2.5 w-2.5 rounded-full bg-status-live"
+ />
+ </div>
+ <p className="hidden text-xs font-mono text-fg-muted sm:block">
+ aisoc.dev/cases/INC-RT-001?tab=ledger
+ </p>
+ <p className="text-[10px] font-semibold uppercase tracking-[0.18em] text-fg-subtle">
+ Live
+ </p>
+ </header>
+
+ <div className="grid gap-0 md:grid-cols-[1fr_320px]">
+ <div className="px-4 py-5 sm:px-6 sm:py-6">
+ <div className="flex flex-wrap items-center gap-2 text-xs font-medium">
+ <span className="inline-flex items-center gap-2 rounded-full bg-severity-critical/10 px-2.5 py-1 text-severity-critical ring-1 ring-inset ring-severity-critical/30">
+ <span
+ aria-hidden="true"
+ className="inline-block h-1.5 w-1.5 rounded-full bg-severity-critical"
+ />
+ Critical
+ </span>
+ <span className="text-fg-muted">INC-RT-001</span>
+ <span className="text-fg-subtle">·</span>
+ <span className="text-fg-muted">LockBit 3.0</span>
+ <span className="text-fg-subtle">·</span>
+ <span className="text-fg-muted">step 14 of 32</span>
+ </div>
+
+ <ol className="mt-5 space-y-2 font-mono">
+ {STEPS.map((step, idx) => (
+ <motion.li
+ key={step.step}
+ initial={initial}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{
+ duration: 0.45,
+ ease: [0.16, 1, 0.3, 1],
+ delay: 0.15 + idx * 0.07,
+ }}
+ className={cn(
+ 'flex items-start gap-3 rounded-lg px-3 py-2 text-[11.5px] leading-relaxed',
+ step.state === 'active' &&
+ 'bg-brand-500/5 ring-1 ring-inset ring-brand-500/30',
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'mt-1.5 inline-block h-2 w-2 shrink-0 rounded-full',
+ STATE_DOT[step.state],
+ )}
+ />
+ <span className="w-8 shrink-0 text-fg-subtle">
+ #{step.step}
+ </span>
+ <span
+ className={cn(
+ 'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.08em] ring-1 ring-inset',
+ AGENT_COLOR[step.agent],
+ )}
+ >
+ {step.agent}
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-fg-primary">
+ {step.action}
+ {step.state === 'active' && (
+ <span
+ aria-hidden="true"
+ className="ml-1 inline-block h-3 w-2 translate-y-0.5 bg-brand-400 motion-safe:animate-pulse motion-reduce:opacity-50"
+ />
+ )}
+ </p>
+ <p className="text-fg-muted">→ {step.result}</p>
+ </div>
+ </motion.li>
+ ))}
+ </ol>
+ </div>
+
+ <aside className="border-t border-surface-border bg-surface-base/60 px-4 py-5 sm:px-6 sm:py-6 md:border-l md:border-t-0">
+ <p className="text-[10px] font-semibold uppercase tracking-[0.18em] text-fg-subtle">
+ Investigation summary
+ </p>
+ <dl className="mt-4 space-y-4 text-xs">
+ <div className="flex items-start gap-3">
+ <Clock
+ className="mt-0.5 h-3.5 w-3.5 text-brand-300"
+ aria-hidden="true"
+ />
+ <div>
+ <dt className="text-fg-subtle">Elapsed</dt>
+ <dd className="font-mono text-fg-primary">00:01:47</dd>
+ </div>
+ </div>
+ <div className="flex items-start gap-3">
+ <Cpu
+ className="mt-0.5 h-3.5 w-3.5 text-brand-300"
+ aria-hidden="true"
+ />
+ <div>
+ <dt className="text-fg-subtle">LLM spend</dt>
+ <dd className="font-mono text-fg-primary">$0.084</dd>
+ <dd className="text-fg-muted">claude-4-haiku · 14 calls</dd>
+ </div>
+ </div>
+ <div className="flex items-start gap-3">
+ <Database
+ className="mt-0.5 h-3.5 w-3.5 text-brand-300"
+ aria-hidden="true"
+ />
+ <div>
+ <dt className="text-fg-subtle">Touched</dt>
+ <dd className="font-mono text-fg-primary">4 hosts · 2 users</dd>
+ <dd className="text-fg-muted">38 process events</dd>
+ </div>
+ </div>
+ </dl>
+ <hr className="my-5 border-surface-border" />
+ <p className="text-[10px] font-semibold uppercase tracking-[0.18em] text-fg-subtle">
+ Next planned action
+ </p>
+ <p className="mt-2 text-xs leading-relaxed text-fg-secondary">
+ Quarantine WS-RT-014 + force-rotate <span className="font-mono">oliver.tan</span> session.
+ L2 approval requested in <span className="font-mono">#soc-approvals</span>.
+ </p>
+ </aside>
+ </div>
+ </div>
+ {!prefersReducedMotion && (
+ <BorderBeam duration={14} size={220} colorFrom="#3b82f6" colorTo="#8b5cf6" />
+ )}
+ <figcaption className="sr-only">
+ INC-RT-001 LockBit 3.0 investigation, paused on step 14 of 32 inside
+ the AiSOC ledger view.
+ </figcaption>
+ </motion.figure>
+
+ <div className="mx-auto mt-10 flex max-w-3xl flex-col items-center justify-center gap-3 text-center sm:flex-row sm:gap-5">
+ <Link
+ href="https://github.com/beenuar/AiSOC#5-minute-demo"
+ className="group inline-flex h-11 items-center gap-2 rounded-md bg-gradient-to-br from-brand-500 to-brand-700 px-6 text-sm font-semibold text-white shadow-[0_1px_0_rgba(255,255,255,0.18)_inset] transition-shadow duration-200 ease-landing-out-quart hover:shadow-[0_12px_32px_-12px_rgba(59,130,246,0.65)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ Run this yourself in 5 minutes
+ <ArrowRight
+ className="h-4 w-4 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ <Link
+ href="https://docs.aisoc.dev/architecture"
+ className="inline-flex items-center gap-1 text-sm font-medium text-fg-muted transition-colors duration-200 hover:text-fg-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ Read the architecture
+ <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
+ </Link>
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/DeployOptions.tsx b/apps/web/src/components/landing/sections/DeployOptions.tsx
new file mode 100644
index 000000000..2023c44bc
--- /dev/null
+++ b/apps/web/src/components/landing/sections/DeployOptions.tsx
@@ -0,0 +1,195 @@
+'use client';
+
+/**
+ * "Run AiSOC where your data is allowed to live" — `deploy` section
+ * from §6.10 of the brief.
+ *
+ * Three deploy-path cards in a 3-up grid (single column below `md`).
+ *
+ * 1. Managed (waitlist) — host on app.aisoc.dev.
+ * 2. Self-host (recommended) — Render / Docker / Fly.io / Helm /
+ * AWS Terraform. The middle card is highlighted via `ShineBorder`.
+ * 3. Sovereign / air-gap — `AISOC_AIRGAPPED=true`, Ollama sidecar.
+ *
+ * Each card exposes the same four-line stat strip (Time to live / LLM /
+ * Residency / Body) so a buyer can scan horizontally without
+ * re-orienting per card.
+ */
+
+import Link from 'next/link';
+import { motion, useReducedMotion } from 'framer-motion';
+import { ArrowRight, Cloud, Lock, Server } from 'lucide-react';
+import type { ComponentType, SVGProps } from 'react';
+import { ShineBorder } from '@/components/magicui/ShineBorder';
+import { cn } from '@/lib/utils';
+
+interface DeployOption {
+ id: 'managed' | 'self-host' | 'sovereign';
+ icon: ComponentType<SVGProps<SVGSVGElement>>;
+ title: string;
+ recommended?: boolean;
+ timeToLive: string;
+ llm: string;
+ residency: string;
+ body: string;
+ cta: { label: string; href: string };
+}
+
+const OPTIONS: ReadonlyArray<DeployOption> = [
+ {
+ id: 'managed',
+ icon: Cloud,
+ title: 'Managed',
+ timeToLive: 'Same day — once seats open',
+ llm: 'Cloud APIs · BYO endpoint',
+ residency: 'EU · US · India',
+ body:
+ 'We host it. You log in. SOC 2 and GDPR are on the roadmap. Join the waitlist for early access.',
+ cta: { label: 'Join the waitlist', href: '/waitlist' },
+ },
+ {
+ id: 'self-host',
+ icon: Server,
+ title: 'Self-host',
+ recommended: true,
+ timeToLive: 'Five minutes (warm Docker)',
+ llm: 'Cloud APIs · local Ollama · BYO',
+ residency: 'Operator-defined',
+ body:
+ 'Render one-click, Docker Compose, Fly.io, Helm, AWS Terraform — pick any. The slim demo stack ships pre-seeded with a LockBit case mid-investigation.',
+ cta: { label: 'Self-host on GitHub', href: 'https://github.com/beenuar/AiSOC' },
+ },
+ {
+ id: 'sovereign',
+ icon: Lock,
+ title: 'Sovereign / air-gap',
+ timeToLive: 'An afternoon',
+ llm: 'Local Ollama · BYO LiteLLM',
+ residency: 'Operator-defined',
+ body:
+ 'Set AISOC_AIRGAPPED=true and the platform refuses every outbound call. The Ollama sidecar ships a pinned local model so the demo seed runs end-to-end with zero external calls.',
+ cta: { label: 'Read the air-gap guide', href: '/sovereign' },
+ },
+];
+
+function OptionCard({
+ option,
+ index,
+ reduced,
+}: {
+ option: DeployOption;
+ index: number;
+ reduced: boolean | null;
+}) {
+ const Icon = option.icon;
+ return (
+ <motion.li
+ initial={reduced ? false : { opacity: 0, y: 16 }}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{
+ duration: 0.55,
+ ease: [0.16, 1, 0.3, 1],
+ delay: index * 0.08,
+ }}
+ className={cn(
+ 'relative flex flex-col gap-4 rounded-2xl border border-surface-border bg-surface-card/70 p-6 backdrop-blur-sm',
+ option.recommended &&
+ 'shadow-[0_24px_64px_-24px_rgba(59,130,246,0.45)]',
+ )}
+ >
+ {option.recommended && <ShineBorder duration={14} borderWidth={1} />}
+ <div className="relative flex items-center justify-between gap-3">
+ <span
+ aria-hidden="true"
+ className="inline-flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500/20 to-landing-accent-violet/20 text-brand-300 ring-1 ring-inset ring-brand-500/30"
+ >
+ <Icon className="h-5 w-5" />
+ </span>
+ {option.recommended && (
+ <span className="inline-flex items-center rounded-full bg-brand-500/15 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-brand-300 ring-1 ring-inset ring-brand-500/40">
+ Recommended
+ </span>
+ )}
+ </div>
+ <h3 className="relative text-xl font-bold tracking-tight text-fg-primary">
+ {option.title}
+ </h3>
+ <dl className="relative space-y-2 text-xs">
+ <div className="flex items-baseline justify-between gap-2 border-b border-surface-border pb-2">
+ <dt className="font-semibold uppercase tracking-[0.12em] text-fg-subtle">
+ Time to live
+ </dt>
+ <dd className="text-right text-fg-primary">{option.timeToLive}</dd>
+ </div>
+ <div className="flex items-baseline justify-between gap-2 border-b border-surface-border pb-2">
+ <dt className="font-semibold uppercase tracking-[0.12em] text-fg-subtle">
+ LLM
+ </dt>
+ <dd className="text-right text-fg-primary">{option.llm}</dd>
+ </div>
+ <div className="flex items-baseline justify-between gap-2">
+ <dt className="font-semibold uppercase tracking-[0.12em] text-fg-subtle">
+ Residency
+ </dt>
+ <dd className="text-right text-fg-primary">{option.residency}</dd>
+ </div>
+ </dl>
+ <p className="relative text-sm leading-relaxed text-fg-secondary">
+ {option.body}
+ </p>
+ <Link
+ href={option.cta.href}
+ className={cn(
+ 'group relative mt-auto inline-flex h-10 items-center justify-center gap-1 rounded-md px-4 text-sm font-semibold transition-shadow duration-200 ease-landing-out-quart focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base',
+ option.recommended
+ ? 'bg-gradient-to-br from-brand-500 to-brand-700 text-white shadow-[0_1px_0_rgba(255,255,255,0.18)_inset] hover:shadow-[0_12px_32px_-12px_rgba(59,130,246,0.65)]'
+ : 'border border-surface-border bg-surface-raised/60 text-fg-primary hover:border-brand-500/40',
+ )}
+ >
+ {option.cta.label}
+ <ArrowRight
+ className="h-3.5 w-3.5 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ </motion.li>
+ );
+}
+
+export function DeployOptions() {
+ const prefersReducedMotion = useReducedMotion();
+
+ return (
+ <section
+ id="deploy"
+ aria-labelledby="deploy-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <div className="mx-auto max-w-3xl text-center">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ Run AiSOC where your data is allowed to live
+ </p>
+ <h2
+ id="deploy-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ Three deploy paths. Same code.
+ </h2>
+ </div>
+
+ <ul className="mt-12 grid gap-4 sm:gap-6 md:grid-cols-3 lg:mt-16 lg:gap-8">
+ {OPTIONS.map((option, idx) => (
+ <OptionCard
+ key={option.id}
+ option={option}
+ index={idx}
+ reduced={prefersReducedMotion}
+ />
+ ))}
+ </ul>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/Faq.tsx b/apps/web/src/components/landing/sections/Faq.tsx
new file mode 100644
index 000000000..04de4d26c
--- /dev/null
+++ b/apps/web/src/components/landing/sections/Faq.tsx
@@ -0,0 +1,156 @@
+'use client';
+
+/**
+ * "FAQ" — `faq` section from §6.14 of the brief.
+ *
+ * Hand-rolled accordion (no Radix dependency yet) that satisfies the
+ * brief's a11y contract:
+ *
+ * - Each row is a `<button>` inside a `<dt>`, exposing `aria-expanded`
+ * and `aria-controls`. The associated `<dd>` carries the matching
+ * `id` and `role="region"`.
+ * - Keyboard: Tab/Shift-Tab between rows, Enter or Space toggles,
+ * focus-visible ring on the trigger.
+ * - Animation: only the body gets a height transition, so the click
+ * stays snappy on slower devices. The chevron rotates 180°. Under
+ * `prefers-reduced-motion` both transitions are dropped via
+ * `motion-reduce:` utilities.
+ *
+ * All eight Q/A pairs are lifted verbatim from `landing-page-content.md`.
+ */
+
+import { useId, useState } from 'react';
+import { ChevronDown } from 'lucide-react';
+import { cn } from '@/lib/utils';
+
+interface QA {
+ q: string;
+ a: string;
+}
+
+const FAQS: ReadonlyArray<QA> = [
+ {
+ q: 'Is AiSOC really open source?',
+ a:
+ 'Yes — the agent, the connectors, the detection rules, the benchmark dataset, and every piece of infrastructure code are MIT-licensed. There is no private fork.',
+ },
+ {
+ q: 'What does the agent need to call out to?',
+ a:
+ 'By default the Triage and Hunt agents call an LLM provider you configure (OpenAI, Anthropic, Azure, Bedrock, or a private LiteLLM gateway). Set AISOC_AIRGAPPED=true and the platform refuses every outbound call; an Ollama sidecar runs a local model in-cluster.',
+ },
+ {
+ q: 'Where does my data live?',
+ a:
+ 'Self-host: wherever you point Postgres, ClickHouse, and Redis. Managed: EU, US, or India region you pick at signup. Sovereign: a single-tenant VPC you control. The connector vault encrypts secrets with Fernet AES-128-CBC + HMAC-SHA256.',
+ },
+ {
+ q: 'Can the agent take real-world action without a human?',
+ a:
+ 'Only inside the maturity tier you configure. L0 keeps the agent advisory only; L2 (the production default) lets it run reversible containment actions; L4 allows whitelisted closed-loop actions. Every action class is gated against blast radius.',
+ },
+ {
+ q: 'How is this benchmarked?',
+ a:
+ 'Five pytest suites in services/agents/tests/ run on every PR. Three are substrate self-consistency gates; the fourth is a real measurement against a fixed 1,000-alert noisy stream; the fifth is a coverage gate on the synthetic telemetry corpus. The methodology page documents what each suite measures and what it does not.',
+ },
+ {
+ q: 'How do connectors work?',
+ a:
+ 'Each connector is a Python class that declares a schema, tests its credentials, polls on a schedule, and normalises events into OCSF. 69 ship in the box. The plugin SDKs (Python, TypeScript, Go) let you author your own in roughly 50 lines.',
+ },
+ {
+ q: 'What runs in production today?',
+ a:
+ 'Beta deployments through reference partners and an internal demo on tryaisoc.com. The managed waitlist at app.aisoc.dev is the route for hosted customers.',
+ },
+ {
+ q: 'Why not just use an existing AI SOC vendor?',
+ a:
+ "Use whichever tools fit your risk and procurement model. AiSOC's contribution is making the agent itself open, the decisions step-by-step auditable, and the benchmark reproducible — three guarantees closed-source platforms typically do not offer.",
+ },
+];
+
+function FaqRow({
+ qa,
+ index,
+ idBase,
+}: {
+ qa: QA;
+ index: number;
+ idBase: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const buttonId = `${idBase}-q-${index}`;
+ const panelId = `${idBase}-a-${index}`;
+
+ return (
+ <div className="border-b border-surface-border last:border-b-0">
+ <dt>
+ <button
+ id={buttonId}
+ type="button"
+ aria-expanded={open}
+ aria-controls={panelId}
+ onClick={() => setOpen((prev) => !prev)}
+ className="flex w-full items-start justify-between gap-4 py-5 text-left transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base sm:py-6"
+ >
+ <span className="text-base font-semibold text-fg-primary sm:text-lg">
+ {qa.q}
+ </span>
+ <ChevronDown
+ className={cn(
+ 'mt-1 h-5 w-5 flex-none text-fg-muted transition-transform duration-300 ease-landing-out-quart motion-reduce:transition-none',
+ open && 'rotate-180 text-brand-300',
+ )}
+ aria-hidden="true"
+ />
+ </button>
+ </dt>
+ <dd
+ id={panelId}
+ role="region"
+ aria-labelledby={buttonId}
+ hidden={!open}
+ className={cn(
+ 'overflow-hidden text-sm leading-relaxed text-fg-secondary sm:text-base',
+ open && 'pb-5 sm:pb-6',
+ )}
+ >
+ {qa.a}
+ </dd>
+ </div>
+ );
+}
+
+export function Faq() {
+ const idBase = useId();
+
+ return (
+ <section
+ id="faq"
+ aria-labelledby="faq-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-3xl px-4 sm:px-6 lg:px-8">
+ <div className="text-center">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ Questions, asked honestly
+ </p>
+ <h2
+ id="faq-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ Frequently asked.
+ </h2>
+ </div>
+
+ <dl className="mt-12 lg:mt-14">
+ {FAQS.map((qa, idx) => (
+ <FaqRow key={qa.q} qa={qa} index={idx} idBase={idBase} />
+ ))}
+ </dl>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/FeatureGrid.tsx b/apps/web/src/components/landing/sections/FeatureGrid.tsx
new file mode 100644
index 000000000..03eff482b
--- /dev/null
+++ b/apps/web/src/components/landing/sections/FeatureGrid.tsx
@@ -0,0 +1,249 @@
+'use client';
+
+/**
+ * Three feature deep-dive grids — `features` section from §6.7 of the
+ * brief.
+ *
+ * Grid 1 — Detect & Investigate (6 tiles)
+ * Grid 2 — Hunt & Respond (6 tiles)
+ * Grid 3 — Operate at scale (6 tiles)
+ *
+ * Layout is 3-up at ≥1024 px, 2-up at ≥640 px, single column on phone.
+ * Each tile gets a Lucide icon, a one-line title, and a single-sentence
+ * body — copy lifted verbatim from `landing-page-content.md`.
+ *
+ * Reveal: per-grid header staggers in first, then each tile fades up at
+ * 60 ms intervals when its row enters the viewport. The `once: true`
+ * viewport keeps a re-scrolled section from re-firing the animation.
+ */
+
+import { motion, useReducedMotion } from 'framer-motion';
+import {
+ AlertOctagon,
+ Boxes,
+ CalendarClock,
+ ClipboardList,
+ CloudCog,
+ Code2,
+ DollarSign,
+ FileCog,
+ KeyRound,
+ Network,
+ PlugZap,
+ Receipt,
+ ScrollText,
+ ShieldHalf,
+ Sigma,
+ Telescope,
+ TerminalSquare,
+ Workflow,
+} from 'lucide-react';
+import type { ComponentType, SVGProps } from 'react';
+import { cn } from '@/lib/utils';
+
+interface Tile {
+ icon: ComponentType<SVGProps<SVGSVGElement>>;
+ title: string;
+ body: string;
+}
+
+interface FeatureBlock {
+ id: 'detect' | 'hunt' | 'operate';
+ title: string;
+ tiles: ReadonlyArray<Tile>;
+}
+
+const BLOCKS: ReadonlyArray<FeatureBlock> = [
+ {
+ id: 'detect',
+ title: 'Detect & investigate',
+ tiles: [
+ {
+ icon: Sigma,
+ title: 'Fusion engine.',
+ body: 'Real-time dedup, ML scoring, per-alert confidence.',
+ },
+ {
+ icon: AlertOctagon,
+ title: 'Entity-risk rollup (RBA).',
+ body: 'Time-decayed risk per user, host, IP, domain — 50:1 alert-to-incident.',
+ },
+ {
+ icon: FileCog,
+ title: 'Native detections.',
+ body: '6,998 YAML rules across cloud, endpoint, identity, network, application, and data-exfil.',
+ },
+ {
+ icon: ScrollText,
+ title: 'Investigation Ledger.',
+ body: 'Replayable, step-by-step record of every agent decision per case.',
+ },
+ {
+ icon: Network,
+ title: 'Attack-chain timeline.',
+ body: 'Cytoscape over the Neo4j subgraph — see the path, not just the alerts.',
+ },
+ {
+ icon: KeyRound,
+ title: 'Effective permissions.',
+ body: 'What a principal can actually do across AWS, Azure, GCP, Okta, Google Workspace.',
+ },
+ ],
+ },
+ {
+ id: 'hunt',
+ title: 'Hunt & respond',
+ tiles: [
+ {
+ icon: Telescope,
+ title: 'NL hunt at /hunt.',
+ body: 'Ask in English. Get ES|QL, KQL, and SPL back.',
+ },
+ {
+ icon: CalendarClock,
+ title: 'Hunt-as-Code (YAML).',
+ body: 'Hypothesis-driven, MITRE-tagged hunts on a cron.',
+ },
+ {
+ icon: Workflow,
+ title: 'Response planner.',
+ body: 'Containment → eradication → recovery, dry-run by default.',
+ },
+ {
+ icon: ClipboardList,
+ title: 'ChatOps approvals.',
+ body: 'Slack Block Kit + Teams Adaptive Cards, HMAC signed.',
+ },
+ {
+ icon: ShieldHalf,
+ title: 'L0–L4 maturity dial.',
+ body: 'One per-tenant setting governs every action class. Auditable.',
+ },
+ {
+ icon: CloudCog,
+ title: 'SOAR exec.',
+ body: 'Blast-radius gated playbook execution with full rollback.',
+ },
+ ],
+ },
+ {
+ id: 'operate',
+ title: 'Operate at scale',
+ tiles: [
+ {
+ icon: PlugZap,
+ title: '69 click-and-connect connectors.',
+ body: 'EDR · SIEM · cloud · IAM · SaaS · VCS · network.',
+ },
+ {
+ icon: Boxes,
+ title: 'Marketplace.',
+ body: '7,117 community items — detections, playbooks, plugins.',
+ },
+ {
+ icon: Code2,
+ title: 'Plugin SDKs.',
+ body: 'Python, TypeScript, Go — build a connector in 50 lines.',
+ },
+ {
+ icon: DollarSign,
+ title: 'MCP server.',
+ body: 'Use AiSOC from Claude, Cursor, Continue, Cody — 11 tools.',
+ },
+ {
+ icon: TerminalSquare,
+ title: 'Cursor extension.',
+ body: 'Investigate alerts without leaving your editor.',
+ },
+ {
+ icon: Receipt,
+ title: 'Cost telemetry.',
+ body: 'Per-call tokens and USD captured in the run ledger.',
+ },
+ ],
+ },
+];
+
+function FeatureTile({
+ tile,
+ index,
+ reduced,
+}: {
+ tile: Tile;
+ index: number;
+ reduced: boolean | null;
+}) {
+ const Icon = tile.icon;
+ return (
+ <motion.li
+ initial={reduced ? false : { opacity: 0, y: 12 }}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{
+ duration: 0.45,
+ ease: [0.16, 1, 0.3, 1],
+ delay: (index % 6) * 0.06,
+ }}
+ className={cn(
+ 'group relative flex flex-col gap-2 rounded-xl border border-surface-border bg-surface-card/60 p-5 backdrop-blur-sm',
+ 'transition-[border-color,transform] duration-300 ease-landing-out-quart hover:-translate-y-0.5 hover:border-brand-500/40',
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-brand-500/10 text-brand-300 ring-1 ring-inset ring-brand-500/30"
+ >
+ <Icon className="h-4 w-4" />
+ </span>
+ <h3 className="mt-1 text-sm font-semibold text-fg-primary">{tile.title}</h3>
+ <p className="text-xs leading-relaxed text-fg-secondary">{tile.body}</p>
+ </motion.li>
+ );
+}
+
+export function FeatureGrid() {
+ const prefersReducedMotion = useReducedMotion();
+
+ return (
+ <section
+ id="features"
+ aria-labelledby="features-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <h2
+ id="features-heading"
+ className="sr-only"
+ >
+ Feature deep-dive
+ </h2>
+ <div className="space-y-16 lg:space-y-20">
+ {BLOCKS.map((block, blockIdx) => (
+ <div key={block.id} aria-labelledby={`features-${block.id}`}>
+ <motion.h3
+ id={`features-${block.id}`}
+ initial={prefersReducedMotion ? false : { opacity: 0, y: 10 }}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-20%' }}
+ transition={{ duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
+ className="text-2xl font-bold tracking-tight text-fg-primary sm:text-3xl"
+ >
+ {block.title}
+ </motion.h3>
+ <ul className="mt-6 grid gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3">
+ {block.tiles.map((tile, idx) => (
+ <FeatureTile
+ key={`${block.id}-${tile.title}-${blockIdx}-${idx}`}
+ tile={tile}
+ index={idx}
+ reduced={prefersReducedMotion}
+ />
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/FinalCta.tsx b/apps/web/src/components/landing/sections/FinalCta.tsx
new file mode 100644
index 000000000..876249f70
--- /dev/null
+++ b/apps/web/src/components/landing/sections/FinalCta.tsx
@@ -0,0 +1,84 @@
+'use client';
+
+/**
+ * "Ship the SOC you wish you had." — `final-cta` section from §6.15.
+ *
+ * Closing CTA band over the `landing-grad-cta` gradient with a
+ * `BackgroundBeams` mesh on top. Two CTAs (Try managed / Self-host on
+ * GitHub) plus the microcopy from the content doc.
+ */
+
+import Link from 'next/link';
+import { motion, useReducedMotion } from 'framer-motion';
+import { ArrowRight } from 'lucide-react';
+import { BackgroundBeams } from '@/components/aceternity/BackgroundBeams';
+import { GithubMark } from './icons';
+
+export function FinalCta() {
+ const prefersReducedMotion = useReducedMotion();
+
+ return (
+ <section
+ id="cta"
+ aria-labelledby="cta-heading"
+ className="relative isolate overflow-hidden py-24 sm:py-28 lg:py-32"
+ >
+ <div className="absolute inset-0 -z-10 bg-landing-grad-cta opacity-[0.18]" aria-hidden="true" />
+ <div className="absolute inset-0 -z-10" aria-hidden="true">
+ <BackgroundBeams />
+ </div>
+
+ <div className="mx-auto max-w-3xl px-4 text-center sm:px-6 lg:px-8">
+ <motion.h2
+ id="cta-heading"
+ initial={prefersReducedMotion ? false : { opacity: 0, y: 16 }}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{ duration: 0.6, ease: [0.16, 1, 0.3, 1] }}
+ className="text-4xl font-bold tracking-tight text-fg-primary sm:text-5xl lg:text-[56px] lg:leading-[1.05] lg:tracking-[-0.02em]"
+ >
+ Ship the SOC you wish you had.
+ </motion.h2>
+ <motion.p
+ initial={prefersReducedMotion ? false : { opacity: 0, y: 12 }}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{ duration: 0.55, ease: [0.16, 1, 0.3, 1], delay: 0.08 }}
+ className="mx-auto mt-5 max-w-xl text-base leading-relaxed text-fg-secondary sm:text-lg"
+ >
+ Either path lands you on a working SOC, not a blank dashboard.
+ </motion.p>
+ <motion.div
+ initial={prefersReducedMotion ? false : { opacity: 0, y: 12 }}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{ duration: 0.55, ease: [0.16, 1, 0.3, 1], delay: 0.16 }}
+ className="mt-8 flex flex-col items-center justify-center gap-3 sm:flex-row sm:gap-4"
+ >
+ <Link
+ href="/waitlist"
+ className="group inline-flex h-11 items-center justify-center gap-2 rounded-md bg-gradient-to-br from-brand-500 to-brand-700 px-6 text-sm font-semibold text-white shadow-[0_1px_0_rgba(255,255,255,0.18)_inset] transition-shadow duration-200 ease-landing-out-quart hover:shadow-[0_18px_44px_-12px_rgba(59,130,246,0.65)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ Try managed
+ <ArrowRight
+ className="h-3.5 w-3.5 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ <Link
+ href="https://github.com/beenuar/AiSOC"
+ rel="noreferrer"
+ target="_blank"
+ className="inline-flex h-11 items-center justify-center gap-2 rounded-md border border-surface-border bg-surface-card/80 px-6 text-sm font-semibold text-fg-primary backdrop-blur-sm transition-colors duration-200 hover:border-brand-500/40 hover:text-brand-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ <GithubMark className="h-4 w-4" />
+ Self-host on GitHub
+ </Link>
+ </motion.div>
+ <p className="mt-6 text-xs text-fg-muted">
+ MIT-licensed · No credit card · Air-gap on a flag
+ </p>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/Footer.tsx b/apps/web/src/components/landing/sections/Footer.tsx
new file mode 100644
index 000000000..51b827ab9
--- /dev/null
+++ b/apps/web/src/components/landing/sections/Footer.tsx
@@ -0,0 +1,175 @@
+'use client';
+
+/**
+ * Footer — `footer` section from §6.16.
+ *
+ * Five-column link grid (Product · Resources · Company · Legal ·
+ * Status & GitHub) plus a bottom row with the copyright, the social
+ * icons (GitHub, Discord, X) and the static VERSION (`7.3.1` today —
+ * sourced from /VERSION at build time once the metadata pass lands).
+ *
+ * No fancy motion. The page closes on the FinalCta band — the footer
+ * is informational chrome.
+ */
+
+import type { ReactElement, SVGProps } from 'react';
+import Link from 'next/link';
+import { GithubMark } from './icons';
+
+interface LinkSpec {
+ label: string;
+ href: string;
+}
+
+interface LinkColumn {
+ heading: string;
+ links: ReadonlyArray<LinkSpec>;
+}
+
+const COLUMNS: ReadonlyArray<LinkColumn> = [
+ {
+ heading: 'Product',
+ links: [
+ { label: 'Detect', href: '/product/detect' },
+ { label: 'Triage', href: '/product/triage' },
+ { label: 'Hunt', href: '/product/hunt' },
+ { label: 'Respond', href: '/product/respond' },
+ { label: 'Connectors', href: '/connectors' },
+ { label: 'Marketplace', href: '/marketplace' },
+ ],
+ },
+ {
+ heading: 'Resources',
+ links: [
+ { label: 'Docs', href: 'https://docs.tryaisoc.com' },
+ { label: 'Architecture', href: 'https://docs.tryaisoc.com/architecture' },
+ { label: 'Benchmark', href: '/benchmark' },
+ { label: 'Blog', href: '/blog' },
+ { label: 'Changelog', href: '/changelog' },
+ { label: 'Roadmap', href: '/roadmap' },
+ ],
+ },
+ {
+ heading: 'Company',
+ links: [
+ { label: 'About', href: '/about' },
+ { label: 'Sovereign', href: '/sovereign' },
+ { label: 'Customers', href: '/customers' },
+ { label: 'Contact', href: '/contact' },
+ { label: 'Press', href: '/press' },
+ ],
+ },
+ {
+ heading: 'Legal',
+ links: [
+ {
+ label: 'License (MIT)',
+ href: 'https://github.com/beenuar/AiSOC/blob/main/LICENSE',
+ },
+ { label: 'Privacy', href: '/privacy' },
+ { label: 'Terms', href: '/terms' },
+ { label: 'Security', href: '/security' },
+ ],
+ },
+ {
+ heading: 'Status & GitHub',
+ links: [
+ { label: 'Status page', href: 'https://status.tryaisoc.com' },
+ { label: 'GitHub repo', href: 'https://github.com/beenuar/AiSOC' },
+ { label: 'Discord', href: 'https://discord.gg/aisoc' },
+ { label: 'RSS', href: '/rss.xml' },
+ ],
+ },
+];
+
+const VERSION = '7.3.1';
+
+function isExternal(href: string) {
+ return /^https?:\/\//.test(href);
+}
+
+function FooterLink({ label, href }: LinkSpec) {
+ const external = isExternal(href);
+ return (
+ <li>
+ <Link
+ href={href}
+ rel={external ? 'noreferrer' : undefined}
+ target={external ? '_blank' : undefined}
+ className="text-sm text-fg-muted transition-colors duration-200 hover:text-fg-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ {label}
+ </Link>
+ </li>
+ );
+}
+
+function DiscordIcon(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" {...props}>
+ <path d="M20.317 4.37a19.79 19.79 0 0 0-4.885-1.515.07.07 0 0 0-.07.035c-.21.378-.443.872-.608 1.26a18.27 18.27 0 0 0-5.487 0 12.51 12.51 0 0 0-.617-1.26.07.07 0 0 0-.07-.035 19.74 19.74 0 0 0-4.885 1.515.064.064 0 0 0-.03.027C.533 9.046-.32 13.58.099 18.057a.084.084 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.07.07 0 0 0 .076-.026 14.21 14.21 0 0 0 1.226-1.994.07.07 0 0 0-.038-.098 13.13 13.13 0 0 1-1.872-.892.07.07 0 0 1-.007-.116c.126-.094.252-.192.371-.291a.07.07 0 0 1 .073-.01c3.927 1.793 8.18 1.793 12.062 0a.07.07 0 0 1 .074.009c.12.099.246.198.372.292a.07.07 0 0 1-.006.116 12.32 12.32 0 0 1-1.873.891.07.07 0 0 0-.038.099c.36.698.772 1.362 1.225 1.993a.07.07 0 0 0 .076.027 19.84 19.84 0 0 0 6-3.03.07.07 0 0 0 .032-.056c.5-5.177-.838-9.674-3.548-13.66a.061.061 0 0 0-.03-.027ZM8.02 15.331c-1.182 0-2.157-1.085-2.157-2.419 0-1.333.956-2.418 2.157-2.418 1.21 0 2.176 1.094 2.157 2.418 0 1.334-.956 2.419-2.157 2.419Zm7.974 0c-1.182 0-2.156-1.085-2.156-2.419 0-1.333.955-2.418 2.156-2.418 1.21 0 2.176 1.094 2.157 2.418 0 1.334-.946 2.419-2.157 2.419Z" />
+ </svg>
+ );
+}
+
+function XIcon(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" {...props}>
+ <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231ZM17.083 19.77h1.833L7.084 4.126H5.117L17.083 19.77Z" />
+ </svg>
+ );
+}
+
+const SOCIAL_LINKS: ReadonlyArray<{
+ label: string;
+ href: string;
+ Icon: (props: SVGProps<SVGSVGElement>) => ReactElement;
+}> = [
+ { label: 'GitHub', href: 'https://github.com/beenuar/AiSOC', Icon: GithubMark },
+ { label: 'Discord', href: 'https://discord.gg/aisoc', Icon: DiscordIcon },
+ { label: 'X (Twitter)', href: 'https://twitter.com/tryaisoc', Icon: XIcon },
+];
+
+export function Footer() {
+ return (
+ <footer className="relative border-t border-surface-border bg-surface-base/80 backdrop-blur-sm">
+ <div className="mx-auto max-w-7xl px-4 py-12 sm:px-6 sm:py-14 lg:px-8 lg:py-16">
+ <div className="grid gap-10 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 lg:gap-8">
+ {COLUMNS.map((column) => (
+ <nav key={column.heading} aria-label={column.heading}>
+ <h3 className="text-xs font-semibold uppercase tracking-[0.12em] text-fg-primary">
+ {column.heading}
+ </h3>
+ <ul className="mt-4 space-y-3">
+ {column.links.map((link) => (
+ <FooterLink key={link.label} {...link} />
+ ))}
+ </ul>
+ </nav>
+ ))}
+ </div>
+
+ <div className="mt-12 flex flex-col items-start justify-between gap-4 border-t border-surface-border pt-8 sm:flex-row sm:items-center">
+ <p className="text-xs text-fg-muted">
+ © 2024–present AiSOC contributors · MIT-licensed · v{VERSION}
+ </p>
+ <ul className="flex items-center gap-3">
+ {SOCIAL_LINKS.map(({ label, href, Icon }) => (
+ <li key={label}>
+ <Link
+ href={href}
+ rel="noreferrer"
+ target="_blank"
+ aria-label={`AiSOC on ${label}`}
+ className="inline-flex h-9 w-9 items-center justify-center rounded-md border border-surface-border text-fg-muted transition-colors duration-200 hover:border-brand-500/40 hover:text-fg-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ <Icon className="h-4 w-4" />
+ </Link>
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ </footer>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/Hero.tsx b/apps/web/src/components/landing/sections/Hero.tsx
new file mode 100644
index 000000000..814cab2ee
--- /dev/null
+++ b/apps/web/src/components/landing/sections/Hero.tsx
@@ -0,0 +1,172 @@
+'use client';
+
+/**
+ * Hero section for the T6.5 landing page.
+ *
+ * Composes the vendored Aceternity / MagicUI primitives in a single,
+ * GPU-cheap stack:
+ *
+ * AnimatedGridPattern (random-fade grid)
+ * ↓ overlaid by
+ * Spotlight (static SVG glow, corner-anchored)
+ * ↓ overlaid by
+ * TextGenerateEffect (per-word reveal on H1)
+ * +
+ * AuroraText (the "auditable" accent)
+ *
+ * The H1 reveal totals ~750 ms (24 ms × 4 words × stagger + 0.55 s fade)
+ * which is inside the §7 brief's 800 ms ceiling. The grid is purely SVG;
+ * the Spotlight is one filter element with no JS. The background does
+ * not paint to the canvas — Lighthouse LCP stays on the H1 string itself.
+ *
+ * Every animated path is suppressed under `prefers-reduced-motion` (the
+ * primitives' own hooks handle that; this file only renders, never
+ * conditions on the reduced-motion bit).
+ */
+
+import Link from 'next/link';
+import { ArrowRight, Play } from 'lucide-react';
+import { GithubMark } from './icons';
+import { Spotlight } from '@/components/aceternity/Spotlight';
+import { TextGenerateEffect } from '@/components/aceternity/TextGenerateEffect';
+import { AnimatedGridPattern } from '@/components/magicui/AnimatedGridPattern';
+import { AuroraText } from '@/components/magicui/AuroraText';
+import { cn } from '@/lib/utils';
+
+const PROOF_CHIPS: ReadonlyArray<string> = [
+ '69 connectors · EDR · SIEM · cloud · IAM · SaaS · VCS · network',
+ '6,998 detections · 62 playbook packs · 57 plugins',
+ 'Self-host · Render · Fly.io · Helm · Terraform · air-gap',
+];
+
+export function Hero() {
+ return (
+ <section
+ id="hero"
+ aria-labelledby="hero-heading"
+ className="relative isolate overflow-hidden pt-28 sm:pt-32 lg:pt-36"
+ >
+ <div
+ aria-hidden="true"
+ className="absolute inset-0 -z-10 bg-landing-grad-hero opacity-90"
+ />
+ <AnimatedGridPattern
+ className="-z-10 [mask-image:radial-gradient(ellipse_at_top,white,transparent_70%)]"
+ numSquares={42}
+ maxOpacity={0.07}
+ duration={3.6}
+ repeatDelay={1.2}
+ />
+ <Spotlight
+ className="-top-40 left-0 md:-top-20 md:left-60"
+ fill="rgba(59,130,246,0.45)"
+ />
+
+ <div className="mx-auto max-w-7xl px-4 pb-20 sm:px-6 lg:px-8 lg:pb-28">
+ <div className="mx-auto max-w-3xl text-center">
+ <p
+ className={cn(
+ 'inline-flex items-center gap-2 rounded-full border border-surface-border bg-surface-raised/60 px-3 py-1 text-xs font-medium text-fg-muted backdrop-blur-sm',
+ 'animate-fade-in-up',
+ )}
+ style={{ animationDelay: '60ms' }}
+ >
+ <span
+ aria-hidden="true"
+ className="inline-block h-1.5 w-1.5 rounded-full bg-brand-400 shadow-[0_0_0_2px_rgba(59,130,246,0.25)]"
+ />
+ Open-source <span aria-hidden="true">·</span> MIT
+ <span aria-hidden="true">·</span> self-hostable
+ </p>
+
+ <h1
+ id="hero-heading"
+ className="mt-6 font-sans text-4xl font-bold leading-[1.1] tracking-tight text-fg-primary sm:text-5xl lg:text-[64px] lg:leading-[1.05] lg:tracking-[-0.02em]"
+ >
+ <TextGenerateEffect
+ words="Detect. Triage."
+ staggerDelay={0.06}
+ duration={0.55}
+ className="block"
+ />
+ <span className="mt-1 block sm:mt-2">
+ <AuroraText>Hunt.</AuroraText>{' '}
+ <TextGenerateEffect
+ words="Respond."
+ staggerDelay={0.06}
+ duration={0.55}
+ className="inline"
+ />
+ </span>
+ </h1>
+
+ <p
+ className="mx-auto mt-6 max-w-2xl text-base leading-relaxed text-fg-secondary sm:text-lg sm:leading-[1.6] motion-safe:animate-fade-in-up"
+ style={{ animationDelay: '420ms' }}
+ >
+ AiSOC is the open agentic Security Operations Center. Four named
+ agents investigate every incident end-to-end, and every prompt,
+ tool call, and rationale lands in a replayable ledger.
+ Self-host in five minutes, take it air-gapped on a flag, or join
+ the managed waitlist.
+ </p>
+
+ <div
+ className="mt-8 flex flex-col items-center justify-center gap-3 motion-safe:animate-fade-in-up sm:flex-row sm:gap-4"
+ style={{ animationDelay: '540ms' }}
+ >
+ <Link
+ href="https://app.aisoc.dev/signup"
+ className="group inline-flex h-11 w-full items-center justify-center gap-2 rounded-md bg-gradient-to-br from-brand-500 to-brand-700 px-6 text-sm font-semibold text-white shadow-[0_1px_0_rgba(255,255,255,0.18)_inset,0_8px_24px_-12px_rgba(59,130,246,0.55)] transition-[box-shadow,transform] duration-200 ease-landing-out-quart hover:shadow-[0_12px_32px_-12px_rgba(59,130,246,0.75)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base sm:w-auto"
+ >
+ Start free on managed
+ <ArrowRight
+ className="h-4 w-4 transition-transform duration-200 ease-landing-out-quart group-hover:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ <a
+ href="https://github.com/beenuar/AiSOC"
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex h-11 w-full items-center justify-center gap-2 rounded-md border border-surface-border bg-surface-raised/60 px-6 text-sm font-semibold text-fg-primary backdrop-blur-sm transition-colors duration-200 ease-landing-out-quart hover:border-brand-500/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base sm:w-auto"
+ >
+ <GithubMark className="h-4 w-4" />
+ Self-host on GitHub
+ </a>
+ </div>
+
+ <Link
+ href="#demo"
+ className="group mt-5 inline-flex items-center gap-2 text-sm font-medium text-fg-muted transition-colors duration-200 ease-landing-out-quart hover:text-fg-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base motion-safe:animate-fade-in-up"
+ style={{ animationDelay: '660ms' }}
+ >
+ <Play
+ className="h-3.5 w-3.5 fill-current opacity-70 transition-opacity duration-200 group-hover:opacity-100"
+ aria-hidden="true"
+ />
+ Watch a 90-second investigation
+ <ArrowRight
+ className="h-3 w-3 transition-transform duration-200 ease-landing-out-quart group-hover:translate-x-0.5"
+ aria-hidden="true"
+ />
+ </Link>
+ </div>
+
+ <ul
+ className="mx-auto mt-14 flex max-w-5xl flex-wrap items-center justify-center gap-x-3 gap-y-2 motion-safe:animate-fade-in-up sm:mt-16"
+ style={{ animationDelay: '780ms' }}
+ >
+ {PROOF_CHIPS.map((chip) => (
+ <li
+ key={chip}
+ className="inline-flex items-center rounded-full border border-surface-border bg-surface-raised/40 px-3 py-1.5 text-xs font-medium text-fg-muted shadow-[0_0_0_1px_rgba(148,163,184,0.04)_inset] backdrop-blur-sm"
+ >
+ {chip}
+ </li>
+ ))}
+ </ul>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/OpenSourceMoment.tsx b/apps/web/src/components/landing/sections/OpenSourceMoment.tsx
new file mode 100644
index 000000000..298e00cdf
--- /dev/null
+++ b/apps/web/src/components/landing/sections/OpenSourceMoment.tsx
@@ -0,0 +1,151 @@
+'use client';
+
+/**
+ * "MIT all the way down" — `open-source` section from §6.11 of the brief.
+ *
+ * Single-column band split into two halves on `≥md`:
+ *
+ * - Left: eyebrow + H2 + sub-head + primary/secondary CTAs.
+ * - Right: a "repo card" rendered as a stylised README header with a
+ * `BorderBeam` and a `bash` snippet underneath. Three commands —
+ * the same `git clone … pnpm aisoc:demo` shorthand the
+ * `landing-page-content.md` doc specifies.
+ *
+ * No live GitHub API call for the star count; it is intentionally
+ * static here. A follow-up workflow will fill in the real value from
+ * `github.repos.get`.
+ */
+
+import Link from 'next/link';
+import { motion, useReducedMotion } from 'framer-motion';
+import { ArrowRight, GitBranch, Star, Terminal } from 'lucide-react';
+import { BorderBeam } from '@/components/magicui/BorderBeam';
+import { GithubMark } from './icons';
+
+const REPO_URL = 'https://github.com/beenuar/AiSOC';
+const CONTRIBUTING_URL = 'https://github.com/beenuar/AiSOC/blob/main/CONTRIBUTING.md';
+const SNIPPET = `git clone https://github.com/beenuar/AiSOC.git
+cd AiSOC
+pnpm aisoc:demo`;
+
+export function OpenSourceMoment() {
+ const prefersReducedMotion = useReducedMotion();
+ const fadeIn = (delay = 0) =>
+ prefersReducedMotion
+ ? false
+ : ({
+ initial: { opacity: 0, y: 16 },
+ whileInView: { opacity: 1, y: 0 },
+ viewport: { once: true, margin: '-15%' as const },
+ transition: { duration: 0.55, ease: [0.16, 1, 0.3, 1], delay },
+ } as const);
+
+ return (
+ <section
+ id="open-source"
+ aria-labelledby="open-source-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <div className="grid items-center gap-12 lg:grid-cols-[1.05fr_1fr] lg:gap-16">
+ <motion.div {...(fadeIn(0) || {})}>
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ MIT all the way down
+ </p>
+ <h2
+ id="open-source-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ Every detection rule public. Every benchmark reproducible.
+ </h2>
+ <p className="mt-4 max-w-xl text-base leading-relaxed text-fg-secondary">
+ Fork the agent, fork the rules, fork the harness. We measure
+ ourselves on the same metrics we publish, and we ship the
+ dataset that produced them. There is no private fork.
+ </p>
+ <div className="mt-6 flex flex-wrap items-center gap-3">
+ <Link
+ href={REPO_URL}
+ rel="noreferrer"
+ target="_blank"
+ className="group inline-flex h-10 items-center gap-2 rounded-md bg-gradient-to-br from-brand-500 to-brand-700 px-4 text-sm font-semibold text-white shadow-[0_1px_0_rgba(255,255,255,0.18)_inset] transition-shadow duration-200 ease-landing-out-quart hover:shadow-[0_12px_32px_-12px_rgba(59,130,246,0.65)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ <Star className="h-4 w-4" aria-hidden="true" />
+ Star on GitHub
+ <ArrowRight
+ className="h-3.5 w-3.5 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ <Link
+ href={CONTRIBUTING_URL}
+ rel="noreferrer"
+ target="_blank"
+ className="inline-flex h-10 items-center gap-2 rounded-md border border-surface-border bg-surface-raised/60 px-4 text-sm font-semibold text-fg-primary transition-colors duration-200 hover:border-brand-500/40 hover:text-brand-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ <GitBranch className="h-4 w-4" aria-hidden="true" />
+ Read CONTRIBUTING.md
+ </Link>
+ </div>
+ </motion.div>
+
+ <motion.div {...(fadeIn(0.12) || {})} className="relative">
+ <div className="relative overflow-hidden rounded-2xl border border-surface-border bg-surface-card/80 backdrop-blur-sm">
+ <BorderBeam size={160} duration={14} colorFrom="#3b82f6" colorTo="#8b5cf6" />
+ <div className="flex items-center gap-2 border-b border-surface-border bg-surface-raised/70 px-4 py-3 text-xs text-fg-muted">
+ <span className="flex gap-1.5" aria-hidden="true">
+ <span className="h-2.5 w-2.5 rounded-full bg-red-500/70" />
+ <span className="h-2.5 w-2.5 rounded-full bg-amber-400/70" />
+ <span className="h-2.5 w-2.5 rounded-full bg-emerald-500/70" />
+ </span>
+ <span className="ml-2 font-mono">github.com/beenuar/AiSOC</span>
+ </div>
+ <div className="space-y-4 p-6">
+ <div className="flex items-start gap-3">
+ <span
+ aria-hidden="true"
+ className="inline-flex h-10 w-10 items-center justify-center rounded-lg bg-fg-primary/10 text-fg-primary"
+ >
+ <GithubMark className="h-5 w-5" />
+ </span>
+ <div>
+ <p className="text-sm font-semibold text-fg-primary">
+ beenuar / AiSOC
+ </p>
+ <p className="text-xs text-fg-muted">
+ <span aria-label="GitHub stars">★ 2.3k</span> · MIT · TypeScript / Python / Go
+ </p>
+ </div>
+ </div>
+ <p className="text-sm leading-relaxed text-fg-secondary">
+ Clone, demo, and inspect a live case in three commands:
+ </p>
+ <pre className="overflow-x-auto rounded-lg border border-surface-border bg-surface-raised/60 p-4 text-xs leading-relaxed text-fg-secondary">
+ <code className="block whitespace-pre font-mono">
+ <span className="select-none text-fg-muted">$ </span>
+ <span className="text-brand-300">git clone</span>{' '}
+ <span className="text-fg-primary">https://github.com/beenuar/AiSOC.git</span>
+ {'\n'}
+ <span className="select-none text-fg-muted">$ </span>
+ <span className="text-brand-300">cd</span>{' '}
+ <span className="text-fg-primary">AiSOC</span>
+ {'\n'}
+ <span className="select-none text-fg-muted">$ </span>
+ <span className="text-brand-300">pnpm</span>{' '}
+ <span className="text-fg-primary">aisoc:demo</span>
+ </code>
+ </pre>
+ <div className="flex items-center gap-2 text-xs text-fg-muted">
+ <Terminal className="h-3.5 w-3.5" aria-hidden="true" />
+ <span>Boots a pre-seeded case in under a minute.</span>
+ </div>
+ {/* Hidden plaintext copy for screen readers / clipboard tools */}
+ <span className="sr-only">{SNIPPET}</span>
+ </div>
+ </div>
+ </motion.div>
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/Pillars.tsx b/apps/web/src/components/landing/sections/Pillars.tsx
new file mode 100644
index 000000000..f9477c127
--- /dev/null
+++ b/apps/web/src/components/landing/sections/Pillars.tsx
@@ -0,0 +1,189 @@
+'use client';
+
+/**
+ * "What makes AiSOC different" — `pillars` section from §6.6 of the
+ * brief. Four differentiation cards in a 2×2 grid above `md`, single
+ * column below.
+ *
+ * Each card composes two Aceternity primitives:
+ * - `GlowingEffect` paints a soft conic halo that tracks the pointer
+ * when the card is hovered or focused.
+ * - `CardHoverEffect` swaps to a brand-tinted overlay on the same
+ * pointer event so the card reads as "active" without redrawing
+ * its body.
+ *
+ * Each card carries a stat strip (e.g. "6,998 public detection rules")
+ * with `tnum`-enabled mono digits and a single CTA link that opens the
+ * corresponding repo file.
+ */
+
+import Link from 'next/link';
+import { motion, useReducedMotion } from 'framer-motion';
+import { ArrowRight, GitGraph, ScrollText, Sparkles, Boxes } from 'lucide-react';
+import type { ComponentType, SVGProps } from 'react';
+import { GlowingEffect } from '@/components/aceternity/GlowingEffect';
+import { cn } from '@/lib/utils';
+
+interface Pillar {
+ id: 'open-source' | 'graph-native' | 'agentic' | 'deploy';
+ icon: ComponentType<SVGProps<SVGSVGElement>>;
+ title: string;
+ body: string;
+ stat: string;
+ statLabel: string;
+ href: string;
+ linkLabel: string;
+}
+
+const PILLARS: ReadonlyArray<Pillar> = [
+ {
+ id: 'open-source',
+ icon: ScrollText,
+ title: 'Open source and transparent',
+ body:
+ 'MIT-licensed agent, public detection corpus, reproducible benchmark — every claim on this page maps to a file in the repo.',
+ stat: '6,998',
+ statLabel: 'public detection rules',
+ href: 'https://github.com/beenuar/AiSOC/blob/main/LICENSE',
+ linkLabel: 'Read the LICENSE',
+ },
+ {
+ id: 'graph-native',
+ icon: GitGraph,
+ title: 'Graph-native at ingest',
+ body:
+ 'The entity graph is written while events are normalised, not when an analyst clicks "show graph." Schema v1.0 is published.',
+ stat: '17 + 14',
+ statLabel: 'node labels · relationships',
+ href: 'https://docs.aisoc.dev/architecture/graph-schema',
+ linkLabel: 'Read the graph schema',
+ },
+ {
+ id: 'agentic',
+ icon: Sparkles,
+ title: 'Agentic and auditable',
+ body:
+ 'Four named agents. Every prompt, tool call, and decision is logged. The LLM-input contract fails closed on malformed prompts.',
+ stat: '4 / 100%',
+ statLabel: 'agents · audited',
+ href: 'https://docs.aisoc.dev/architecture/agents',
+ linkLabel: 'Read the agent contract',
+ },
+ {
+ id: 'deploy',
+ icon: Boxes,
+ title: 'Deploy anywhere',
+ body:
+ 'Render, Fly.io, Kubernetes, AWS, your air-gapped rack — same code path. BYOK LLM credentials in the encrypted vault.',
+ stat: '6 + 1',
+ statLabel: 'deploy targets · air-gap overlay',
+ href: 'https://docs.aisoc.dev/deployment',
+ linkLabel: 'Read the deployment guide',
+ },
+];
+
+function PillarCard({
+ pillar,
+ index,
+ reduced,
+}: {
+ pillar: Pillar;
+ index: number;
+ reduced: boolean | null;
+}) {
+ const Icon = pillar.icon;
+ return (
+ <motion.li
+ initial={reduced ? false : { opacity: 0, y: 16 }}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{
+ duration: 0.55,
+ ease: [0.16, 1, 0.3, 1],
+ delay: index * 0.07,
+ }}
+ className="group relative"
+ >
+ <div className="relative h-full overflow-hidden rounded-2xl border border-surface-border bg-surface-card/70 p-6 backdrop-blur-sm transition-shadow duration-300 ease-landing-out-quart hover:shadow-[0_24px_64px_-32px_rgba(59,130,246,0.4)]">
+ <GlowingEffect proximity={120} inactiveZone={0.35} />
+ <div className="relative flex items-start gap-4">
+ <span
+ aria-hidden="true"
+ className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500/20 to-landing-accent-violet/20 text-brand-300 ring-1 ring-inset ring-brand-500/30"
+ >
+ <Icon className="h-5 w-5" />
+ </span>
+ <div className="min-w-0">
+ <h3 className="text-base font-semibold tracking-tight text-fg-primary sm:text-lg">
+ {pillar.title}
+ </h3>
+ <p className="mt-2 text-sm leading-relaxed text-fg-secondary">
+ {pillar.body}
+ </p>
+ </div>
+ </div>
+ <hr className="my-5 border-surface-border" />
+ <div className="relative flex flex-wrap items-end justify-between gap-3">
+ <div>
+ <p
+ className={cn(
+ 'font-mono text-2xl font-semibold tracking-tight text-fg-primary tabular-nums',
+ 'sm:text-3xl',
+ )}
+ >
+ {pillar.stat}
+ </p>
+ <p className="text-xs text-fg-muted">{pillar.statLabel}</p>
+ </div>
+ <Link
+ href={pillar.href}
+ className="group/link inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-semibold text-brand-300 transition-colors duration-200 hover:text-brand-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ {pillar.linkLabel}
+ <ArrowRight
+ className="h-3 w-3 transition-transform duration-200 group-hover/link:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover/link:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ </div>
+ </div>
+ </motion.li>
+ );
+}
+
+export function Pillars() {
+ const prefersReducedMotion = useReducedMotion();
+
+ return (
+ <section
+ id="pillars"
+ aria-labelledby="pillars-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <div className="mx-auto max-w-3xl text-center">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ What makes AiSOC different
+ </p>
+ <h2
+ id="pillars-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ Four promises we hold ourselves to.
+ </h2>
+ </div>
+
+ <ul className="mt-12 grid gap-4 sm:gap-6 md:grid-cols-2 lg:mt-16">
+ {PILLARS.map((pillar, idx) => (
+ <PillarCard
+ key={pillar.id}
+ pillar={pillar}
+ index={idx}
+ reduced={prefersReducedMotion}
+ />
+ ))}
+ </ul>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/PricingTeaser.tsx b/apps/web/src/components/landing/sections/PricingTeaser.tsx
new file mode 100644
index 000000000..1ee6aa0a0
--- /dev/null
+++ b/apps/web/src/components/landing/sections/PricingTeaser.tsx
@@ -0,0 +1,195 @@
+'use client';
+
+/**
+ * "Free to self-host. Pay only when we host." — `pricing-teaser`
+ * section from §6.13 of the brief.
+ *
+ * Three-column tier teaser (mobile: stacked). "Team" is the middle
+ * card and carries the recommended treatment — `ShineBorder` plus the
+ * brighter "Contact us — waitlist" CTA. The page links out to the full
+ * pricing page for the bottom of the funnel; this section is the
+ * scan-and-skim teaser.
+ */
+
+import Link from 'next/link';
+import { motion, useReducedMotion } from 'framer-motion';
+import { ArrowRight, Check } from 'lucide-react';
+import { ShineBorder } from '@/components/magicui/ShineBorder';
+import { cn } from '@/lib/utils';
+
+interface Tier {
+ id: 'community' | 'team' | 'enterprise';
+ name: string;
+ price: string;
+ tagline: string;
+ includes: ReadonlyArray<string>;
+ cta: { label: string; href: string };
+ recommended?: boolean;
+}
+
+const TIERS: ReadonlyArray<Tier> = [
+ {
+ id: 'community',
+ name: 'Community',
+ price: 'Free',
+ tagline: 'Self-host the full stack.',
+ includes: [
+ 'MIT-licensed code',
+ 'All 69 connectors',
+ 'Marketplace',
+ 'Public benchmark harness',
+ 'Community Discord',
+ ],
+ cta: { label: 'Clone on GitHub', href: 'https://github.com/beenuar/AiSOC' },
+ },
+ {
+ id: 'team',
+ name: 'Team',
+ price: 'Waitlist',
+ tagline: 'We run it. You log in.',
+ includes: [
+ 'Everything in Community',
+ 'Managed instance on app.aisoc.dev',
+ 'BYOK LLM',
+ 'Email support',
+ 'SOC 2 (in progress)',
+ ],
+ cta: { label: 'Join the waitlist', href: '/waitlist' },
+ recommended: true,
+ },
+ {
+ id: 'enterprise',
+ name: 'Enterprise',
+ price: 'Contact us',
+ tagline: 'Sovereign, air-gap, or single-tenant in your VPC.',
+ includes: [
+ 'Everything in Team',
+ 'Sovereign / air-gap deploy',
+ 'Named onboarding',
+ 'Architecture review',
+ '24×7 incident channel',
+ ],
+ cta: { label: 'Talk to us', href: '/contact' },
+ },
+];
+
+function TierCard({
+ tier,
+ index,
+ reduced,
+}: {
+ tier: Tier;
+ index: number;
+ reduced: boolean | null;
+}) {
+ return (
+ <motion.li
+ initial={reduced ? false : { opacity: 0, y: 16 }}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{
+ duration: 0.55,
+ ease: [0.16, 1, 0.3, 1],
+ delay: index * 0.08,
+ }}
+ className={cn(
+ 'relative flex flex-col gap-6 rounded-2xl border border-surface-border bg-surface-card/70 p-6 backdrop-blur-sm sm:p-8',
+ tier.recommended &&
+ 'shadow-[0_24px_64px_-24px_rgba(59,130,246,0.45)]',
+ )}
+ >
+ {tier.recommended && <ShineBorder duration={14} borderWidth={1} />}
+ <div className="relative">
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-lg font-semibold text-fg-primary">{tier.name}</h3>
+ {tier.recommended && (
+ <span className="inline-flex items-center rounded-full bg-brand-500/15 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-brand-300 ring-1 ring-inset ring-brand-500/40">
+ Most asked for
+ </span>
+ )}
+ </div>
+ <p className="mt-3 text-3xl font-bold tracking-tight text-fg-primary">
+ {tier.price}
+ </p>
+ <p className="mt-2 text-sm leading-relaxed text-fg-secondary">
+ {tier.tagline}
+ </p>
+ </div>
+ <ul className="relative space-y-2 text-sm text-fg-secondary">
+ {tier.includes.map((line) => (
+ <li key={line} className="flex items-start gap-2">
+ <Check
+ className="mt-0.5 h-4 w-4 flex-none text-brand-300"
+ aria-hidden="true"
+ />
+ <span>{line}</span>
+ </li>
+ ))}
+ </ul>
+ <Link
+ href={tier.cta.href}
+ rel={tier.cta.href.startsWith('http') ? 'noreferrer' : undefined}
+ target={tier.cta.href.startsWith('http') ? '_blank' : undefined}
+ className={cn(
+ 'group relative mt-auto inline-flex h-10 items-center justify-center gap-1 rounded-md px-4 text-sm font-semibold transition-shadow duration-200 ease-landing-out-quart focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base',
+ tier.recommended
+ ? 'bg-gradient-to-br from-brand-500 to-brand-700 text-white shadow-[0_1px_0_rgba(255,255,255,0.18)_inset] hover:shadow-[0_12px_32px_-12px_rgba(59,130,246,0.65)]'
+ : 'border border-surface-border bg-surface-raised/60 text-fg-primary hover:border-brand-500/40',
+ )}
+ >
+ {tier.cta.label}
+ <ArrowRight
+ className="h-3.5 w-3.5 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ </motion.li>
+ );
+}
+
+export function PricingTeaser() {
+ const prefersReducedMotion = useReducedMotion();
+
+ return (
+ <section
+ id="pricing"
+ aria-labelledby="pricing-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <div className="mx-auto max-w-3xl text-center">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ Pricing
+ </p>
+ <h2
+ id="pricing-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ Free to self-host. Pay only when we host.
+ </h2>
+ </div>
+
+ <ul className="mt-12 grid gap-4 sm:gap-6 md:grid-cols-3 lg:mt-16 lg:gap-8">
+ {TIERS.map((tier, idx) => (
+ <TierCard
+ key={tier.id}
+ tier={tier}
+ index={idx}
+ reduced={prefersReducedMotion}
+ />
+ ))}
+ </ul>
+
+ <p className="mt-10 text-center text-sm text-fg-muted">
+ <Link
+ href="/pricing"
+ className="inline-flex items-center gap-1 text-brand-300 transition-colors duration-200 hover:text-brand-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ See full pricing
+ <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
+ </Link>
+ </p>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/Problem.tsx b/apps/web/src/components/landing/sections/Problem.tsx
new file mode 100644
index 000000000..74d70a7fb
--- /dev/null
+++ b/apps/web/src/components/landing/sections/Problem.tsx
@@ -0,0 +1,110 @@
+'use client';
+
+/**
+ * "Why we built this" — `problem` section from §6.3 of the brief.
+ *
+ * Renders three pain bullets in a three-up grid (single column below
+ * `md`). Each card reveals once when it enters the viewport, staggered
+ * 80 ms apart per §7 of the brief. The icon is a Lucide glyph that
+ * matches the pain point, sitting inside a 40×40 brand-tinted tile.
+ *
+ * Copy is lifted verbatim from `docs/design/landing-page-content.md`
+ * (headlines + bodies).
+ */
+
+import { motion, useReducedMotion } from 'framer-motion';
+import { AlertTriangle, Layers, ScrollText } from 'lucide-react';
+import type { ComponentType, SVGProps } from 'react';
+
+interface Pain {
+ icon: ComponentType<SVGProps<SVGSVGElement>>;
+ headline: string;
+ body: string;
+}
+
+const PAINS: ReadonlyArray<Pain> = [
+ {
+ icon: AlertTriangle,
+ headline: 'Alert volume is up. Headcount is not.',
+ body:
+ 'A typical mid-market SOC sees more alerts in a single shift than an analyst can read end-to-end, and the AI tools that promise to triage them ship as black boxes you cannot audit.',
+ },
+ {
+ icon: Layers,
+ headline: 'Context lives in eight tabs.',
+ body:
+ 'SIEM, EDR, cloud console, ticketing, chat, identity provider, on-call, runbook. Every alert is the same context-switch tax.',
+ },
+ {
+ icon: ScrollText,
+ headline: 'You cannot defend a verdict you cannot read.',
+ body:
+ 'When an autonomous tool closes an alert, your analyst, your manager, and your auditor all need to know exactly why. Most vendors do not show the rationale.',
+ },
+];
+
+export function Problem() {
+ const prefersReducedMotion = useReducedMotion();
+
+ const initial = prefersReducedMotion ? false : { opacity: 0, y: 20 };
+ const inView = { opacity: 1, y: 0 };
+
+ return (
+ <section
+ id="problem"
+ aria-labelledby="problem-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <div className="mx-auto max-w-2xl text-center">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ Why we built this
+ </p>
+ <h2
+ id="problem-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ Your SOC is drowning in alerts.
+ </h2>
+ <p className="mt-4 text-base leading-relaxed text-fg-secondary sm:text-lg">
+ Three problems compound every shift. AiSOC was built to dissolve
+ them, not paper over them.
+ </p>
+ </div>
+
+ <ul className="mt-12 grid gap-4 sm:gap-6 md:grid-cols-3 lg:mt-16">
+ {PAINS.map((pain, index) => {
+ const Icon = pain.icon;
+ return (
+ <motion.li
+ key={pain.headline}
+ initial={initial}
+ whileInView={inView}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{
+ duration: 0.55,
+ ease: [0.16, 1, 0.3, 1],
+ delay: index * 0.08,
+ }}
+ className="flex flex-col gap-4 rounded-2xl border border-surface-border bg-surface-card/60 p-6 backdrop-blur-sm transition-shadow duration-300 ease-landing-out-quart hover:shadow-[0_18px_48px_-24px_rgba(59,130,246,0.4)]"
+ >
+ <span
+ aria-hidden="true"
+ className="inline-flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500/20 to-brand-700/20 text-brand-300 ring-1 ring-inset ring-brand-500/30"
+ >
+ <Icon className="h-5 w-5" />
+ </span>
+ <h3 className="text-base font-semibold leading-snug text-fg-primary sm:text-lg">
+ {pain.headline}
+ </h3>
+ <p className="text-sm leading-relaxed text-fg-secondary">
+ {pain.body}
+ </p>
+ </motion.li>
+ );
+ })}
+ </ul>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/ProofStrip.tsx b/apps/web/src/components/landing/sections/ProofStrip.tsx
new file mode 100644
index 000000000..931255b09
--- /dev/null
+++ b/apps/web/src/components/landing/sections/ProofStrip.tsx
@@ -0,0 +1,123 @@
+'use client';
+
+/**
+ * Proof / logo strip — `proof-strip` from §6.2 of the brief.
+ *
+ * Renders two horizontal rows:
+ *
+ * 1. "Built on the open-source stack you already trust" — six line-art
+ * brand wordmarks (LangGraph, Apache Kafka, Neo4j, PostgreSQL,
+ * Qdrant, Ollama) inside a Marquee, paused on hover/focus.
+ *
+ * 2. "Design partners" — four greyed partner-outline pills that read
+ * "Reference partners onboarding through Q2 2026", matching the
+ * content doc's empty-state treatment until real customer logos
+ * are licensed.
+ *
+ * The Marquee primitive (`MagicUI`) already collapses to a static row
+ * under `prefers-reduced-motion` via the `animate-marquee` keyframe
+ * guard in `globals.css`, so this surface is fully accessible without
+ * any extra branching here.
+ */
+
+import { Marquee } from '@/components/magicui/Marquee';
+import { cn } from '@/lib/utils';
+
+const STACK_WORDMARKS: ReadonlyArray<{
+ name: string;
+ caption: string;
+}> = [
+ { name: 'LangGraph', caption: 'Agent runtime' },
+ { name: 'Apache Kafka', caption: 'Streaming' },
+ { name: 'Neo4j', caption: 'Entity graph' },
+ { name: 'PostgreSQL', caption: 'Source of truth' },
+ { name: 'Qdrant', caption: 'Vector store' },
+ { name: 'Ollama', caption: 'Local LLM' },
+];
+
+const PARTNER_PLACEHOLDERS = [
+ 'Partner A',
+ 'Partner B',
+ 'Partner C',
+ 'Partner D',
+] as const;
+
+function StackWordmark({ name, caption }: { name: string; caption: string }) {
+ return (
+ <div
+ className={cn(
+ 'flex items-center gap-3 rounded-md px-4 py-3 text-fg-muted',
+ 'border border-transparent hover:border-surface-border hover:text-fg-secondary',
+ 'transition-colors duration-200 ease-landing-out-quart',
+ )}
+ >
+ <span className="text-sm font-semibold tracking-[-0.005em] text-fg-secondary">
+ {name}
+ </span>
+ <span className="hidden text-xs font-medium text-fg-subtle sm:inline">
+ {caption}
+ </span>
+ </div>
+ );
+}
+
+export function ProofStrip() {
+ return (
+ <section
+ id="proof-strip"
+ aria-labelledby="proof-strip-heading"
+ className="relative border-y border-surface-border/60 bg-surface-base/60 py-12 sm:py-14"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <h2
+ id="proof-strip-heading"
+ className="text-center text-xs font-semibold uppercase tracking-[0.18em] text-fg-subtle"
+ >
+ Built on the open-source stack you already trust
+ </h2>
+
+ <div className="relative mt-6">
+ <div
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-y-0 left-0 z-10 w-16 bg-gradient-to-r from-surface-base to-transparent sm:w-24"
+ />
+ <div
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-y-0 right-0 z-10 w-16 bg-gradient-to-l from-surface-base to-transparent sm:w-24"
+ />
+ <Marquee className="[--gap:0.5rem] sm:[--gap:2rem]">
+ {STACK_WORDMARKS.map((stack) => (
+ <StackWordmark key={stack.name} {...stack} />
+ ))}
+ </Marquee>
+ </div>
+
+ <div className="mt-10 flex flex-col items-center gap-4">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-fg-subtle">
+ Design partners
+ </p>
+ <ul
+ aria-label="Reference partners onboarding through Q2 2026"
+ className="flex flex-wrap items-center justify-center gap-2 sm:gap-3"
+ >
+ {PARTNER_PLACEHOLDERS.map((partner) => (
+ <li
+ key={partner}
+ className="inline-flex items-center gap-2 rounded-full border border-dashed border-surface-border bg-surface-raised/30 px-4 py-1.5 text-xs font-medium text-fg-subtle"
+ >
+ <span
+ aria-hidden="true"
+ className="inline-block h-1.5 w-1.5 rounded-full bg-fg-subtle/40"
+ />
+ {partner}
+ </li>
+ ))}
+ </ul>
+ <p className="text-xs text-fg-subtle">
+ Reference partners onboarding through Q2 2026
+ </p>
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/SolutionAgents.tsx b/apps/web/src/components/landing/sections/SolutionAgents.tsx
new file mode 100644
index 000000000..d7a6c1bb1
--- /dev/null
+++ b/apps/web/src/components/landing/sections/SolutionAgents.tsx
@@ -0,0 +1,253 @@
+'use client';
+
+/**
+ * "Four agents, one workflow" — `solution` section from §6.4 of the
+ * brief. The most animation-heavy piece on the page; everything in it
+ * is built to flatten gracefully under `prefers-reduced-motion`.
+ *
+ * Layout (desktop ≥ 1024 px):
+ *
+ * ┌────────┐ ┌────────┐ ┌────────┐ ┌─────────┐
+ * │ Detect │ → │ Triage │ → │ Hunt │ → │ Respond │
+ * └────────┘ └────────┘ └────────┘ └─────────┘
+ *
+ * The arrows are three `AnimatedBeam` instances anchored on real DOM
+ * refs (the card edges) so the curve auto-recomputes on resize. Each
+ * beam fires a brand-tinted comet on a 3 s loop with a 700 ms phase
+ * shift so the four-agent narrative reads as a *pipeline*, not four
+ * independent boxes.
+ *
+ * Mobile (< 1024 px): cards stack vertically and the beams are
+ * suppressed (the comet only renders when the layout is horizontal —
+ * the curvature math doesn't translate cleanly to a column layout).
+ */
+
+import { motion, useReducedMotion } from 'framer-motion';
+import { ScanSearch, Sparkles, Telescope, ShieldCheck } from 'lucide-react';
+import {
+ type ComponentType,
+ type SVGProps,
+ useRef,
+ useState,
+ useEffect,
+} from 'react';
+import { AnimatedBeam } from '@/components/magicui/AnimatedBeam';
+import { cn } from '@/lib/utils';
+
+interface Agent {
+ id: 'detect' | 'triage' | 'hunt' | 'respond';
+ label: string;
+ job: string;
+ capabilities: string;
+ runsOn: string;
+ icon: ComponentType<SVGProps<SVGSVGElement>>;
+ accent: string;
+}
+
+const AGENTS: ReadonlyArray<Agent> = [
+ {
+ id: 'detect',
+ label: 'Detect',
+ job: 'Fuse raw signals into incidents.',
+ capabilities: 'fusion · entity-risk (RBA) · native detections',
+ runsOn: 'Deterministic · no LLM required',
+ icon: ScanSearch,
+ accent: 'from-brand-400/20 to-brand-700/20 ring-brand-400/30 text-brand-200',
+ },
+ {
+ id: 'triage',
+ label: 'Triage',
+ job: 'Decide what matters and how urgent.',
+ capabilities:
+ 'LLM auto-triage · phishing · identity · cloud · insider',
+ runsOn: 'OpenAI · Anthropic · Azure · Bedrock · Ollama · BYO endpoint',
+ icon: Sparkles,
+ accent:
+ 'from-landing-accent-violet/20 to-brand-500/20 ring-landing-accent-violet/30 text-landing-accent-violet',
+ },
+ {
+ id: 'hunt',
+ label: 'Hunt',
+ job: 'Ask new questions across the data.',
+ capabilities: 'NL → ES|QL · KQL · SPL · scheduled YAML hunts',
+ runsOn: 'Cloud LLM or local model',
+ icon: Telescope,
+ accent:
+ 'from-brand-500/20 to-brand-300/20 ring-brand-300/30 text-brand-300',
+ },
+ {
+ id: 'respond',
+ label: 'Respond',
+ job: 'Plan containment, gate execution, approve via ChatOps.',
+ capabilities: 'response planner · SOAR exec · approvals',
+ runsOn: 'L0–L4 maturity dial, dry-run by default',
+ icon: ShieldCheck,
+ accent:
+ 'from-landing-accent-ember/20 to-brand-500/20 ring-landing-accent-ember/30 text-landing-accent-ember',
+ },
+];
+
+function AgentCard({
+ agent,
+ index,
+ innerRef,
+}: {
+ agent: Agent;
+ index: number;
+ innerRef: React.RefObject<HTMLDivElement | null>;
+}) {
+ const Icon = agent.icon;
+ return (
+ <motion.div
+ ref={innerRef}
+ initial={{ opacity: 0, y: 16 }}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{
+ duration: 0.5,
+ ease: [0.16, 1, 0.3, 1],
+ delay: index * 0.08,
+ }}
+ className={cn(
+ 'group relative flex h-full flex-col gap-3 rounded-2xl border border-surface-border bg-surface-card/70 p-5 backdrop-blur-sm',
+ 'transition-transform duration-300 ease-landing-out-quart hover:-translate-y-1 hover:border-brand-500/40',
+ 'focus-within:-translate-y-1 focus-within:border-brand-500/40',
+ )}
+ >
+ <div className="flex items-center gap-3">
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'inline-flex h-9 w-9 items-center justify-center rounded-lg bg-gradient-to-br ring-1 ring-inset',
+ agent.accent,
+ )}
+ >
+ <Icon className="h-4 w-4" />
+ </span>
+ <h3 className="text-base font-semibold tracking-tight text-fg-primary">
+ {agent.label}
+ </h3>
+ <span
+ aria-hidden="true"
+ className="ml-auto inline-flex items-center justify-center rounded-md border border-surface-border bg-surface-raised/60 px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.12em] text-fg-subtle"
+ >
+ 0{index + 1}
+ </span>
+ </div>
+ <p className="text-sm font-medium leading-snug text-fg-primary">
+ {agent.job}
+ </p>
+ <dl className="mt-auto space-y-2 text-xs">
+ <div>
+ <dt className="font-semibold uppercase tracking-[0.12em] text-fg-subtle">
+ Capabilities
+ </dt>
+ <dd className="mt-1 leading-relaxed text-fg-secondary">
+ {agent.capabilities}
+ </dd>
+ </div>
+ <div>
+ <dt className="font-semibold uppercase tracking-[0.12em] text-fg-subtle">
+ Runs on
+ </dt>
+ <dd className="mt-1 leading-relaxed text-fg-muted">{agent.runsOn}</dd>
+ </div>
+ </dl>
+ </motion.div>
+ );
+}
+
+export function SolutionAgents() {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const detectRef = useRef<HTMLDivElement | null>(null);
+ const triageRef = useRef<HTMLDivElement | null>(null);
+ const huntRef = useRef<HTMLDivElement | null>(null);
+ const respondRef = useRef<HTMLDivElement | null>(null);
+ const cardRefs = [detectRef, triageRef, huntRef, respondRef];
+ const prefersReducedMotion = useReducedMotion();
+
+ const [isHorizontal, setIsHorizontal] = useState(false);
+ useEffect(() => {
+ if (typeof window === 'undefined') return;
+ const mq = window.matchMedia('(min-width: 1024px)');
+ const onChange = () => setIsHorizontal(mq.matches);
+ onChange();
+ mq.addEventListener('change', onChange);
+ return () => mq.removeEventListener('change', onChange);
+ }, []);
+
+ return (
+ <section
+ id="solution"
+ aria-labelledby="solution-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <div className="mx-auto max-w-3xl text-center">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ Four agents, one workflow
+ </p>
+ <h2
+ id="solution-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ One agent for each stage of an incident.
+ </h2>
+ <p className="mt-4 text-base leading-relaxed text-fg-secondary sm:text-lg">
+ AiSOC ships exactly four named agents — Detect, Triage, Hunt, and
+ Respond. Each one has a fixed job, a published capability list,
+ and a replayable audit trail. Sub-agents (phishing, identity,
+ cloud, insider) are capabilities of Triage, never separate brands.
+ </p>
+ </div>
+
+ <div
+ ref={containerRef}
+ className="relative mt-12 grid gap-4 sm:gap-6 lg:mt-16 lg:grid-cols-4"
+ >
+ {AGENTS.map((agent, i) => (
+ <AgentCard
+ key={agent.id}
+ agent={agent}
+ index={i}
+ innerRef={cardRefs[i]}
+ />
+ ))}
+
+ {isHorizontal && !prefersReducedMotion && (
+ <>
+ <AnimatedBeam
+ containerRef={containerRef}
+ fromRef={detectRef}
+ toRef={triageRef}
+ duration={3}
+ delay={0}
+ curvature={0}
+ />
+ <AnimatedBeam
+ containerRef={containerRef}
+ fromRef={triageRef}
+ toRef={huntRef}
+ duration={3}
+ delay={0.7}
+ curvature={0}
+ gradientStart="#8b5cf6"
+ gradientStop="#3b82f6"
+ />
+ <AnimatedBeam
+ containerRef={containerRef}
+ fromRef={huntRef}
+ toRef={respondRef}
+ duration={3}
+ delay={1.4}
+ curvature={0}
+ gradientStart="#3b82f6"
+ gradientStop="#f97316"
+ />
+ </>
+ )}
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/StickyNav.tsx b/apps/web/src/components/landing/sections/StickyNav.tsx
new file mode 100644
index 000000000..44f750e54
--- /dev/null
+++ b/apps/web/src/components/landing/sections/StickyNav.tsx
@@ -0,0 +1,180 @@
+'use client';
+
+/**
+ * Sticky marketing nav for the T6.5 landing page (`apps/web/src/app/page.tsx`).
+ *
+ * The existing console nav (`landing/LandingNav.tsx`) is left in place because
+ * it's still imported from `/sovereign`, `/blog`, `/customers`, etc. — this
+ * file is the dedicated chrome for the GTM landing page only and is scoped
+ * to `landing/sections/` so it cannot collide.
+ *
+ * Behaviour matches `docs/design/landing-page-brief.md` §6.1:
+ * - transparent at the very top of the page
+ * - opaque + 1 px hairline + backdrop-blur after 12 px of scroll
+ * - mobile collapses links into a sheet, body scroll-locked while open
+ * - `prefers-reduced-motion` suppresses the opacity / translate transitions
+ */
+
+import Link from 'next/link';
+import { useEffect, useState } from 'react';
+import { ArrowRight, Menu, X } from 'lucide-react';
+import { GithubMark } from './icons';
+import { cn } from '@/lib/utils';
+
+const NAV_LINKS: ReadonlyArray<{ label: string; href: string }> = [
+ { label: 'Product', href: '#solution' },
+ { label: 'Solutions', href: '#pillars' },
+ { label: 'Connectors', href: '#connectors' },
+ { label: 'Benchmark', href: '#benchmark' },
+ { label: 'Pricing', href: '#pricing' },
+ { label: 'Docs', href: 'https://docs.aisoc.dev' },
+];
+
+export function StickyNav() {
+ const [scrolled, setScrolled] = useState(false);
+ const [open, setOpen] = useState(false);
+
+ useEffect(() => {
+ const onScroll = () => setScrolled(window.scrollY > 12);
+ onScroll();
+ window.addEventListener('scroll', onScroll, { passive: true });
+ return () => window.removeEventListener('scroll', onScroll);
+ }, []);
+
+ useEffect(() => {
+ if (typeof document === 'undefined') return;
+ document.body.style.overflow = open ? 'hidden' : '';
+ return () => {
+ document.body.style.overflow = '';
+ };
+ }, [open]);
+
+ return (
+ <header
+ className={cn(
+ 'fixed inset-x-0 top-0 z-50 transition-[background-color,border-color,backdrop-filter] duration-200 ease-landing-out-quart',
+ scrolled
+ ? 'border-b border-surface-border bg-surface-base/85 backdrop-blur-md'
+ : 'border-b border-transparent bg-transparent',
+ )}
+ >
+ <nav
+ aria-label="Primary"
+ className="mx-auto flex h-16 max-w-7xl items-center justify-between gap-4 px-4 sm:px-6 lg:px-8"
+ >
+ <Link
+ href="/"
+ aria-label="AiSOC home"
+ className="flex items-center gap-2 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ <span
+ aria-hidden="true"
+ className="inline-flex h-8 w-8 items-center justify-center rounded-md bg-gradient-to-br from-brand-400 to-brand-700 text-xs font-bold text-white shadow-[inset_0_0_0_1px_rgba(255,255,255,0.18)]"
+ >
+ Ai
+ </span>
+ <span className="text-base font-semibold tracking-tight text-fg-primary">
+ AiSOC
+ </span>
+ </Link>
+
+ <ul className="hidden items-center gap-1 lg:flex">
+ {NAV_LINKS.map((link) => (
+ <li key={link.href}>
+ <Link
+ href={link.href}
+ className="rounded-md px-3 py-2 text-sm font-medium text-fg-secondary transition-colors duration-150 ease-landing-out-quart hover:text-fg-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ {link.label}
+ </Link>
+ </li>
+ ))}
+ </ul>
+
+ <div className="hidden items-center gap-2 lg:flex">
+ <a
+ href="https://github.com/beenuar/AiSOC"
+ target="_blank"
+ rel="noreferrer"
+ aria-label="Star AiSOC on GitHub"
+ className="inline-flex items-center gap-2 rounded-md border border-surface-border bg-surface-raised/60 px-3 py-1.5 text-sm font-medium text-fg-secondary transition-colors duration-150 ease-landing-out-quart hover:border-brand-500/40 hover:text-fg-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ <GithubMark className="h-3.5 w-3.5" />
+ <span aria-hidden="true">Star on GitHub</span>
+ </a>
+ <Link
+ href="#pricing"
+ className="rounded-md px-3 py-1.5 text-sm font-medium text-fg-secondary transition-colors duration-150 ease-landing-out-quart hover:text-fg-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ Self-host
+ </Link>
+ <Link
+ href="https://app.aisoc.dev/signup"
+ className="group inline-flex items-center gap-1 rounded-md bg-gradient-to-br from-brand-500 to-brand-700 px-4 py-1.5 text-sm font-semibold text-white shadow-[0_1px_0_rgba(255,255,255,0.18)_inset] transition-shadow duration-200 ease-landing-out-quart hover:shadow-[0_8px_24px_-8px_rgba(59,130,246,0.55)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ Start free
+ <ArrowRight
+ className="h-3.5 w-3.5 transition-transform duration-200 ease-landing-out-quart group-hover:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ </div>
+
+ <button
+ type="button"
+ onClick={() => setOpen((value) => !value)}
+ aria-expanded={open}
+ aria-controls="aisoc-mobile-nav"
+ aria-label={open ? 'Close menu' : 'Open menu'}
+ className="inline-flex h-9 w-9 items-center justify-center rounded-md border border-surface-border bg-surface-raised/60 text-fg-secondary transition-colors duration-150 ease-landing-out-quart hover:border-brand-500/40 hover:text-fg-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base lg:hidden"
+ >
+ {open ? (
+ <X className="h-4 w-4" aria-hidden="true" />
+ ) : (
+ <Menu className="h-4 w-4" aria-hidden="true" />
+ )}
+ </button>
+ </nav>
+
+ <div
+ id="aisoc-mobile-nav"
+ className={cn(
+ 'lg:hidden',
+ 'overflow-hidden border-t border-surface-border bg-surface-base/95 backdrop-blur-md transition-[max-height,opacity] duration-200 ease-landing-out-quart',
+ open ? 'max-h-[60vh] opacity-100' : 'max-h-0 opacity-0',
+ )}
+ >
+ <ul className="space-y-1 px-4 py-3">
+ {NAV_LINKS.map((link) => (
+ <li key={link.href}>
+ <Link
+ href={link.href}
+ onClick={() => setOpen(false)}
+ className="block rounded-md px-3 py-2 text-sm font-medium text-fg-secondary transition-colors duration-150 ease-landing-out-quart hover:bg-surface-hover hover:text-fg-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300"
+ >
+ {link.label}
+ </Link>
+ </li>
+ ))}
+ </ul>
+ <div className="flex gap-2 px-4 pb-4">
+ <a
+ href="https://github.com/beenuar/AiSOC"
+ target="_blank"
+ rel="noreferrer"
+ className="flex-1 rounded-md border border-surface-border bg-surface-raised/60 px-3 py-2 text-center text-sm font-medium text-fg-secondary"
+ >
+ Self-host
+ </a>
+ <Link
+ href="https://app.aisoc.dev/signup"
+ onClick={() => setOpen(false)}
+ className="flex-1 rounded-md bg-gradient-to-br from-brand-500 to-brand-700 px-3 py-2 text-center text-sm font-semibold text-white"
+ >
+ Start free
+ </Link>
+ </div>
+ </div>
+ </header>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/Testimonials.tsx b/apps/web/src/components/landing/sections/Testimonials.tsx
new file mode 100644
index 000000000..7b8f03d26
--- /dev/null
+++ b/apps/web/src/components/landing/sections/Testimonials.tsx
@@ -0,0 +1,88 @@
+'use client';
+
+/**
+ * "From the people running it" — `testimonials` section from §6.12 of
+ * the brief.
+ *
+ * Empty-state surface: there are no published case studies yet, so we
+ * ship the honest version rather than fabricated quotes. Per the
+ * content doc, once `apps/web/content/customers/*.mdx` has at least
+ * two real studies the carousel below replaces this block — but
+ * unverified social proof is worse than no social proof.
+ *
+ * - Eyebrow + H2 from the content doc.
+ * - Centered card: H3 ("Be the first reference team."), body,
+ * CTA ("Become a reference partner").
+ * - Decorative `Meteors` layer behind the card adds gentle motion
+ * without implying a non-existent customer base.
+ */
+
+import Link from 'next/link';
+import { motion, useReducedMotion } from 'framer-motion';
+import { ArrowRight, ShieldCheck } from 'lucide-react';
+import { Meteors } from '@/components/magicui/Meteors';
+
+export function Testimonials() {
+ const prefersReducedMotion = useReducedMotion();
+
+ return (
+ <section
+ id="testimonials"
+ aria-labelledby="testimonials-heading"
+ className="relative py-20 sm:py-24 lg:py-28"
+ >
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
+ <div className="mx-auto max-w-3xl text-center">
+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-brand-400">
+ From the people running it
+ </p>
+ <h2
+ id="testimonials-heading"
+ className="mt-3 text-3xl font-bold tracking-tight text-fg-primary sm:text-4xl lg:text-[40px] lg:leading-[1.15] lg:tracking-[-0.015em]"
+ >
+ What teams say after their first month.
+ </h2>
+ </div>
+
+ <motion.div
+ initial={prefersReducedMotion ? false : { opacity: 0, y: 24 }}
+ whileInView={{ opacity: 1, y: 0 }}
+ viewport={{ once: true, margin: '-15%' }}
+ transition={{ duration: 0.6, ease: [0.16, 1, 0.3, 1] }}
+ className="relative mx-auto mt-12 max-w-2xl overflow-hidden rounded-2xl border border-surface-border bg-surface-card/80 p-8 backdrop-blur-sm sm:p-10 lg:mt-16"
+ >
+ {!prefersReducedMotion && (
+ <Meteors number={14} className="opacity-50" />
+ )}
+ <div className="relative flex flex-col items-center text-center">
+ <span
+ aria-hidden="true"
+ className="inline-flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500/20 to-landing-accent-violet/20 text-brand-300 ring-1 ring-inset ring-brand-500/30"
+ >
+ <ShieldCheck className="h-6 w-6" />
+ </span>
+ <h3 className="mt-5 text-xl font-bold text-fg-primary sm:text-2xl">
+ Be the first reference team.
+ </h3>
+ <p className="mt-3 max-w-xl text-base leading-relaxed text-fg-secondary">
+ We are onboarding reference partners through Q2 2026. If your
+ team ships AiSOC into production, we will publish your case
+ study under your byline, with the before/after metrics you
+ choose.
+ </p>
+ <Link
+ href="/partners"
+ className="group mt-6 inline-flex h-10 items-center gap-2 rounded-md bg-gradient-to-br from-brand-500 to-brand-700 px-4 text-sm font-semibold text-white shadow-[0_1px_0_rgba(255,255,255,0.18)_inset] transition-shadow duration-200 ease-landing-out-quart hover:shadow-[0_12px_32px_-12px_rgba(59,130,246,0.65)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base"
+ >
+ Become a reference partner
+ <ArrowRight
+ className="h-3.5 w-3.5 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover:translate-x-0"
+ aria-hidden="true"
+ />
+ </Link>
+ </div>
+ </motion.div>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/landing/sections/icons.tsx b/apps/web/src/components/landing/sections/icons.tsx
new file mode 100644
index 000000000..dded6089d
--- /dev/null
+++ b/apps/web/src/components/landing/sections/icons.tsx
@@ -0,0 +1,24 @@
+import type { SVGProps } from 'react';
+
+/**
+ * Small bag of brand SVGs the marketing landing page needs that aren't
+ * available in `lucide-react` (brand icons were removed from the package
+ * around v0.469). Keep these inline so the landing route never reaches
+ * for a font-icon library or pulls a second copy of the GitHub mark.
+ *
+ * Geometry copied from the official GitHub Octicons mark (MIT-licensed).
+ */
+
+export function GithubMark(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ aria-hidden="true"
+ focusable="false"
+ {...props}
+ >
+ <path d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.69-3.88-1.54-3.88-1.54-.52-1.32-1.27-1.67-1.27-1.67-1.04-.71.08-.69.08-.69 1.15.08 1.76 1.18 1.76 1.18 1.02 1.75 2.68 1.24 3.34.95.1-.74.4-1.24.73-1.53-2.55-.29-5.24-1.28-5.24-5.69 0-1.26.45-2.29 1.18-3.1-.12-.29-.51-1.46.11-3.05 0 0 .96-.31 3.15 1.18a10.9 10.9 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.59.23 2.76.11 3.05.74.81 1.18 1.84 1.18 3.1 0 4.42-2.7 5.39-5.27 5.68.41.36.78 1.06.78 2.14 0 1.55-.01 2.79-.01 3.17 0 .31.21.68.8.56C20.21 21.39 23.5 17.08 23.5 12 23.5 5.65 18.35.5 12 .5z" />
+ </svg>
+ );
+}
diff --git a/apps/web/src/components/magicui/AnimatedBeam.tsx b/apps/web/src/components/magicui/AnimatedBeam.tsx
new file mode 100644
index 000000000..58ef2e84b
--- /dev/null
+++ b/apps/web/src/components/magicui/AnimatedBeam.tsx
@@ -0,0 +1,123 @@
+// Source: https://magicui.design/docs/components/animated-beam
+// Licensed under MIT. Vendored implementation. Draws a curved SVG path
+// between two ref'd DOM nodes (e.g. two agent cards) and animates a
+// brand-tinted comet along it. Falls back to a static path under
+// `prefers-reduced-motion` per `landing-page-motion-spec.md` §2.5.
+'use client';
+
+import { motion, useReducedMotion } from 'framer-motion';
+import { type RefObject, useCallback, useEffect, useId, useState } from 'react';
+import { cn } from '@/lib/utils';
+
+interface AnimatedBeamProps {
+ containerRef: RefObject<HTMLElement | null>;
+ fromRef: RefObject<HTMLElement | null>;
+ toRef: RefObject<HTMLElement | null>;
+ className?: string;
+ /** Negative for an arc that bows upward, positive for downward. */
+ curvature?: number;
+ /** Comet duration in seconds. */
+ duration?: number;
+ /** Negative phase shift (in seconds) so multiple beams don't fire in lockstep. */
+ delay?: number;
+ pathColor?: string;
+ pathOpacity?: number;
+ gradientStart?: string;
+ gradientStop?: string;
+ reverse?: boolean;
+}
+
+export function AnimatedBeam({
+ containerRef,
+ fromRef,
+ toRef,
+ className,
+ curvature = -30,
+ duration = 3,
+ delay = 0,
+ pathColor = 'rgba(148,163,184,0.18)',
+ pathOpacity = 1,
+ gradientStart = '#3b82f6',
+ gradientStop = '#8b5cf6',
+ reverse = false,
+}: AnimatedBeamProps) {
+ const id = useId();
+ const [path, setPath] = useState('');
+ const [size, setSize] = useState({ w: 0, h: 0 });
+ const prefersReducedMotion = useReducedMotion();
+
+ const update = useCallback(() => {
+ const container = containerRef.current;
+ const from = fromRef.current;
+ const to = toRef.current;
+ if (!container || !from || !to) return;
+ const cRect = container.getBoundingClientRect();
+ const fRect = from.getBoundingClientRect();
+ const tRect = to.getBoundingClientRect();
+ setSize({ w: cRect.width, h: cRect.height });
+ const x1 = fRect.left + fRect.width / 2 - cRect.left;
+ const y1 = fRect.top + fRect.height / 2 - cRect.top;
+ const x2 = tRect.left + tRect.width / 2 - cRect.left;
+ const y2 = tRect.top + tRect.height / 2 - cRect.top;
+ const midX = (x1 + x2) / 2;
+ const midY = (y1 + y2) / 2 + curvature;
+ setPath(`M ${x1},${y1} Q ${midX},${midY} ${x2},${y2}`);
+ }, [containerRef, fromRef, toRef, curvature]);
+
+ useEffect(() => {
+ update();
+ window.addEventListener('resize', update);
+ const interval = window.setTimeout(update, 80); // post-layout settle
+ return () => {
+ window.removeEventListener('resize', update);
+ window.clearTimeout(interval);
+ };
+ }, [update]);
+
+ if (!path) return null;
+
+ const grad = `url(#${id.replace(/[:]/g, '')}-grad)`;
+
+ return (
+ <svg
+ width={size.w}
+ height={size.h}
+ viewBox={`0 0 ${size.w} ${size.h}`}
+ className={cn('pointer-events-none absolute inset-0', className)}
+ aria-hidden="true"
+ >
+ <defs>
+ <linearGradient
+ id={`${id.replace(/[:]/g, '')}-grad`}
+ x1="0%"
+ y1="0%"
+ x2="100%"
+ y2="0%"
+ gradientUnits="userSpaceOnUse"
+ >
+ <stop offset="0%" stopColor={gradientStart} stopOpacity="0" />
+ <stop offset="50%" stopColor={reverse ? gradientStop : gradientStart} stopOpacity="1" />
+ <stop offset="100%" stopColor={reverse ? gradientStart : gradientStop} stopOpacity="0" />
+ </linearGradient>
+ </defs>
+ <path d={path} stroke={pathColor} strokeOpacity={pathOpacity} strokeWidth="1.5" fill="none" />
+ {!prefersReducedMotion && (
+ <motion.path
+ d={path}
+ stroke={grad}
+ strokeWidth="2"
+ fill="none"
+ strokeLinecap="round"
+ initial={{ pathLength: 0, pathOffset: 0, opacity: 0.6 }}
+ animate={{ pathLength: 1, pathOffset: reverse ? -1 : 1, opacity: [0, 0.9, 0] }}
+ transition={{
+ duration,
+ repeat: Infinity,
+ ease: [0.65, 0, 0.35, 1],
+ delay,
+ }}
+ />
+ )}
+ </svg>
+ );
+}
diff --git a/apps/web/src/components/magicui/AnimatedGridPattern.tsx b/apps/web/src/components/magicui/AnimatedGridPattern.tsx
new file mode 100644
index 000000000..d178269c4
--- /dev/null
+++ b/apps/web/src/components/magicui/AnimatedGridPattern.tsx
@@ -0,0 +1,103 @@
+// Source: https://magicui.design/docs/components/animated-grid-pattern
+// Licensed under MIT. Vendored implementation. Renders a subtle grid of
+// equally-sized squares; a handful of randomly-chosen squares fade in and
+// out on a stagger so the hero never feels static. Disabled entirely
+// under `prefers-reduced-motion` — a flat grid still tells the same story.
+'use client';
+
+import { motion, useReducedMotion } from 'framer-motion';
+import { useEffect, useMemo, useState } from 'react';
+import { cn } from '@/lib/utils';
+
+interface AnimatedGridPatternProps {
+ className?: string;
+ /** Side length (px) of one grid square. */
+ width?: number;
+ height?: number;
+ /** Total number of squares that participate in the fade animation. */
+ numSquares?: number;
+ /** Max opacity any single square reaches during fade. */
+ maxOpacity?: number;
+ /** Duration (seconds) for each fade cycle. */
+ duration?: number;
+ /** Delay (seconds) between cycles for each square. */
+ repeatDelay?: number;
+}
+
+interface Square {
+ id: number;
+ x: number;
+ y: number;
+}
+
+export function AnimatedGridPattern({
+ className,
+ width = 56,
+ height = 56,
+ numSquares = 48,
+ maxOpacity = 0.08,
+ duration = 3,
+ repeatDelay = 1,
+}: AnimatedGridPatternProps) {
+ const prefersReducedMotion = useReducedMotion();
+ const [dim, setDim] = useState({ w: 0, h: 0 });
+
+ useEffect(() => {
+ const update = () => {
+ if (typeof window === 'undefined') return;
+ setDim({ w: window.innerWidth, h: window.innerHeight });
+ };
+ update();
+ window.addEventListener('resize', update);
+ return () => window.removeEventListener('resize', update);
+ }, []);
+
+ const cols = Math.max(1, Math.ceil(dim.w / width));
+ const rows = Math.max(1, Math.ceil(dim.h / height));
+
+ const squares = useMemo<Square[]>(() => {
+ if (cols === 0 || rows === 0) return [];
+ return Array.from({ length: numSquares }, (_, idx) => ({
+ id: idx,
+ x: Math.floor(Math.random() * cols),
+ y: Math.floor(Math.random() * rows),
+ }));
+ }, [cols, rows, numSquares]);
+
+ return (
+ <svg
+ aria-hidden="true"
+ className={cn(
+ 'pointer-events-none absolute inset-0 h-full w-full text-brand-500/15 [mask-image:radial-gradient(circle_at_center,white,transparent_70%)]',
+ className,
+ )}
+ >
+ <defs>
+ <pattern id="aisoc-grid-pattern" width={width} height={height} patternUnits="userSpaceOnUse">
+ <path d={`M.5 ${height}V.5H${width}`} fill="none" stroke="currentColor" strokeWidth="1" />
+ </pattern>
+ </defs>
+ <rect width="100%" height="100%" fill="url(#aisoc-grid-pattern)" />
+ {!prefersReducedMotion &&
+ squares.map(({ id, x, y }) => (
+ <motion.rect
+ key={id}
+ width={width - 1}
+ height={height - 1}
+ x={x * width + 1}
+ y={y * height + 1}
+ fill="currentColor"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: [0, maxOpacity, 0] }}
+ transition={{
+ duration,
+ repeat: Infinity,
+ repeatDelay,
+ delay: id * 0.12,
+ ease: 'easeInOut',
+ }}
+ />
+ ))}
+ </svg>
+ );
+}
diff --git a/apps/web/src/components/magicui/AuroraText.tsx b/apps/web/src/components/magicui/AuroraText.tsx
new file mode 100644
index 000000000..66b4587e4
--- /dev/null
+++ b/apps/web/src/components/magicui/AuroraText.tsx
@@ -0,0 +1,30 @@
+// Source: https://magicui.design/docs/components/aurora-text
+// Licensed under MIT. Vendored implementation. Renders inline text with
+// a slow-shifting aurora gradient (brand-500 → violet → brand-700) so
+// the hero H1's accent phrase ("ten minutes" in the content doc) draws
+// the eye without competing with the surrounding white text.
+'use client';
+
+import { useReducedMotion } from 'framer-motion';
+import type { ReactNode } from 'react';
+import { cn } from '@/lib/utils';
+
+interface AuroraTextProps {
+ children: ReactNode;
+ className?: string;
+}
+
+export function AuroraText({ children, className }: AuroraTextProps) {
+ const prefersReducedMotion = useReducedMotion();
+ return (
+ <span
+ className={cn(
+ 'inline-block bg-gradient-to-r from-brand-300 via-landing-accent-violet to-brand-500 bg-clip-text text-transparent',
+ !prefersReducedMotion && 'animate-aurora-shift [background-size:200%_100%]',
+ className,
+ )}
+ >
+ {children}
+ </span>
+ );
+}
diff --git a/apps/web/src/components/magicui/BorderBeam.tsx b/apps/web/src/components/magicui/BorderBeam.tsx
new file mode 100644
index 000000000..dde48c858
--- /dev/null
+++ b/apps/web/src/components/magicui/BorderBeam.tsx
@@ -0,0 +1,69 @@
+// Source: https://magicui.design/docs/components/border-beam
+// Licensed under MIT. Vendored implementation. A brand-tinted comet
+// traces the border of the parent (which must be `position: relative`
+// and have a non-zero border-radius). Driven by a single CSS keyframe
+// (`border-beam` in `globals.css`) using the new `offset-path` API.
+// Falls back to a static 1 px brand border under `prefers-reduced-motion`.
+'use client';
+
+import { useReducedMotion } from 'framer-motion';
+import { cn } from '@/lib/utils';
+
+interface BorderBeamProps {
+ className?: string;
+ /** Size of the comet in pixels. */
+ size?: number;
+ /** Animation duration in seconds. */
+ duration?: number;
+ /** Comet gradient start color. */
+ colorFrom?: string;
+ /** Comet gradient end color. */
+ colorTo?: string;
+ /** Negative delay in seconds to phase-shift the beam. */
+ delay?: number;
+}
+
+export function BorderBeam({
+ className,
+ size = 200,
+ duration = 12,
+ colorFrom = '#3b82f6',
+ colorTo = '#8b5cf6',
+ delay = 0,
+}: BorderBeamProps) {
+ const prefersReducedMotion = useReducedMotion();
+ if (prefersReducedMotion) {
+ return (
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'pointer-events-none absolute inset-0 rounded-[inherit] border border-brand-500/30',
+ className,
+ )}
+ />
+ );
+ }
+ return (
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'pointer-events-none absolute inset-0 rounded-[inherit] [border:calc(var(--border-width)*1px)_solid_transparent]',
+ '[mask-clip:padding-box,border-box] [mask-composite:intersect] [mask-image:linear-gradient(transparent,transparent),linear-gradient(white,white)]',
+ // The single moving dot drawn along the border path.
+ 'after:absolute after:aspect-square after:w-[calc(var(--size)*1px)] after:animate-[border-beam_calc(var(--duration)*1s)_infinite_linear]',
+ 'after:[background:linear-gradient(to_left,var(--color-from),var(--color-to),transparent)] after:[offset-anchor:90%_50%] after:[offset-path:rect(0_auto_auto_0_round_calc(var(--size)*1px))]',
+ className,
+ )}
+ style={
+ {
+ '--size': String(size),
+ '--duration': String(duration),
+ '--border-width': '1.4',
+ '--color-from': colorFrom,
+ '--color-to': colorTo,
+ animationDelay: `${delay}s`,
+ } as React.CSSProperties
+ }
+ />
+ );
+}
diff --git a/apps/web/src/components/magicui/Marquee.tsx b/apps/web/src/components/magicui/Marquee.tsx
new file mode 100644
index 000000000..eb3fcf1a8
--- /dev/null
+++ b/apps/web/src/components/magicui/Marquee.tsx
@@ -0,0 +1,58 @@
+// Source: https://magicui.design/docs/components/marquee
+// Licensed under MIT. Vendored implementation. Renders an infinitely
+// scrolling row by duplicating its children once and using a CSS keyframe
+// (`animate-marquee` in `globals.css`) for the translate. Pauses on hover
+// via the `marquee-pausable` wrapper class.
+'use client';
+
+import type { ReactNode } from 'react';
+import { cn } from '@/lib/utils';
+
+interface MarqueeProps {
+ className?: string;
+ /** Scroll right-to-left when false, left-to-right when true. */
+ reverse?: boolean;
+ /** Number of times to duplicate the children for visual seamlessness. */
+ repeat?: number;
+ /** Pause animation when the wrapper is hovered or focused. Default true. */
+ pauseOnHover?: boolean;
+ /** Scroll vertically. */
+ vertical?: boolean;
+ children: ReactNode;
+}
+
+export function Marquee({
+ className,
+ reverse = false,
+ repeat = 2,
+ pauseOnHover = true,
+ vertical = false,
+ children,
+}: MarqueeProps) {
+ return (
+ <div
+ className={cn(
+ 'group/marquee relative flex w-full overflow-hidden [--gap:1.5rem]',
+ vertical ? 'flex-col' : 'flex-row',
+ pauseOnHover && 'marquee-pausable',
+ className,
+ )}
+ >
+ {Array.from({ length: repeat }).map((_, idx) => (
+ <div
+ key={idx}
+ className={cn(
+ 'flex shrink-0 justify-around gap-[--gap]',
+ vertical
+ ? 'animate-marquee-vertical flex-col'
+ : 'animate-marquee flex-row',
+ reverse && '[animation-direction:reverse]',
+ )}
+ aria-hidden={idx === 0 ? undefined : 'true'}
+ >
+ {children}
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/magicui/Meteors.tsx b/apps/web/src/components/magicui/Meteors.tsx
new file mode 100644
index 000000000..746657669
--- /dev/null
+++ b/apps/web/src/components/magicui/Meteors.tsx
@@ -0,0 +1,47 @@
+// Source: https://magicui.design/docs/components/meteors
+// Licensed under MIT. Vendored implementation. Renders a configurable
+// number of meteor streaks across the parent. Each meteor uses the
+// shared `animate-meteor` keyframe in `globals.css`; the JS layer only
+// computes initial start positions and a per-meteor delay. Hidden under
+// `prefers-reduced-motion`.
+'use client';
+
+import { useReducedMotion } from 'framer-motion';
+import { useMemo } from 'react';
+import { cn } from '@/lib/utils';
+
+interface MeteorsProps {
+ /** Number of meteors to render. Default 18 — pre-trimmed for the perf budget. */
+ number?: number;
+ className?: string;
+}
+
+export function Meteors({ number = 18, className }: MeteorsProps) {
+ const prefersReducedMotion = useReducedMotion();
+ const meteors = useMemo(
+ () =>
+ Array.from({ length: number }, (_, idx) => ({
+ id: idx,
+ top: `${Math.floor(Math.random() * 100)}%`,
+ left: `${Math.floor(Math.random() * 100)}%`,
+ delay: `${Math.random() * 4}s`,
+ duration: `${4 + Math.random() * 6}s`,
+ })),
+ [number],
+ );
+
+ if (prefersReducedMotion) return null;
+
+ return (
+ <div className={cn('pointer-events-none absolute inset-0 overflow-hidden', className)}>
+ {meteors.map(({ id, top, left, delay, duration }) => (
+ <span
+ key={id}
+ aria-hidden="true"
+ className="absolute h-0.5 w-0.5 rotate-[215deg] animate-meteor rounded-full bg-slate-200 shadow-[0_0_0_1px_rgba(255,255,255,0.1)] before:absolute before:top-1/2 before:h-px before:w-12 before:-translate-y-1/2 before:bg-gradient-to-r before:from-slate-100 before:to-transparent before:content-['']"
+ style={{ top, left, animationDelay: delay, animationDuration: duration }}
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/magicui/NumberTicker.tsx b/apps/web/src/components/magicui/NumberTicker.tsx
new file mode 100644
index 000000000..fdee5500f
--- /dev/null
+++ b/apps/web/src/components/magicui/NumberTicker.tsx
@@ -0,0 +1,78 @@
+// Source: https://magicui.design/docs/components/number-ticker
+// Licensed under MIT. Vendored implementation. Counts a number up (or
+// down) to its target value once the element scrolls into view; uses a
+// framer-motion `motionValue` so the count is composited on the GPU.
+// Falls back to the final value immediately under `prefers-reduced-motion`.
+'use client';
+
+import {
+ motion,
+ useInView,
+ useMotionValue,
+ useReducedMotion,
+ useSpring,
+ useTransform,
+} from 'framer-motion';
+import { useEffect, useRef } from 'react';
+import { cn } from '@/lib/utils';
+
+interface NumberTickerProps {
+ value: number;
+ className?: string;
+ /** Number of decimal places to render. Default 0. */
+ decimalPlaces?: number;
+ /** Direction of the count. */
+ direction?: 'up' | 'down';
+ /** Delay before the ticker begins, in seconds. */
+ delay?: number;
+ /** Locale used to format the rendered number. */
+ locale?: string;
+}
+
+export function NumberTicker({
+ value,
+ className,
+ decimalPlaces = 0,
+ direction = 'up',
+ delay = 0,
+ locale = 'en-US',
+}: NumberTickerProps) {
+ const ref = useRef<HTMLSpanElement | null>(null);
+ const isInView = useInView(ref, { once: true, margin: '0px' });
+ const prefersReducedMotion = useReducedMotion();
+ const start = direction === 'up' ? 0 : value;
+ const target = direction === 'up' ? value : 0;
+ const motionValue = useMotionValue(start);
+ const spring = useSpring(motionValue, { damping: 28, stiffness: 90 });
+ const formatted = useTransform(spring, (latest: number) =>
+ Number(latest).toLocaleString(locale, {
+ minimumFractionDigits: decimalPlaces,
+ maximumFractionDigits: decimalPlaces,
+ }),
+ );
+
+ useEffect(() => {
+ if (!isInView) return;
+ if (prefersReducedMotion) {
+ motionValue.set(target);
+ return;
+ }
+ const timeout = window.setTimeout(() => {
+ motionValue.set(target);
+ }, delay * 1000);
+ return () => window.clearTimeout(timeout);
+ }, [isInView, motionValue, prefersReducedMotion, target, delay]);
+
+ return (
+ <motion.span
+ ref={ref}
+ className={cn('tabular-nums', className)}
+ aria-label={value.toLocaleString(locale, {
+ minimumFractionDigits: decimalPlaces,
+ maximumFractionDigits: decimalPlaces,
+ })}
+ >
+ {formatted}
+ </motion.span>
+ );
+}
diff --git a/apps/web/src/components/magicui/ShimmerButton.tsx b/apps/web/src/components/magicui/ShimmerButton.tsx
new file mode 100644
index 000000000..9af18c108
--- /dev/null
+++ b/apps/web/src/components/magicui/ShimmerButton.tsx
@@ -0,0 +1,65 @@
+// Source: https://magicui.design/docs/components/shimmer-button
+// Licensed under MIT. Vendored implementation. A brand-tinted button that
+// loops a soft sheen across its surface on hover only — never on mount —
+// so the conversion target never competes with the H1 reveal for
+// attention. Reduces to a solid brand-500 button under
+// `prefers-reduced-motion`.
+'use client';
+
+import type { ButtonHTMLAttributes } from 'react';
+import { forwardRef } from 'react';
+import { cn } from '@/lib/utils';
+
+type ShimmerButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
+ shimmerColor?: string;
+ shimmerDuration?: string;
+};
+
+export const ShimmerButton = forwardRef<HTMLButtonElement, ShimmerButtonProps>(
+ function ShimmerButton(
+ {
+ children,
+ className,
+ shimmerColor = 'rgba(147,197,253,0.65)',
+ shimmerDuration = '2.5s',
+ ...rest
+ },
+ ref,
+ ) {
+ return (
+ <button
+ ref={ref}
+ className={cn(
+ 'group/shimmer relative inline-flex h-11 cursor-pointer items-center justify-center overflow-hidden rounded-md bg-gradient-to-br from-brand-500 to-brand-700 px-6 text-sm font-semibold text-white shadow-[0_0_0_1px_rgba(59,130,246,0.35)] transition-shadow duration-200 ease-landing-in-out-quad',
+ 'hover:shadow-[0_8px_24px_-8px_rgba(59,130,246,0.55)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base',
+ 'motion-reduce:hover:shadow-none',
+ className,
+ )}
+ style={
+ {
+ '--shimmer-color': shimmerColor,
+ '--shimmer-duration': shimmerDuration,
+ } as React.CSSProperties
+ }
+ {...rest}
+ >
+ <span
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-0 -translate-x-full bg-[linear-gradient(110deg,transparent_0%,var(--shimmer-color)_50%,transparent_100%)] opacity-0 transition-opacity duration-200 ease-out group-hover/shimmer:opacity-100 group-hover/shimmer:[animation:shimmer-pass_var(--shimmer-duration)_linear_infinite] motion-reduce:hidden"
+ />
+ <span className="relative z-10 flex items-center gap-2">{children}</span>
+ </button>
+ );
+ },
+);
+
+// Keyframe lives here so a host page that imports the button gets the
+// animation without needing to load it from globals.css separately. This
+// is the one keyframe we keep co-located with its consumer — every other
+// landing-page keyframe is in globals.css.
+if (typeof document !== 'undefined' && !document.getElementById('shimmer-button-keyframe')) {
+ const style = document.createElement('style');
+ style.id = 'shimmer-button-keyframe';
+ style.textContent = `@keyframes shimmer-pass { from { transform: translateX(-120%); } to { transform: translateX(120%); } }`;
+ document.head.appendChild(style);
+}
diff --git a/apps/web/src/components/magicui/ShineBorder.tsx b/apps/web/src/components/magicui/ShineBorder.tsx
new file mode 100644
index 000000000..d252162f1
--- /dev/null
+++ b/apps/web/src/components/magicui/ShineBorder.tsx
@@ -0,0 +1,57 @@
+// Source: https://magicui.design/docs/components/shine-border
+// Licensed under MIT. Vendored implementation. Adds a soft tri-stop
+// conic-gradient border to the parent (must be `position: relative`)
+// that animates around its perimeter. Cheaper than `BorderBeam` for the
+// cases where a constant, low-energy frame is all we need (deploy-
+// options "sovereign" card, pricing teaser card).
+'use client';
+
+import { useReducedMotion } from 'framer-motion';
+import { cn } from '@/lib/utils';
+
+interface ShineBorderProps {
+ className?: string;
+ /** Animation duration in seconds. */
+ duration?: number;
+ /** Tailwind class for border-width (defaults to `[--border-radius:1rem]` parent). */
+ borderWidth?: number;
+ /** Comma-separated CSS color stops. */
+ colors?: readonly string[];
+}
+
+export function ShineBorder({
+ className,
+ duration = 14,
+ borderWidth = 1,
+ colors = ['#3b82f6', '#8b5cf6', '#1d4ed8'],
+}: ShineBorderProps) {
+ const prefersReducedMotion = useReducedMotion();
+ if (prefersReducedMotion) {
+ return (
+ <span
+ aria-hidden="true"
+ className={cn('pointer-events-none absolute inset-0 rounded-[inherit] border border-brand-500/25', className)}
+ />
+ );
+ }
+ return (
+ <span
+ aria-hidden="true"
+ style={
+ {
+ '--shine-duration': `${duration}s`,
+ '--shine-border-width': `${borderWidth}px`,
+ '--shine-color-stops': colors.join(','),
+ } as React.CSSProperties
+ }
+ className={cn(
+ // Solid 1 px border in the brand gradient. Cheaper than the upstream
+ // conic-gradient + mask-composite trick and still reads as "active"
+ // against the surface-raised card body.
+ 'pointer-events-none absolute inset-0 rounded-[inherit] [background:linear-gradient(135deg,var(--shine-color-stops))] [padding:var(--shine-border-width)]',
+ '[mask-composite:exclude] [mask:linear-gradient(white,white)_content-box,linear-gradient(white,white)]',
+ className,
+ )}
+ />
+ );
+}
diff --git a/apps/web/src/components/soc-insights/SOCInsightsView.test.tsx b/apps/web/src/components/soc-insights/SOCInsightsView.test.tsx
index c145863ed..098e50cd1 100644
--- a/apps/web/src/components/soc-insights/SOCInsightsView.test.tsx
+++ b/apps/web/src/components/soc-insights/SOCInsightsView.test.tsx
@@ -12,8 +12,6 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
-import { SWRConfig } from 'swr';
-import type { ReactNode } from 'react';
vi.mock('@/lib/api', () => ({
insightsApi: {
@@ -35,16 +33,6 @@ import { insightsApi, type SOCInsightsResponse } from '@/lib/api';
import { SOCInsightsView } from './SOCInsightsView';
import { pointsToPath } from './Sparkline';
-// SWR keeps a single global cache by default, which means the first test's
-// pending-forever promise survives into subsequent tests and pins them in
-// the loading state. Wrap each render in a fresh provider so every test
-// gets its own clean Map cache.
-function renderWithFreshSWR(node: ReactNode) {
- return render(
- <SWRConfig value={{ provider: () => new Map() }}>{node}</SWRConfig>,
- );
-}
-
const sampleResponse: SOCInsightsResponse = {
window: '24h',
generated_at: '2026-05-13T12:00:00Z',
@@ -128,7 +116,7 @@ describe('SOCInsightsView', () => {
new Promise(() => {}),
);
- renderWithFreshSWR(<SOCInsightsView />);
+ render(<SOCInsightsView />);
expect(screen.getByLabelText(/loading soc insights/i)).toBeInTheDocument();
});
@@ -138,7 +126,7 @@ describe('SOCInsightsView', () => {
sampleResponse,
);
- renderWithFreshSWR(<SOCInsightsView />);
+ render(<SOCInsightsView />);
// Wait for at least one tile to land — proves the SWR cycle
// completed without re-rendering into the error/loading branch.
@@ -162,7 +150,7 @@ describe('SOCInsightsView', () => {
new Error('500 boom'),
);
- renderWithFreshSWR(<SOCInsightsView />);
+ render(<SOCInsightsView />);
await waitFor(() =>
expect(screen.getByRole('alert')).toBeInTheDocument(),
diff --git a/apps/web/src/hooks/useGraphWebSocket.test.ts b/apps/web/src/hooks/useGraphWebSocket.test.ts
new file mode 100644
index 000000000..c3e3a736e
--- /dev/null
+++ b/apps/web/src/hooks/useGraphWebSocket.test.ts
@@ -0,0 +1,312 @@
+/**
+ * useGraphWebSocket — unit tests (T1.4 — v8.0).
+ *
+ * Covers the contract the consuming RealtimeGraph component relies on:
+ *
+ * - default URL composition (scheme, path, token query param)
+ * - JSON-frame parsing into a typed envelope
+ * - history bounding & "newest first" ordering
+ * - graceful handling of malformed / non-string frames
+ * - reconnect-on-close + exponential backoff (mocked clock)
+ * - cleanup on unmount cancels pending reconnects
+ *
+ * The WebSocket constructor is replaced with a controllable stub
+ * (``MockWebSocket``) so we can drive open / message / close events
+ * deterministically. We do NOT use ``vi.advanceTimersByTimeAsync``
+ * here because the React state batching plays badly with overlapping
+ * fake-timer windows — the `act` wrappers + ``vi.runOnlyPendingTimers``
+ * keep the assertions linear.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, renderHook } from '@testing-library/react';
+
+import { AUTH_TOKEN_KEY } from '@/lib/api';
+
+import {
+ __testables,
+ useGraphWebSocket,
+ type GraphUpdateEnvelope,
+} from './useGraphWebSocket';
+
+// --- WebSocket stub ----------------------------------------------------------
+
+type StubInstance = {
+ url: string;
+ readyState: number;
+ onopen: ((ev: Event) => void) | null;
+ onmessage: ((ev: MessageEvent) => void) | null;
+ onerror: ((ev: Event) => void) | null;
+ onclose: ((ev: CloseEvent) => void) | null;
+ open: () => void;
+ emit: (data: unknown) => void;
+ triggerError: () => void;
+ close: (code?: number) => void;
+};
+
+const created: StubInstance[] = [];
+
+class MockWebSocket implements StubInstance {
+ static CONNECTING = 0;
+ static OPEN = 1;
+ static CLOSING = 2;
+ static CLOSED = 3;
+
+ url: string;
+ readyState = MockWebSocket.CONNECTING;
+ onopen: ((ev: Event) => void) | null = null;
+ onmessage: ((ev: MessageEvent) => void) | null = null;
+ onerror: ((ev: Event) => void) | null = null;
+ onclose: ((ev: CloseEvent) => void) | null = null;
+
+ constructor(url: string) {
+ this.url = url;
+ created.push(this);
+ }
+
+ open() {
+ this.readyState = MockWebSocket.OPEN;
+ this.onopen?.(new Event('open'));
+ }
+
+ emit(data: unknown) {
+ const payload = typeof data === 'string' ? data : JSON.stringify(data);
+ this.onmessage?.(new MessageEvent('message', { data: payload }));
+ }
+
+ triggerError() {
+ this.onerror?.(new Event('error'));
+ }
+
+ close() {
+ if (this.readyState === MockWebSocket.CLOSED) return;
+ this.readyState = MockWebSocket.CLOSED;
+ this.onclose?.(new CloseEvent('close', { code: 1000 }));
+ }
+}
+
+// --- Test helpers ------------------------------------------------------------
+
+function makeEnvelope(
+ i: number,
+ override: Partial<GraphUpdateEnvelope> = {},
+): GraphUpdateEnvelope {
+ return {
+ entity_id: `entity-${i}`,
+ change_type: 'upsert_node',
+ ts: new Date(1_700_000_000_000 + i * 1000).toISOString(),
+ label: 'Host',
+ schema_version: 'v1.0',
+ ...override,
+ };
+}
+
+const originalWebSocket = globalThis.WebSocket;
+
+beforeEach(() => {
+ created.length = 0;
+ Object.defineProperty(window, 'WebSocket', {
+ configurable: true,
+ writable: true,
+ value: MockWebSocket as unknown as typeof WebSocket,
+ });
+ (globalThis as unknown as { WebSocket: typeof WebSocket }).WebSocket =
+ MockWebSocket as unknown as typeof WebSocket;
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ Object.defineProperty(window, 'WebSocket', {
+ configurable: true,
+ writable: true,
+ value: originalWebSocket,
+ });
+ (globalThis as unknown as { WebSocket: typeof WebSocket }).WebSocket =
+ originalWebSocket;
+ window.localStorage.clear();
+});
+
+// --- Tests -------------------------------------------------------------------
+
+describe('useGraphWebSocket — URL composition', () => {
+ it('uses same-origin scheme + the /api/v1/graph_ws/stream path', () => {
+ const url = __testables.defaultGraphWsUrl(null);
+ // jsdom default origin is http://localhost → ws://localhost
+ expect(url.endsWith('/api/v1/graph_ws/stream')).toBe(true);
+ expect(url.startsWith('ws://') || url.startsWith('wss://')).toBe(true);
+ });
+
+ it('appends the token as ?token=<encoded>', () => {
+ const url = __testables.defaultGraphWsUrl('abc/def=&value');
+ expect(url).toContain('?token=abc%2Fdef%3D%26value');
+ });
+
+ it('reads the token from localStorage[AUTH_TOKEN_KEY] when not overridden', () => {
+ window.localStorage.setItem(AUTH_TOKEN_KEY, 'jwt-from-storage');
+ renderHook(() => useGraphWebSocket());
+ expect(created.length).toBe(1);
+ expect(created[0].url).toContain('token=jwt-from-storage');
+ });
+
+ it('honours an explicit token override', () => {
+ window.localStorage.setItem(AUTH_TOKEN_KEY, 'wrong');
+ renderHook(() => useGraphWebSocket({ token: 'explicit' }));
+ expect(created[0].url).toContain('token=explicit');
+ expect(created[0].url).not.toContain('wrong');
+ });
+
+ it('honours an explicit url override', () => {
+ renderHook(() =>
+ useGraphWebSocket({ url: 'ws://mock/stream', token: 'ignored' }),
+ );
+ // When url is set we pass it verbatim — auth is the proxy's problem.
+ expect(created[0].url).toBe('ws://mock/stream');
+ });
+});
+
+describe('useGraphWebSocket — connection lifecycle', () => {
+ it('starts idle and transitions through connecting → open', () => {
+ const { result } = renderHook(() =>
+ useGraphWebSocket({ url: 'ws://mock/stream' }),
+ );
+ expect(result.current.status).toBe('connecting');
+ act(() => {
+ created[0].open();
+ });
+ expect(result.current.status).toBe('open');
+ });
+
+ it('is a no-op when enabled is false', () => {
+ const { result } = renderHook(() =>
+ useGraphWebSocket({ url: 'ws://mock/stream', enabled: false }),
+ );
+ expect(created.length).toBe(0);
+ expect(result.current.status).toBe('idle');
+ });
+
+ it('returns to closed and schedules a reconnect on socket close', () => {
+ vi.useFakeTimers();
+ const { result, unmount } = renderHook(() =>
+ useGraphWebSocket({ url: 'ws://mock/stream', maxBackoffMs: 4000 }),
+ );
+ act(() => {
+ created[0].open();
+ });
+ expect(result.current.status).toBe('open');
+
+ act(() => {
+ created[0].close();
+ });
+ expect(result.current.status).toBe('closed');
+ expect(created.length).toBe(1);
+
+ // Fast-forward past the first backoff slot.
+ act(() => {
+ vi.advanceTimersByTime(2000);
+ });
+ expect(created.length).toBe(2);
+ expect(result.current.status).toBe('connecting');
+
+ unmount();
+ });
+
+ it('cleans up pending reconnect timers on unmount', () => {
+ vi.useFakeTimers();
+ const { unmount } = renderHook(() =>
+ useGraphWebSocket({ url: 'ws://mock/stream' }),
+ );
+ act(() => {
+ created[0].close();
+ });
+ unmount();
+ act(() => {
+ vi.advanceTimersByTime(60_000);
+ });
+ expect(created.length).toBe(1); // No reconnect after unmount.
+ });
+});
+
+describe('useGraphWebSocket — events stream', () => {
+ it('parses JSON frames into typed envelopes and exposes last + events', () => {
+ const { result } = renderHook(() =>
+ useGraphWebSocket({ url: 'ws://mock/stream' }),
+ );
+ act(() => {
+ created[0].open();
+ });
+
+ const env = makeEnvelope(1);
+ act(() => {
+ created[0].emit(env);
+ });
+
+ expect(result.current.last).toEqual(env);
+ expect(result.current.events).toHaveLength(1);
+ expect(result.current.events[0]).toEqual(env);
+ });
+
+ it('drops malformed frames silently', () => {
+ const { result } = renderHook(() =>
+ useGraphWebSocket({ url: 'ws://mock/stream' }),
+ );
+ act(() => {
+ created[0].open();
+ });
+
+ act(() => {
+ // Raw non-JSON text — JSON.parse throws.
+ created[0].onmessage?.(new MessageEvent('message', { data: 'not-json' }));
+ });
+ act(() => {
+ // Binary frame — typeof event.data !== 'string'.
+ created[0].onmessage?.(
+ new MessageEvent('message', {
+ data: new ArrayBuffer(8) as unknown as string,
+ }),
+ );
+ });
+
+ expect(result.current.last).toBeNull();
+ expect(result.current.events).toHaveLength(0);
+ });
+
+ it('keeps events newest-first and bounds the buffer at historyLimit', () => {
+ const { result } = renderHook(() =>
+ useGraphWebSocket({ url: 'ws://mock/stream', historyLimit: 3 }),
+ );
+ act(() => {
+ created[0].open();
+ });
+
+ for (let i = 0; i < 5; i++) {
+ const env = makeEnvelope(i);
+ act(() => {
+ created[0].emit(env);
+ });
+ }
+
+ expect(result.current.events).toHaveLength(3);
+ expect(result.current.events[0].entity_id).toBe('entity-4');
+ expect(result.current.events[2].entity_id).toBe('entity-2');
+ expect(result.current.last?.entity_id).toBe('entity-4');
+ });
+
+ it('clear() wipes history and last', () => {
+ const { result } = renderHook(() =>
+ useGraphWebSocket({ url: 'ws://mock/stream' }),
+ );
+ act(() => {
+ created[0].open();
+ });
+ act(() => {
+ created[0].emit(makeEnvelope(1));
+ created[0].emit(makeEnvelope(2));
+ });
+ expect(result.current.events).toHaveLength(2);
+
+ act(() => {
+ result.current.clear();
+ });
+ expect(result.current.events).toHaveLength(0);
+ expect(result.current.last).toBeNull();
+ });
+});
diff --git a/apps/web/src/hooks/useGraphWebSocket.ts b/apps/web/src/hooks/useGraphWebSocket.ts
new file mode 100644
index 000000000..b885a8c20
--- /dev/null
+++ b/apps/web/src/hooks/useGraphWebSocket.ts
@@ -0,0 +1,278 @@
+/**
+ * useGraphWebSocket — live tail of graph-mutation envelopes (T1.4 — v8.0).
+ *
+ * Opens a WebSocket against the API service's
+ * ``/api/v1/graph_ws/stream`` proxy (see
+ * ``services/api/app/api/v1/endpoints/graph_ws.py``), which in turn
+ * brokers a tenant-scoped feed from the ingest broadcaster at
+ * ``services/ingest/internal/graph_ws``. The hook owns three concerns
+ * the consuming component should never have to think about:
+ *
+ * 1. **Authentication.** Browsers cannot set ``Authorization``
+ * headers on a WebSocket open, so the hook reads the access
+ * token from ``localStorage[AUTH_TOKEN_KEY]`` (the same key
+ * ``services/api/app/api/v1/endpoints/graph_ws.py`` looks for as
+ * ``?token=…``) and appends it to the URL. ``getActiveTenantId``
+ * from ``@/lib/api`` is *not* sent — the proxy rebinds tenant_id
+ * from the resolved user server-side so a client cannot subscribe
+ * to another tenant by tampering with the URL.
+ *
+ * 2. **Reconnect with exponential backoff.** Capped at
+ * ``maxBackoffMs`` (default 15 s) and reset on a successful
+ * ``onopen``. Mirrors the cadence of
+ * :func:`useRealtimeChannel <lib/realtime.useRealtimeChannel>`
+ * so two simultaneous WS connections (insights + graph) don't
+ * thunder-herd the gateway when the network flaps.
+ *
+ * 3. **Bounded event history.** ``events`` accumulates the last
+ * ``historyLimit`` envelopes (default 200) in newest-first order,
+ * and ``last`` is the most recent. Consumers can render either:
+ * a Cytoscape live graph patches against ``last``, a debug panel
+ * walks ``events``.
+ *
+ * The hook is a no-op on the server (``typeof window === 'undefined'``)
+ * and when ``enabled`` is false — useful for SSR pages and tests that
+ * want to skip the upgrade entirely.
+ */
+
+'use client';
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { AUTH_TOKEN_KEY, getActiveTenantId } from '@/lib/api';
+
+/**
+ * Graph-update envelope shape, mirrored from
+ * ``services/ingest/internal/graph/writer.go::GraphUpdate``. The
+ * ``change_type`` is one of ``upsert_node`` | ``upsert_edge`` |
+ * ``delete_node`` | ``delete_edge`` (see ``schema.go``). All optional
+ * fields are populated based on the change_type.
+ */
+export interface GraphUpdateEnvelope {
+ entity_id: string;
+ change_type:
+ | 'upsert_node'
+ | 'upsert_edge'
+ | 'delete_node'
+ | 'delete_edge'
+ | string;
+ ts: string;
+ label?: string;
+ rel_type?: string;
+ from?: string;
+ to?: string;
+ properties?: Record<string, unknown>;
+ schema_version: string;
+ tenant_id?: string;
+}
+
+export type GraphWebSocketStatus =
+ | 'idle'
+ | 'connecting'
+ | 'open'
+ | 'closing'
+ | 'closed'
+ | 'error';
+
+export interface UseGraphWebSocketOptions {
+ /**
+ * Override the WebSocket URL. Used by tests to inject a mock socket
+ * server. In production the URL is derived from same-origin so
+ * Next.js can proxy the upgrade through to the API service.
+ */
+ url?: string;
+ /** When false, the hook never opens a socket. */
+ enabled?: boolean;
+ /** Override the bearer token. Defaults to the stored access token. */
+ token?: string | null;
+ /** Cap for the reconnect backoff (ms). Default 15s. */
+ maxBackoffMs?: number;
+ /** How many envelopes to retain in ``events``. Default 200. */
+ historyLimit?: number;
+}
+
+export interface UseGraphWebSocketResult {
+ /** Connection state machine — see :type:`GraphWebSocketStatus`. */
+ status: GraphWebSocketStatus;
+ /** Most recently received envelope, or ``null`` before the first. */
+ last: GraphUpdateEnvelope | null;
+ /** Newest-first list of envelopes, bounded by ``historyLimit``. */
+ events: GraphUpdateEnvelope[];
+ /** Drop accumulated history. Useful when switching views. */
+ clear: () => void;
+}
+
+const DEFAULT_HISTORY_LIMIT = 200;
+const DEFAULT_MAX_BACKOFF_MS = 15_000;
+
+/**
+ * Build the same-origin WS URL the API proxy listens on.
+ *
+ * Two reasons we don't reuse ``realtimeApi.channelUrl`` from
+ * ``@/lib/api``: (1) the realtime gateway is a separate service at
+ * ``/ws/<channel>`` while graph_ws is wired into the API service at
+ * ``/api/v1/graph_ws/stream``, and (2) Next.js rewrites
+ * (``next.config.js``) only proxy WS to a single backend per source,
+ * so the path matters.
+ *
+ * SSR fallback returns a path-only URL — nothing on the server opens
+ * a WebSocket, but we still want the function pure.
+ */
+function defaultGraphWsUrl(token: string | null): string {
+ let origin = '';
+ if (typeof window !== 'undefined') {
+ const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
+ origin = `${proto}//${window.location.host}`;
+ }
+ const path = '/api/v1/graph_ws/stream';
+ if (!token) return `${origin}${path}`;
+ return `${origin}${path}?token=${encodeURIComponent(token)}`;
+}
+
+function readStoredToken(): string | null {
+ if (typeof window === 'undefined') return null;
+ try {
+ return window.localStorage.getItem(AUTH_TOKEN_KEY);
+ } catch {
+ return null;
+ }
+}
+
+export function useGraphWebSocket(
+ options: UseGraphWebSocketOptions = {},
+): UseGraphWebSocketResult {
+ const {
+ url,
+ enabled = true,
+ token,
+ maxBackoffMs = DEFAULT_MAX_BACKOFF_MS,
+ historyLimit = DEFAULT_HISTORY_LIMIT,
+ } = options;
+
+ const [status, setStatus] = useState<GraphWebSocketStatus>('idle');
+ const [last, setLast] = useState<GraphUpdateEnvelope | null>(null);
+ const [events, setEvents] = useState<GraphUpdateEnvelope[]>([]);
+
+ const socketRef = useRef<WebSocket | null>(null);
+ const attemptRef = useRef(0);
+ const cancelledRef = useRef(false);
+ const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const clear = useCallback(() => {
+ setLast(null);
+ setEvents([]);
+ }, []);
+
+ useEffect(() => {
+ if (!enabled || typeof window === 'undefined') {
+ setStatus('idle');
+ return;
+ }
+
+ cancelledRef.current = false;
+
+ // Pin the tenant_id we *think* we are in for diagnostic logs. The
+ // proxy rebinds server-side so this value is purely advisory — it
+ // never controls authorisation. Touch the helper so a linter
+ // doesn't flag the import; the read also catches a regression
+ // where some future change starts trusting it for routing.
+ void getActiveTenantId();
+
+ const resolvedToken = token === undefined ? readStoredToken() : token;
+ const target = url ?? defaultGraphWsUrl(resolvedToken);
+
+ function connect() {
+ if (cancelledRef.current) return;
+ setStatus('connecting');
+
+ let ws: WebSocket;
+ try {
+ ws = new WebSocket(target);
+ } catch {
+ // Some browsers throw synchronously on invalid URLs; treat
+ // that as a hard error and schedule a reconnect.
+ setStatus('error');
+ scheduleReconnect();
+ return;
+ }
+ socketRef.current = ws;
+
+ ws.onopen = () => {
+ attemptRef.current = 0;
+ setStatus('open');
+ };
+
+ ws.onmessage = (event) => {
+ if (typeof event.data !== 'string') return;
+ let payload: GraphUpdateEnvelope | null = null;
+ try {
+ payload = JSON.parse(event.data) as GraphUpdateEnvelope;
+ } catch {
+ // Drop non-JSON / malformed frames — the broadcaster only
+ // ever sends JSON envelopes, so any garbage here is a bug
+ // and we don't want it to poison the consumer.
+ return;
+ }
+ if (!payload || typeof payload !== 'object') return;
+ setLast(payload);
+ setEvents((prev) => {
+ const next = [payload as GraphUpdateEnvelope, ...prev];
+ return next.length > historyLimit ? next.slice(0, historyLimit) : next;
+ });
+ };
+
+ ws.onerror = () => setStatus('error');
+
+ ws.onclose = () => {
+ socketRef.current = null;
+ if (cancelledRef.current) {
+ setStatus('closed');
+ return;
+ }
+ setStatus('closed');
+ scheduleReconnect();
+ };
+ }
+
+ function scheduleReconnect() {
+ if (cancelledRef.current) return;
+ const attempt = attemptRef.current + 1;
+ attemptRef.current = attempt;
+ // Exponential backoff: 1s → 2s → 4s → … → maxBackoffMs.
+ // Cap the exponent so very long-lived disconnect loops don't
+ // overflow the math.
+ const exp = Math.min(attempt, 6);
+ const delay = Math.min(1000 * 2 ** exp, maxBackoffMs);
+ reconnectTimerRef.current = setTimeout(connect, delay);
+ }
+
+ connect();
+
+ return () => {
+ cancelledRef.current = true;
+ if (reconnectTimerRef.current) {
+ clearTimeout(reconnectTimerRef.current);
+ reconnectTimerRef.current = null;
+ }
+ const ws = socketRef.current;
+ socketRef.current = null;
+ if (ws) {
+ if (ws.readyState === WebSocket.OPEN) {
+ setStatus('closing');
+ }
+ try {
+ ws.close();
+ } catch {
+ /* ignore — close errors don't matter on teardown */
+ }
+ }
+ };
+ }, [enabled, url, token, maxBackoffMs, historyLimit]);
+
+ return { status, last, events, clear };
+}
+
+export const __testables = {
+ defaultGraphWsUrl,
+ readStoredToken,
+};
diff --git a/apps/web/src/lib/blog.ts b/apps/web/src/lib/blog.ts
index eebf7bab1..28273dae5 100644
--- a/apps/web/src/lib/blog.ts
+++ b/apps/web/src/lib/blog.ts
@@ -64,28 +64,8 @@ function estimateReadingMinutes(body: string): number {
return Math.max(1, Math.round(words / WORDS_PER_MINUTE));
}
-// Slugs are derived from filenames on disk and flow into both URL paths
-// (`/blog/${slug}`) and HTML attributes (`<Link href>`). Even though only
-// maintainers can add files to `content/blog/`, we enforce a strict
-// kebab-case alphanumeric shape so a malicious or typo'd filename can
-// never produce HTML/JS-injecting URL segments. Doubles as a CodeQL
-// sanitizer for the `js/stored-xss` taint flow.
-const SAFE_SLUG = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u;
-
-function assertSafeSlug(slug: string, filename: string): void {
- if (!SAFE_SLUG.test(slug)) {
- throw new Error(
- `Blog post filename "${filename}" produces an unsafe slug "${slug}". ` +
- `Slugs must match ${SAFE_SLUG.source}.`,
- );
- }
-}
-
function parseFile(filename: string): BlogPost {
- const rawSlug = filename.replace(/\.(mdx|md)$/u, '');
- assertSafeSlug(rawSlug, filename);
- // After validation, ``slug`` is known to be safe URL-segment text.
- const slug: string = rawSlug;
+ const slug = filename.replace(/\.(mdx|md)$/u, '');
const raw = fs.readFileSync(path.join(CONTENT_DIR, filename), 'utf8');
const { data, content } = matter(raw);
const fm = data as BlogFrontmatter;
diff --git a/apps/web/src/lib/customers.ts b/apps/web/src/lib/customers.ts
index ecfd49af6..225262b75 100644
--- a/apps/web/src/lib/customers.ts
+++ b/apps/web/src/lib/customers.ts
@@ -74,27 +74,8 @@ function readDir(): string[] {
.filter((name) => name.endsWith('.mdx') || name.endsWith('.md'));
}
-// Slugs flow from filenames into `/customers/${slug}` URLs and `<Link href>`
-// attributes. Even though only maintainers can land files in
-// `content/customers/`, we enforce a strict kebab-case alphanumeric shape
-// so a malicious or typo'd filename can never produce
-// HTML/JS-injecting URL segments. Doubles as a CodeQL sanitizer for the
-// `js/stored-xss` taint flow.
-const SAFE_SLUG = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u;
-
-function assertSafeSlug(slug: string, filename: string): void {
- if (!SAFE_SLUG.test(slug)) {
- throw new Error(
- `Customer study filename "${filename}" produces an unsafe slug "${slug}". ` +
- `Slugs must match ${SAFE_SLUG.source}.`,
- );
- }
-}
-
function parseFile(filename: string): CustomerStudy {
- const rawSlug = filename.replace(/\.(mdx|md)$/u, '');
- assertSafeSlug(rawSlug, filename);
- const slug: string = rawSlug;
+ const slug = filename.replace(/\.(mdx|md)$/u, '');
const raw = fs.readFileSync(path.join(CONTENT_DIR, filename), 'utf8');
const { data, content } = matter(raw);
// gray-matter returns `data` as a generic object; we trust the file author
diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts
new file mode 100644
index 000000000..37661aae3
--- /dev/null
+++ b/apps/web/src/lib/utils.ts
@@ -0,0 +1,15 @@
+import { type ClassValue, clsx } from 'clsx';
+import { twMerge } from 'tailwind-merge';
+
+/**
+ * Compose Tailwind classes safely: `clsx` resolves conditional inputs and
+ * `tailwind-merge` collapses conflicts (e.g. `px-4` later replacing `px-2`).
+ *
+ * Aceternity UI, MagicUI, and shadcn/ui-style primitives all expect a `cn`
+ * helper at `@/lib/utils`; this is the single source of truth so the copied
+ * source files in `apps/web/src/components/{aceternity,magicui}/` can import
+ * it without each shipping its own merge implementation.
+ */
+export function cn(...inputs: ClassValue[]): string {
+ return twMerge(clsx(inputs));
+}
diff --git a/apps/web/tailwind.config.ts b/apps/web/tailwind.config.ts
index 875115bc0..5f16dc651 100644
--- a/apps/web/tailwind.config.ts
+++ b/apps/web/tailwind.config.ts
@@ -78,6 +78,30 @@ const config: Config = {
dead: '#ef4444',
idle: '#64748b',
},
+ // Marketing-landing accents (T6.5). Strictly additive — these live in
+ // a `landing.*` namespace so they cannot collide with the console
+ // palette and only appear on `apps/web/src/components/landing/`
+ // surfaces. Mirrors `docs/design/landing-page-design-tokens.md` §2.3.
+ landing: {
+ accent: {
+ ember: '#f97316',
+ violet: '#8b5cf6',
+ },
+ },
+ },
+ backgroundImage: {
+ // Three brand-tinted gradients used by the landing page only. Resolve
+ // to CSS variables defined in `globals.css` so a future light-mode
+ // landing variant can flip the stops without touching components.
+ 'landing-grad-hero': 'var(--landing-grad-hero)',
+ 'landing-grad-pillars': 'var(--landing-grad-pillars)',
+ 'landing-grad-cta': 'var(--landing-grad-cta)',
+ },
+ transitionTimingFunction: {
+ // Easing tokens from `docs/design/landing-page-design-tokens.md` §7.1.
+ 'landing-out-expo': 'cubic-bezier(0.16, 1, 0.3, 1)',
+ 'landing-out-quart': 'cubic-bezier(0.25, 1, 0.5, 1)',
+ 'landing-in-out-quad': 'cubic-bezier(0.45, 0, 0.55, 1)',
},
fontFamily: {
sans: ['var(--font-inter)', 'system-ui', 'sans-serif'],
diff --git a/docker-compose.demo.yml b/docker-compose.demo.yml
index 41d894ee3..bc3ac8a44 100644
--- a/docker-compose.demo.yml
+++ b/docker-compose.demo.yml
@@ -47,8 +47,11 @@ services:
POSTGRES_DB: aisoc
POSTGRES_USER: aisoc
POSTGRES_PASSWORD: aisoc_dev_secret
+ # Host port is overridable so `pnpm aisoc:demo` can fall forward to the
+ # next free port when a local Postgres is already bound to 5432. The
+ # container port stays at 5432; only the publish side changes.
ports:
- - "127.0.0.1:5432:5432"
+ - "127.0.0.1:${AISOC_POSTGRES_PORT:-5432}:5432"
volumes:
- postgres_demo_data:/var/lib/postgresql/data
networks:
@@ -64,7 +67,7 @@ services:
container_name: aisoc-demo-redis
command: redis-server --appendonly yes --requirepass redis_dev_secret
ports:
- - "127.0.0.1:6379:6379"
+ - "127.0.0.1:${AISOC_REDIS_PORT:-6379}:6379"
volumes:
- redis_demo_data:/data
networks:
@@ -96,7 +99,7 @@ services:
zookeeper:
condition: service_healthy
ports:
- - "127.0.0.1:9092:9092"
+ - "127.0.0.1:${AISOC_KAFKA_PORT:-9092}:9092"
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
@@ -139,7 +142,7 @@ services:
kafka:
condition: service_healthy
ports:
- - "127.0.0.1:8000:8000"
+ - "127.0.0.1:${AISOC_API_PORT:-8000}:8000"
environment:
DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_dev_secret@postgres:5432/aisoc
REDIS_URL: redis://:redis_dev_secret@redis:6379/0
@@ -148,7 +151,10 @@ services:
ENV: development
ENVIRONMENT: development
LOG_LEVEL: info
- CORS_ORIGINS: http://localhost:3000
+ # Browser → api CORS origin tracks the web host port so a fallback
+ # publish (e.g. 3001) still passes the api's CORS preflight when a
+ # caller hits the api directly.
+ CORS_ORIGINS: http://localhost:${AISOC_WEB_PORT:-3000}
# The agents service listens on port 8084 inside the Docker network
# (see its Dockerfile + the agents service block below). Without this
# the api defaults to `http://agents:8000` and every playbook / case
@@ -176,7 +182,7 @@ services:
redis:
condition: service_healthy
ports:
- - "127.0.0.1:8001:8084"
+ - "127.0.0.1:${AISOC_AGENTS_PORT:-8001}:8084"
environment:
DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_dev_secret@postgres:5432/aisoc
REDIS_URL: redis://:redis_dev_secret@redis:6379/4
@@ -201,7 +207,7 @@ services:
kafka:
condition: service_healthy
ports:
- - "127.0.0.1:8086:4000"
+ - "127.0.0.1:${AISOC_REALTIME_PORT:-8086}:4000"
environment:
KAFKA_BOOTSTRAP_SERVERS: kafka:29092
REDIS_URL: redis://:redis_dev_secret@redis:6379
@@ -281,7 +287,7 @@ services:
- agents
- realtime
ports:
- - "127.0.0.1:3000:3000"
+ - "127.0.0.1:${AISOC_WEB_PORT:-3000}:3000"
environment:
# Server-side rewrite targets (used by the Next.js Node process).
# These never reach the browser — only the proxy layer in next.config.js.
diff --git a/docs/design/README.md b/docs/design/README.md
index ca9639452..c09e71db3 100644
--- a/docs/design/README.md
+++ b/docs/design/README.md
@@ -1,7 +1,7 @@
# `docs/design/` — landing page kickoff bundle
This folder is the design-team handoff for the AiSOC marketing landing
-page on `aisoc.dev`. Three documents, in order of importance:
+page on `aisoc.dev`. Six documents, in order of importance:
1. **`landing-page-brief.md`** — the product brief. Seventeen sections,
from positioning and personas through information architecture,
@@ -17,6 +17,19 @@ page on `aisoc.dev`. Three documents, in order of importance:
infrastructure, observability), each tagged with "what to steal"
and "what to avoid." Per project rule, no SOC-competitor product is
named.
+4. **`landing-page-design-tokens.md`** — copy-paste-ready token spec.
+ Surfaces, foregrounds, brand, gradients, type scale, spacing, radius,
+ elevation, motion durations / easings, iconography, imagery, banned
+ tokens. Resolves every magic number to a Tailwind class or CSS
+ variable.
+5. **`landing-page-component-recipes.md`** — one recipe per IA section
+ (`nav` → `footer`). Names the Aceternity / MagicUI primitives to
+ use, the React anatomy to build, the prop tweaks needed, the failure
+ modes to handle, and the responsive states.
+6. **`landing-page-motion-spec.md`** — the choreography table. Twelve
+ distinct micro-animations with trigger, duration, easing, stagger,
+ and `prefers-reduced-motion` fallback per row. The single source of
+ truth for any motion landing on the page.
## Owner
diff --git a/docs/design/landing-page-component-recipes.md b/docs/design/landing-page-component-recipes.md
new file mode 100644
index 000000000..95c91b98c
--- /dev/null
+++ b/docs/design/landing-page-component-recipes.md
@@ -0,0 +1,239 @@
+# AiSOC landing page — component recipes
+
+> Companion to `landing-page-brief.md` §6 and
+> `landing-page-design-tokens.md`. One recipe per IA section, in the
+> same order with the same ID. The frontend engineer (Subagent F) reads
+> this while implementing `apps/web/src/app/(marketing)/page.tsx`.
+>
+> **Library catalog:**
+> - Aceternity UI — `https://ui.aceternity.com/components`
+> - MagicUI — `https://magicui.design/docs/components`
+>
+> Each recipe lists primitives (with prop overrides), custom touches,
+> anatomy (sub-components), states, and failure modes.
+
+---
+
+## §1 — `nav` (Sticky nav)
+
+- **Primitives:**
+ - Aceternity **Floating Navbar** (`/components/floating-navbar`) — base shell. Override `hideOnScroll={false}`. Glass via `backdrop-blur-md` + `bg-surface-base/70`.
+ - MagicUI **Number Ticker** (`/docs/components/number-ticker`) — live GitHub star chip. `value={liveStars}`, `direction="up"`, `delay={0.4}`.
+ - MagicUI **Shimmer Button** (`/docs/components/shimmer-button`) — primary CTA. `shimmerColor="var(--color-brand-300)"`, `background="linear-gradient(110deg,var(--color-brand-600) 45%,var(--color-brand-500) 55%)"`.
+- **Custom:** Existing `<Wordmark />` from `apps/web/src/components/brand/`. Border-bottom appears via `data-scrolled="true"` set by an `IntersectionObserver` on a hero sentinel.
+- **Anatomy:** `LandingNav` → `NavLogo`, `NavLinks`, `NavStarChip`, `NavCtas`, `NavMobileSheet`.
+- **States:** Default `bg-surface-base/70`; on-scroll `bg-surface-base/90 border-b-surface-border`. <768 → logo + chip + hamburger. Reduced-motion drops shimmer.
+- **Failure:** Star API → static "Star on GitHub" pill. JS off → static `<header>` + anchors. Hamburger fails → `<details>` fallback.
+
+---
+
+## §2 — `hero`
+
+- **Primitives:**
+ - Aceternity **Spotlight** (`/components/spotlight`) — corner glow. `fill="var(--color-brand-500)"`, top-right at 40% / 20%.
+ - Aceternity **Text Generate Effect** (`/components/text-generate-effect`) — H1. `words="Detect. Triage. Hunt. Respond."`, `duration={0.8}`, `filter={false}` (blur unreadable at 56–64 px).
+ - MagicUI **AnimatedGridPattern** (`/docs/components/animated-grid-pattern`) — bg mesh. `numSquares={48}`, `maxOpacity={0.08}`, `duration={3}`, `repeatDelay={1}`. Mask 70%-radius radial fade.
+ - MagicUI **Border Beam** (`/docs/components/border-beam`) — frame around hero visual. `size={250}`, `duration={12}`, `colorFrom="#3b82f6"`, `colorTo="#8b5cf6"`.
+ - MagicUI **Shimmer Button** — primary CTA (same as nav).
+- **Custom:** Right-column visual is a hand-built SVG of the four-agent topology rendered with framer-motion `<motion.path>` (motion spec `agent-beam`). Eyebrow uses `<Eyebrow />` chip with `bg-brand-900/40 text-brand-300 border-brand-500/20`.
+- **Anatomy:** `Hero` → `HeroCopy` (eyebrow, H1, sub-head, CTAs, social-proof), `HeroVisual` (SVG topology + Border Beam), `HeroBackground` (Spotlight + AnimatedGridPattern).
+- **States:** Visual right at `lg+`, stacked at `<lg`; auto-pauses motion at `<md`. Hover primary CTA shimmer slow-loops; secondary CTA border `surface-border → brand-500`. Reduced-motion: H1 instant; mesh static; Border Beam → 1 px static `brand-500/30`.
+- **Failure:** Spotlight fails → inline `radial-gradient`. Mesh fails → flat `bg-surface-base`. SVG fails → `<img src="/og.png" />` poster.
+
+---
+
+## §3 — `proof-strip`
+
+- **Primitives:**
+ - MagicUI **Marquee** (`/docs/components/marquee`) — logos. `pauseOnHover={true}`, `vertical={false}`, `repeat={4}`, `className="[--duration:40s]"`. L → R.
+ - Aceternity **Sparkles** (`/components/sparkles`) — *optional*, soft particles. Skip first ship.
+- **Custom:** Logos at `apps/web/public/logos/oss/{langgraph,kafka,neo4j,postgresql,qdrant,ollama}.svg`. Default `fill="currentColor"` + `text-fg-muted`; hover restores per-logo brand colour. Design partners block: 4 placeholder outlines + caption from content doc.
+- **Anatomy:** `ProofStrip` → `ProofStripLabel`, `ProofStripLogos` (Marquee), `ProofStripPartners`.
+- **States:** Auto-plays; pauses on hover. Phone — two rows. Reduced-motion → static centred 3 × 2 grid.
+- **Failure:** Marquee fails → static row. Logo 404 → 24 × 96 px `bg-surface-card` placeholder.
+
+---
+
+## §4 — `problem`
+
+- **Primitives:**
+ - Aceternity **Hero Highlight** (`/components/hero-highlight`) — wrap H2 to highlight "drowning". `highlightClassName="bg-brand-500/15 px-2 rounded-md"`.
+ - MagicUI **Animated List** (`/docs/components/animated-list`) — three pain bullets, `delay={400}`. Each (icon + headline + body) animates as one unit.
+- **Custom:** Three line-art SVGs at `apps/web/public/glyphs/problem-{1,2,3}.svg`, 56 × 56 px, 1.75 px stroke. Stat callouts use `<mark>` styled `text-brand-300 bg-transparent`.
+- **Anatomy:** `Problem` → `ProblemHeading`, `ProblemBullets` (Animated List of `ProblemBullet`).
+- **States:** 3-column → 1-column at <768. Hover icon → stroke flips `brand.300`. Reduced-motion → flat reveal.
+- **Failure:** Hero Highlight fails → flat `bg-brand-500/15` span. Glyph 404 → `<span aria-hidden>•</span>`.
+
+---
+
+## §5 — `solution`
+
+- **Primitives:**
+ - MagicUI **Animated Beam** (`/docs/components/animated-beam`) — connect four agent cards L → R (Detect → Triage → Hunt → Respond). Three beams. `duration={3}`, `pathColor="rgba(148,163,184,0.15)"`, `gradientStartColor="#3b82f6"`, `gradientStopColor="#8b5cf6"`, `curvature={-30}`.
+ - Aceternity **Bento Grid** (`/components/bento-grid`) — alternate layout for `lg+`. First ship: flat 4-up flex row.
+ - Aceternity **Card Hover Effect** (`/components/card-hover-effect`) — agent cards. Override stagger off; hover `bg-brand-500/8` + `border-brand-500/30`.
+- **Custom:** 24 × 24 SVG glyph per card at `apps/web/public/glyphs/agents/{detect,triage,hunt,respond}.svg`. Animated Beam parent wraps `forwardRef` divs; Subagent F adds a `<BeamAnchor ref={...} />` helper.
+- **Anatomy:** `Solution` → `SolutionHeading`, `SolutionDiagram` (4 × `BeamAnchor` + 3 × `<AnimatedBeam>`), 4 × `SolutionAgentCard`.
+- **States:** Beams loop; cards lift `-2 px` with `landing.shadow.2`. <1024 → vertical stack, beams hidden, agent cards 2 × 2 (<768) or stacked (<640). Reduced-motion → beams swap to static SVG.
+- **Failure:** Animated Beam fails → static SVG fallback path. Card Hover fails → plain Tailwind transition lift.
+
+---
+
+## §6 — `demo`
+
+- **Primitives:**
+ - MagicUI **Border Beam** — frame. `duration={10}`, `colorFrom="#3b82f6"`, `colorTo="#8b5cf6"`, `borderWidth={1.5}`.
+ - Aceternity **Container Scroll Animation** (`/components/container-scroll-animation`) — *optional*, tilts demo on scroll. `titleComponent={null}`. Skip first ship if it bloats bundle.
+ - Aceternity **Spotlight** — soft glow. Reuse hero with `fill="var(--color-brand-700)"`.
+- **Custom:** 90-second muted video at `apps/web/public/demo/inc-rt-001.mp4` + Vimeo fallback. Caption overlay (`INC-RT-001 · LockBit 3.0 · step 14 of 32`) is an absolutely-positioned `<div>`. Lazy-load via `IntersectionObserver` once 30% in viewport. Poster at `apps/web/public/demo/inc-rt-001-poster.avif`.
+- **Anatomy:** `Demo` → `DemoHeading`, `DemoFrame` (Border Beam wraps `<video>`), `DemoCaptionOverlay`, `DemoCta`.
+- **States:** Autoplay muted, loop, inline. Hover → caption + scrub controls. <768 controls always visible. Reduced-motion → freezes on poster, "Play replay" button centred.
+- **Failure:** `<video>` fails → poster + "Watch on Vimeo" link. Border Beam fails → static `brand-500/30` border. Vimeo blocked → CTA changes to "Run this yourself."
+
+---
+
+## §7 — `pillars`
+
+- **Primitives:**
+ - Aceternity **Glowing Effect** (`/components/glowing-effect`) — wraps each card border. `glow={true}`, `proximity={64}`, `inactiveZone={0.4}`.
+ - Aceternity **Bento Grid** — used loosely (flat 2 × 2, equal heights, no skew).
+ - MagicUI **Number Ticker** — stat lines. P1 `value={6998}`, P2 `value={17}`, P3 `value={4}`, P4 `value={6}`.
+- **Custom:** 24 × 24 brand glyphs (`open-source`, `graph`, `agentic`, `deploy-anywhere`). Active borders: P2 → `landing.gradient.pillars`, P3 → `landing.accent.ember`, P1 / P4 → `brand-500/30`.
+- **Anatomy:** `Pillars` → `PillarsHeading`, `PillarsGrid` (4 × `PillarCard`), each → `PillarIcon`, `PillarTitle`, `PillarBody`, `PillarStat`, `PillarLink`.
+- **States:** Default `landing.shadow.1`, `surface-border`. Hover → Glowing Effect on; lift `-2 px`. Focus → existing `:focus-visible` 2 px `brand-500` ring. <768 stacks. Reduced-motion → Glowing `disabled={true}`; lift instant.
+- **Failure:** Glowing fails → static `brand-500/20` border. Number Ticker fails → static formatted string.
+
+---
+
+## §8 — `features` (Detect & Investigate · Hunt & Respond · Operate at scale)
+
+Three sub-section bands with anchor IDs `features-detect`,
+`features-hunt`, `features-operate`.
+
+- **Primitives:**
+ - Aceternity **Tabs** (`/components/tabs`) — *optional*, switch between bands on `lg+`. Safer first ship: render all three sequentially.
+ - Aceternity **Card Hover Effect** — 6 tiles per band. Subtle, no scale; bg shift only.
+- **Custom:** Tile icons from Lucide (`shield-alert`, `users`, `book-open`, `clock`, `git-branch`, `key-round`, …) sized 24, stroke 1.75. Body links resolve to `apps/docs/` URLs.
+- **Anatomy:** `Features` → `FeaturesHeading`, 3 × `FeaturesBand`; each → `FeaturesBandHeading` + `FeaturesGrid` (6 × `FeatureTile`).
+- **States:** 3-up at `lg+`, 2-up at `md`, 1-up at `sm`. Hover → `bg-surface-hover`; link icon translates `+2 px` right. Reduced-motion → translation off.
+- **Failure:** Lucide import fails → tile renders without icon. Doc link 404 → `cursor-default`, no-op.
+
+---
+
+## §9 — `connectors`
+
+- **Primitives:**
+ - MagicUI **Marquee** — two rows, second reversed. `pauseOnHover={true}`, `repeat={3}`, row 1 `[--duration:60s]`, row 2 `[--duration:75s]`.
+ - MagicUI **Particles** (`/docs/components/particles`) — *optional*, drift behind logos. Skip if performance budget tightens.
+ - Aceternity **Code Block** (`/components/code-block`) — connector callout. `language="python"`, `filename="my_connector.py"`, `highlightLines={[7,8,9,10,11]}`.
+- **Custom:** Category chips use existing `<ChipGroup>`; filter is in-page `useState`. Below 640 px, render 18 logos + "See all 69 →" link.
+- **Anatomy:** `Connectors` → `ConnectorsHeading`, `ConnectorsCategoryChips`, `ConnectorsMarquee`, `ConnectorsCodeCallout`.
+- **States:** Marquees loop; chip filter → `opacity-30` on non-matching logos. Reduced-motion → static 5-col grid (first 30 logos). Phone → chips horizontal-scroll; marquee disabled in favour of 18-logo grid.
+- **Failure:** Marquee fails → static grid. Logo 404 → 24 × 96 px placeholder. Code Block fails → plain `<pre>`.
+
+---
+
+## §10 — `benchmark`
+
+- **Primitives:**
+ - MagicUI **Number Ticker** — three big numbers. Tile 1 `value={97.0}` `decimalPlaces={1}`; tile 2 literal "Sub-minute"; tile 3 `value={35}`.
+ - Aceternity **Lamp Effect** (`/components/lamp-effect`) — *optional* section header. Skip first ship.
+ - Aceternity **Animated Tooltip** (`/components/animated-tooltip`) — each tile hovers a tooltip naming the suite (`test_mitre_accuracy`, `wet_eval_target`, `test_substrate_runtime`).
+- **Custom:** Each label includes `(substrate)` or `(wet-eval)` per `AGENTS.md`.
+- **Anatomy:** `Benchmark` → `BenchmarkHeading`, `BenchmarkTiles` (3 × `BenchmarkTile`), each → `BenchmarkMetric`, `BenchmarkCaption`, `BenchmarkTooltip`.
+- **States:** 3-column. Tooltip 200 ms delay. Reduced-motion → final value direct.
+- **Failure:** Number Ticker fails → static string. Tooltip fails → label inline below metric.
+
+---
+
+## §11 — `deploy`
+
+- **Primitives:**
+ - Aceternity **Card Hover Effect** — three deploy cards. Middle card has `landing.gradient.cta` 8% overlay.
+ - Aceternity **Glowing Effect** — middle card only.
+ - MagicUI **Border Beam** — middle card border. `duration={14}`, `colorFrom="#3b82f6"`, `colorTo="#8b5cf6"`.
+- **Custom:** Card titles carry Lucide icons (`cloud`, `terminal`, `lock`). "Time to live" line uses `mono.sm`.
+- **Anatomy:** `Deploy` → `DeployHeading`, `DeployGrid` (3 × `DeployCard`), each → `DeployCardIcon`, `DeployCardTitle`, `DeployCardMeta`, `DeployCardBody`, `DeployCardCta`.
+- **States:** Three equal cards; middle brighter. Hover → Glowing on middle; outer cards lift only. <1024 stacks. Reduced-motion → Border Beam static.
+- **Failure:** All primitives fail → 1 px `surface-border`; recommended card carries `bg-brand-500/8`.
+
+---
+
+## §12 — `open-source`
+
+- **Primitives:**
+ - Aceternity **Code Block** — `git clone … && pnpm aisoc:demo`. `language="bash"`, `filename="terminal"`, `theme="dark"`.
+ - MagicUI **Number Ticker** — repo card star count.
+ - Aceternity **Sparkles** — *optional* behind H2. Skip if it competes with §3.
+- **Custom:** Repo card mirrors GitHub's repo card in `surface-card` with brand-tinted hover. Octocat from `apps/web/public/glyphs/octocat.svg`, brand-tinted via CSS filter.
+- **Anatomy:** `OpenSource` → `OpenSourceHeading`, `OpenSourceRepoCard`, `OpenSourceCodeSnippet`, `OpenSourceCtas`.
+- **States:** 2-column at `lg+` (repo left, code right); stacks at `md`. Hover repo → border `brand-500/40`. Reduced-motion → Sparkles off, ticker static.
+- **Failure:** Star API fails → static "★ Star on GitHub" pill. Code Block fails → `<pre>`. Octocat 404 → SVG placeholder.
+
+---
+
+## §13 — `testimonials`
+
+- **Primitives:**
+ - Aceternity **Animated Testimonials** (`/components/animated-testimonials`) — once ≥ 2 published. `autoplay={true}`, `pauseOnHover={true}`.
+ - Aceternity **Card Stack** (`/components/card-stack`) — alternative layout; pick whichever performs better in QA.
+ - **Empty-state pattern** for v1 (likely first ship): single `surface-card` block with copy from content doc + "Become a reference partner" CTA. **No fake testimonials, no placeholder logos.**
+- **Custom:** Industry chip uses existing `<Chip>` with brand-tinted bg.
+- **Anatomy:** `Testimonials` → `TestimonialsHeading`, `TestimonialsCarousel` (gated on `published.length >= 2`) **or** `TestimonialsEmptyState`.
+- **States:** Carousel autoplays 1 / 6 s; pauses on hover. <768 single card visible, swipe enabled. Reduced-motion → autoplay off, manual arrows visible.
+- **Failure:** MDX fetch fails → empty state. Animated Testimonials fails → static `react-snap-carousel` fallback (existing dep).
+
+---
+
+## §14 — `pricing-teaser`
+
+- **Primitives:**
+ - Aceternity **Card Hover Effect** — three pricing cards.
+ - Aceternity **Glowing Effect** — middle card (Team) only.
+ - MagicUI **Border Beam** — middle card border.
+- **Custom:** `<TierBadge>` (Free / Managed / Enterprise) top-left; explicit "Includes everything in {previous tier}" line.
+- **Anatomy:** `PricingTeaser` → `PricingHeading`, `PricingGrid` (3 × `PricingCard`), each → `PricingTierBadge`, `PricingTitle`, `PricingPrice`, `PricingTagline`, `PricingIncludes`, `PricingCta`.
+- **States:** Three equal cards. Hover middle → Glowing on. <1024 stacks. Reduced-motion → Border Beam static.
+- **Failure:** All primitives fail → plain border + `bg-brand-500/8` on Team.
+
+---
+
+## §15 — `faq`
+
+- **Primitives:**
+ - **Radix Accordion** (existing at `apps/web/src/components/ui/accordion.tsx`) — `type="multiple"`, `defaultValue={['faq-q1','faq-q2']}`.
+ - Aceternity **Tracing Beam** (`/components/tracing-beam`) — *optional* left-edge beam. Skip first ship.
+- **Custom:** Each question carries `id={faq-q{n}}` for analytics. Answers may include `<code>`; respect mono token.
+- **Anatomy:** `Faq` → `FaqHeading`, `FaqAccordion` (Radix), each → `FaqQuestion`, `FaqAnswer`.
+- **States:** First two open. Click toggles Radix's 200 ms slide. Keyboard `Enter` / `Space` toggles, `Tab` traverses. Reduced-motion → instant open.
+- **Failure:** Radix fails → fallback `<details>` with first two `default open`.
+
+---
+
+## §16 — `final-cta`
+
+- **Primitives:**
+ - Aceternity **Wavy Background** (`/components/wavy-background`) — full-bleed panel. `colors={["#1d4ed8","#3b82f6","#8b5cf6"]}`, `waveOpacity={0.3}`, `speed="slow"`, `blur={10}`.
+ - MagicUI **Shimmer Button** — primary CTA only.
+ - Aceternity **Background Boxes** (`/components/background-boxes`) — *alternative*. **Pick one** of Wavy or Boxes; do not stack.
+- **Custom:** Microcopy uses `body.sm` + `fg.muted`; `·` separator rendered as `<span aria-hidden>·</span>`.
+- **Anatomy:** `FinalCta` → `FinalCtaPanel` (Wavy or Boxes), `FinalCtaHeading`, `FinalCtaButtons`, `FinalCtaMicrocopy`.
+- **States:** Wavy animates slowly. Hover primary → shimmer accelerates. <600 buttons stack. Reduced-motion → Wavy frame 0; secondary CTA gains `border-brand-500/40` for balance.
+- **Failure:** Wavy fails → static `landing.gradient.cta`. Shimmer Button fails → solid `brand.500`.
+
+---
+
+## §17 — `footer`
+
+- **Primitives:**
+ - **No animated primitives.** Footer is intentionally calm.
+ - MagicUI **Dot Pattern** (`/docs/components/dot-pattern`) — *optional* dotted bg. `cy={1}`, `cr={1}`, `className="[mask-image:radial-gradient(ellipse_at_top,white,transparent_70%)] opacity-40"`.
+- **Custom:** Five-column grid; bottom row carries copyright, social icons (Lucide `github`, `twitter`, custom Discord glyph), language switcher (English-only v1, dropdown disabled).
+- **Anatomy:** `Footer` → `FooterColumns` (5 × `FooterColumn`), `FooterBottom` (`FooterCopyright`, `FooterSocial`, `FooterLangSwitcher`, `FooterStatusDot`).
+- **States:** Desktop grid, `surface-subtle` bg. Hover link → `text-fg-primary` (was `fg-secondary`). <768 columns collapse into `<details>`. Status dot pulses every 2 s via `.pulse-dot`.
+- **Failure:** Dot Pattern fails → flat `bg-surface-subtle`. Status fetch fails → static dot in `status.idle`.
+
+---
+
+*End of recipes. Pair with `landing-page-design-tokens.md` and
+`landing-page-motion-spec.md`.*
diff --git a/docs/design/landing-page-design-tokens.md b/docs/design/landing-page-design-tokens.md
new file mode 100644
index 000000000..383d9bf30
--- /dev/null
+++ b/docs/design/landing-page-design-tokens.md
@@ -0,0 +1,314 @@
+# AiSOC landing page — design tokens
+
+> Companion to `landing-page-brief.md` §7. Copy-paste-ready token spec
+> for the frontend engineer implementing
+> `apps/web/src/app/(marketing)/page.tsx`. Every value resolves to a
+> Tailwind class or CSS variable — no magic numbers in component code.
+
+---
+
+## 1. Source of truth
+
+`apps/web/src/app/globals.css` and `apps/web/tailwind.config.ts` are
+authoritative. Conflicts resolve in favour of existing tokens unless
+explicitly overridden below.
+
+| Layer | Behaviour |
+|----------------------|------------------------------------------------------------------------|
+| Existing CSS vars | Reuse verbatim (`--surface-base`, `--fg-primary`, …). |
+| Existing Tailwind | Reuse `brand.*`, `surface.*`, `fg.*`, `severity.*`. Do not redefine. |
+| New marketing tokens | Add under `landing.*` namespace. Never collide. |
+| Severity tokens | Off-limits to marketing copy. Product screenshots only. |
+
+**Explicit overrides (this doc wins):**
+
+1. New gradient pairs `landing.gradient.{hero,pillars,cta}`.
+2. New elevation scale `landing.shadow.{1..4}` — additive.
+3. New motion tokens `landing.duration.*`, `landing.ease.*`, `landing.stagger.cards`.
+4. Light-mode landing deferred to v1.1; route is dark-locked
+ (`<html data-theme="dark">`, matching `apps/web/src/app/page.tsx`).
+
+---
+
+## 2. Color tokens
+
+### 2.1 Surface scale (dark — locked v1)
+
+| Token | Hex / value | OKLCH | Use |
+|--------------------|--------------------------|--------------------------|------------------------------------|
+| `surface.base` | `#0a0d14` | `oklch(0.169 0.013 252)` | Page bg. Deepest surface. |
+| `surface.subtle` | `#0d1119` | `oklch(0.184 0.013 252)` | `proof-strip`, `footer`, pricing. |
+| `surface.raised` | `#11151f` | `oklch(0.211 0.013 252)` | Section bg one notch above base. |
+| `surface.card` | `#141926` | `oklch(0.235 0.018 252)` | Pillar / deploy cards, tiles. |
+| `surface.hover` | `#1a2030` | `oklch(0.276 0.020 252)` | Hovered card, focused row. |
+| `surface.border` | `rgba(148,163,184,0.12)` | — | 1 px hairlines. |
+| `surface.divider` | `rgba(148,163,184,0.08)` | — | Section dividers. |
+
+Description: `surface.base` is a near-black with a subtle blue tint
+(~1.3% chroma at hue 252) — graphite on OLED, deep-navy on backlit
+IPS. Each step adds ~3% lightness for elevation legibility without
+hard shadows.
+
+### 2.2 Foreground scale (dark)
+
+| Token | Hex | OKLCH | Use |
+|---------------|-----------|--------------------------|----------------------------------|
+| `fg.primary` | `#e2e8f0` | `oklch(0.910 0.013 247)` | H1, H2, H3, CTA labels. |
+| `fg.secondary`| `#cbd5e1` | `oklch(0.844 0.018 245)` | Paragraph copy, sub-heads. |
+| `fg.muted` | `#9ca3af` | `oklch(0.708 0.013 264)` | Captions, eyebrows, FAQ teasers. |
+| `fg.subtle` | `#6b7280` | `oklch(0.537 0.013 264)` | Timestamps, helper text. |
+| `fg.inverse` | `#0f172a` | `oklch(0.214 0.030 270)` | Text on light buttons (rare). |
+
+### 2.3 Brand, accent, status
+
+| Token | Hex | Source | Use |
+|------------------------|-----------|--------------------------------|----------------------------------------------|
+| `brand.300` | `#93c5fd` | existing | Active text, eyebrows, badges, link hover. |
+| `brand.400` | `#60a5fa` | existing | Secondary CTA bg, focus glow. |
+| `brand.500` | `#3b82f6` | existing | Primary CTA, focus ring. |
+| `brand.600` | `#2563eb` | existing | CTA hover / pressed. |
+| `brand.700` | `#1d4ed8` | existing | CTA active, code keyword colour. |
+| `brand.900` | `#1e3a8a` | existing | Background accents, gradient end-stops. |
+| `landing.accent.ember` | `#f97316` | new | Pillar P3 ring; "auditable" only. |
+| `landing.accent.violet`| `#8b5cf6` | new | Pillar P2 ring; graph-native moments. |
+| `landing.success` | `#22c55e` | existing (`status.live`) | Air-gap "no outbound" badge. |
+| `landing.warning` | `#f59e0b` | existing (`status.warn`) | "Coming soon" chips. |
+| `landing.destructive` | `#ef4444` | existing (`severity.critical`) | Form-error UI only. |
+
+`severity.{critical,high,medium,low,info}` appear only inside product
+screenshots.
+
+### 2.4 Gradient pairs
+
+| Token | From | To | Direction | Use |
+|-----------------------------|-------------------------|-----------------------------------|------------------|--------------------------------------|
+| `landing.gradient.hero` | `#1d4ed8` (`brand.700`) | `#0a0d14` (`surface.base`) | `to bottom right`| Hero mesh fade; demo frame glow. |
+| `landing.gradient.pillars` | `#3b82f6` (`brand.500`) | `#8b5cf6` (`landing.accent.violet`)| `to right` | Pillar P2 active border, eyebrow. |
+| `landing.gradient.cta` | `#3b82f6` (`brand.500`) | `#1d4ed8` (`brand.700`) | `to bottom right`| Final CTA panel; primary button sheen.|
+
+CSS-variable additions (in `globals.css` under `[data-theme="dark"]`):
+
+```css
+--landing-grad-hero: linear-gradient(to bottom right, #1d4ed8 0%, #0a0d14 80%);
+--landing-grad-pillars: linear-gradient(to right, #3b82f6 0%, #8b5cf6 100%);
+--landing-grad-cta: linear-gradient(to bottom right, #3b82f6 0%, #1d4ed8 100%);
+```
+
+### 2.5 Tailwind diff (extension only)
+
+```ts
+// theme.extend.colors
+landing: { accent: { ember: '#f97316', violet: '#8b5cf6' } },
+// theme.extend.backgroundImage
+backgroundImage: {
+ 'landing-grad-hero': 'var(--landing-grad-hero)',
+ 'landing-grad-pillars': 'var(--landing-grad-pillars)',
+ 'landing-grad-cta': 'var(--landing-grad-cta)',
+},
+```
+
+### 2.6 Light-mode equivalents
+
+**Dark-locked v1; light variant deferred** to v1.1.
+
+---
+
+## 3. Type scale
+
+- **Sans:** `var(--font-inter)` (already loaded), variable, weights 400–800.
+- **Mono:** `var(--font-mono)` (JetBrains Mono variable subset).
+
+No new fonts.
+
+### 3.1 Scale (4 px base, unitless line-height, em tracking)
+
+| Token | Size (px) | Line-ht | Tracking | Weight | Use |
+|---------------|-----------|---------|----------|--------|------------------------------------|
+| `display.2xl` | 64 / 56 | 1.05 | -0.02em | 700 | Hero H1 (laptop+). |
+| `display.xl` | 48 / 44 | 1.10 | -0.02em | 700 | `final-cta` H2; section H2 desktop.|
+| `display.lg` | 40 / 36 | 1.15 | -0.015em | 700 | `solution`/`pillars`/`connectors` H2.|
+| `display.md` | 32 / 30 | 1.20 | -0.01em | 600 | Sub-section H3; mobile hero H1. |
+| `display.sm` | 24 / 24 | 1.25 | -0.005em | 600 | Card titles, tile headlines. |
+| `display.xs` | 20 / 20 | 1.30 | 0 | 600 | Pillar card title, FAQ question. |
+| `body.lg` | 18 / 18 | 1.55 | 0 | 400 | Hero sub-head, `solution` sub-head.|
+| `body.md` | 16 / 16 | 1.65 | 0 | 400 | Default paragraph copy. |
+| `body.sm` | 14 / 14 | 1.55 | 0 | 400 | Captions, deploy-card metadata. |
+| `body.xs` | 12 / 12 | 1.50 | 0.01em | 500 | Eyebrows, chip labels. |
+| `mono.md` | 16 / 16 | 1.50 | 0 | 500 | Inline code, big metric mantissa. |
+| `mono.sm` | 14 / 14 | 1.55 | 0 | 500 | Code blocks, repo card line. |
+| `mono.xs` | 12 / 12 | 1.50 | 0.01em | 500 | Number-tile suffix (`%`, `ms`). |
+
+Numbers always use mono with `font-feature-settings:"tnum" 1`.
+
+### 3.2 Per-section recommendation
+
+| Section | H tokens | Body |
+|------------------|----------------------------------------------|------|
+| `hero` | `display.2xl` (laptop+) → `display.md` (phone)| `body.lg` |
+| `proof-strip` | n/a | `body.xs` (label) |
+| `problem` | `display.lg` | `body.md` |
+| `solution` | `display.lg` | `body.lg` (sub-head) / `body.md` (cards) |
+| `demo` | `display.lg` | `body.md` |
+| `pillars` | `display.lg` (H2) / `display.xs` (card) | `body.md` |
+| `features-*` | `display.md` (H3) / `display.sm` (tile) | `body.sm` |
+| `connectors` | `display.lg` | `body.md` |
+| `benchmark` | `display.lg` / `display.xl` mono metric | `body.md` |
+| `deploy` | `display.lg` | `body.md` |
+| `open-source` | `display.lg` | `body.md` |
+| `testimonials` | `display.lg` | `body.md` |
+| `pricing-teaser` | `display.lg` | `body.md` |
+| `faq` | `display.lg` (H2) / `display.xs` (question) | `body.md` |
+| `final-cta` | `display.xl` | `body.lg` |
+| `footer` | n/a | `body.sm` |
+
+---
+
+## 4. Spacing rhythm
+
+Base unit **4 px** (Tailwind default — do not override).
+
+| Breakpoint | Default `py` | Hero `py` | Final-CTA `py` |
+|------------|--------------|-----------|----------------|
+| Phone | `py-16` | `py-20` | `py-20` |
+| Tablet | `py-20` | `py-28` | `py-24` |
+| Laptop+ | `py-24` | `py-32` | `py-28` |
+
+| Token | Value | Use |
+|--------------------------|--------------------------------------|----------------------------|
+| `landing.container.max` | `max-w-[1200px]` | Default sections. |
+| `landing.container.wide` | `max-w-[1320px]` | `hero` only. |
+| `landing.container.bleed`| 100% + 24 px gutter | `connectors`, `proof-strip`.|
+| `landing.gutter.x` | `px-6` / `px-8` / `px-12` (sm/md/lg) | All. |
+
+| Gap | px | Use |
+|---------|----|-------------------------------------|
+| `gap.xs`| 8 | Inside chip, button-icon-to-label. |
+| `gap.sm`| 12 | Card title to body. |
+| `gap.md`| 24 | Card body to footer link, list rows.|
+| `gap.lg`| 40 | Heading-stack to first card row. |
+| `gap.xl`| 64 | Hero copy column to visual column. |
+| `gap.2xl`| 96| Section H2 to nested grid (rare). |
+
+---
+
+## 5. Radius scale
+
+| Token | Value | Use |
+|---------------|-------|-------------------------------------------|
+| `radius.xs` | 4 px | Chip, severity badge in product screenshot.|
+| `radius.sm` | 6 px | Inline code, focus-ring offset. |
+| `radius.md` | 8 px | Buttons (default), inputs. |
+| `radius.lg` | 12 px | Pillar / deploy card, feature tile. |
+| `radius.xl` | 16 px | Hero shell on phone, demo frame. |
+| `radius.2xl` | 24 px | Hero shell on laptop+, final-CTA panel. |
+| `radius.full` | 9999 | Avatar, GitHub-star chip, pill nav. |
+
+---
+
+## 6. Elevation / shadow scale
+
+Soft, diffuse — never hard drops. Each = tight ambient + wider diffuse
+glow tinted toward `brand.900`.
+
+| Token | Dark-mode value | Use |
+|--------------------|--------------------------------------------------------------------------------|------------------------------------|
+| `landing.shadow.1` | `0 1px 0 rgba(255,255,255,0.04) inset, 0 1px 2px rgba(0,0,0,0.4)` | Default card / tile. |
+| `landing.shadow.2` | `0 1px 0 rgba(255,255,255,0.05) inset, 0 8px 24px -8px rgba(0,0,0,0.55)` | Hover state pillar / deploy card. |
+| `landing.shadow.3` | `0 1px 0 rgba(255,255,255,0.06) inset, 0 24px 48px -16px rgba(30,58,138,0.45)` | Hero demo frame, sticky nav glass. |
+| `landing.shadow.4` | `0 1px 0 rgba(255,255,255,0.06) inset, 0 32px 80px -24px rgba(59,130,246,0.35)` | Final-CTA panel. |
+
+Light-mode shadows deferred (see §2.6).
+
+---
+
+## 7. Motion tokens
+
+### 7.1 Easing
+
+| Token | Value |
+|----------------------------|----------------------------------------------------------------|
+| `landing.ease.out-expo` | `cubic-bezier(0.16, 1, 0.3, 1)` (default reveal) |
+| `landing.ease.out-quart` | `cubic-bezier(0.25, 1, 0.5, 1)` (card stagger, list reveal) |
+| `landing.ease.in-out-quad` | `cubic-bezier(0.45, 0, 0.55, 1)` (hover, accordion) |
+| `landing.ease.linear-loop` | `cubic-bezier(0, 0, 1, 1)` (marquee, infinite loops) |
+| `landing.ease.spring-soft` | framer-motion `{type:'spring', stiffness:140, damping:22}` |
+
+### 7.2 Duration
+
+| Token | Value | Use |
+|-----------------------------|------------|----------------------------------|
+| `landing.duration.instant` | `0 ms` | Reduced-motion fallback. |
+| `landing.duration.fast` | `150 ms` | Hover bg, focus-ring fade. |
+| `landing.duration.base` | `250 ms` | Card hover lift, link colour. |
+| `landing.duration.medium` | `400 ms` | Section reveal, accordion open. |
+| `landing.duration.slow` | `800 ms` | Hero H1 reveal, big metric tick. |
+| `landing.duration.beam` | `1500 ms` | Agent-beam path draw. |
+| `landing.duration.marquee` | `20000 ms` | Connector marquee revolution. |
+| `landing.duration.hero-loop`| `8000 ms` | Hero spotlight breathe. |
+| `landing.duration.bg-loop` | `30000 ms` | Background mesh slow drift. |
+
+### 7.3 Stagger
+
+`landing.stagger.cards = 60 ms` per item, capped at four (`pillars`,
+`deploy`, `pricing-teaser`). Larger grids (`features`, `connectors`)
+use 80 ms across the first six, then drop to zero.
+
+### 7.4 `prefers-reduced-motion` policy
+
+Loops pause at first frame; reveals swap to opacity 1 + transform 0
+instantly; hover affordances keep colour, drop transforms / shadows;
+marquees become a static grid; agent-beam becomes a static SVG drawn
+full-length. Per-animation table in `landing-page-motion-spec.md`.
+
+---
+
+## 8. Iconography
+
+- **Library:** Lucide (existing dep).
+- **Sizes:** `16` (chip / inline), `20` (default body), `24` (card glyph).
+- **Stroke:** `1.75 px`. Use `<Icon size={20} strokeWidth={1.75} />`.
+- **Colour:** `currentColor`; default `fg.muted`, active card → `brand.300`.
+- **Never fill icons inline with body text.**
+- **Brand glyphs** at `apps/web/public/glyphs/` (Subagent F creates):
+ four-agent nodes, entity-graph mesh, maturity-dial.
+
+---
+
+## 9. Imagery
+
+- **Banned:** Stock photography, shield-on-circuit, glowing brains,
+ padlock-on-keyboard, hooded-hacker, isometric server rooms.
+- **Allowed (priority):** (1) schematic line-art SVG, (2) real product
+ screenshots dark-theme PNG, (3) captured developer photography (no
+ faces, low-key) for `open-source` if needed.
+
+| Section | Ratio | Pixel target (laptop) |
+|------------------------|--------|--------------------------|
+| `hero` visual | 16:9 | 960 × 540 (SVG preferred)|
+| `demo` embed | 16:9 | 1280 × 720 |
+| `pillars` glyph | 1:1 | 96 × 96 |
+| `features` tile | 4:3 | 320 × 240 |
+| `solution` agent glyph | 1:1 | 64 × 64 |
+| `open-source` repo | 16:9 | 720 × 405 |
+| OG image | 1.91:1 | 1200 × 630 |
+
+---
+
+## 10. Banned tokens
+
+Not allowed inside any landing component:
+
+1. Inline `#hex` strings — use Tailwind class or CSS var (§2).
+2. Inline `px` margins / paddings — use Tailwind utility (§4).
+3. Inline `rgba()` shadows — use `landing.shadow.*` (§6).
+4. Inline `cubic-bezier()` — use `landing.ease.*` (§7).
+5. Tailwind arbitrary values (`text-[14.5px]`, `bg-[#123456]`) outside
+ the OG image generator at `apps/web/src/app/og/route.tsx` (Satori
+ demands literal hex).
+6. `font-bold` on body copy — body is `400`, headings `600`/`700`.
+7. The word `severity` outside product screenshots.
+
+---
+
+*End of tokens. Pair with `landing-page-component-recipes.md` and
+`landing-page-motion-spec.md`.*
diff --git a/docs/design/landing-page-motion-spec.md b/docs/design/landing-page-motion-spec.md
new file mode 100644
index 000000000..611ddc866
--- /dev/null
+++ b/docs/design/landing-page-motion-spec.md
@@ -0,0 +1,95 @@
+# AiSOC landing page — motion spec
+
+> Companion to `landing-page-component-recipes.md` and
+> `landing-page-design-tokens.md` §7. Twelve micro-animations across
+> the page. Every duration / easing resolves to a token from the
+> design-tokens doc — no inline `cubic-bezier()`, no inline `ms`.
+
+---
+
+## 1. Choreography table
+
+The canonical source for **what animates, when, how long, and what
+reduced-motion does instead.** Each row is one PR-sized unit.
+
+| ID | Where | Trigger | Enter dur | Enter easing | Exit dur | Exit easing | Stagger | Reduced-motion fallback | Purpose |
+|-----------------------------|----------------------------------------------|---------------------|--------------------|---------------|--------------|------------------|----------------|----------------------------------------------|-----------------------------------------------------------------|
+| `hero-h1-reveal` | `hero` | mount | `slow` 800 | `out-expo` | — | — | 30 / word | **instant** — opacity 1, no transform | Sets page pace; H1 earns scale by entering with intent. |
+| `hero-bg-grid` | `hero` | mount loop | `bg-loop` 30000 | `linear-loop` | — | — | — | **static** — render grid frame once | Living signal under page that never pulls focus. |
+| `hero-spotlight-pulse` | `hero` | mount loop | `hero-loop` 8000 | `out-expo` | — | — | — | **static** — spotlight at 60%, no breathe | Soft "page is alive" cue without a video. |
+| `hero-cta-shimmer` | `hero`, `final-cta` | hover | `medium` 400 | `in-out-quad` | `fast` 150 | `in-out-quad` | — | **none** — solid `brand-500`, no sheen | Reward intent on conversion target without animating pre-hover. |
+| `pillar-card-stagger` | `pillars` | scroll-into-view | `medium` 400 | `out-quart` | — | — | 80 / card | **instant** — cards opacity 1, no translate | Eye absorbs four claims one at a time. |
+| `pillar-card-glow` | `pillars` (P2) | hover | `base` 250 | `in-out-quad` | `fast` 150 | `in-out-quad` | — | **none** — static `border-brand-500/30` | Marks P2 differentiation without a "look at me" loop. |
+| `connector-marquee` | `connectors`, `proof-strip` | mount loop | `marquee` 20000–60000 | `linear-loop` | — | — | — | **static row** — 18 logos in 5-col grid | Gives "69 connectors" sensory weight; static art still works. |
+| `agent-beam` | `solution`, `hero` visual | scroll + loop | `beam` 1500 | custom `cubic-bezier(0.65,0,0.35,1)` | `slow` 800 | `in-out-quad` | — | **static path** full-length, single colour | Four-agent topology as a sequence, not an org chart. |
+| `number-ticker-benchmark` | `benchmark`, `nav`, `pillars`, `open-source` | scroll-into-view | `slow` 800–`beam` 1500 | `out-expo` | — | — | 200 / tile | **final value** rendered directly | Earns the metric; reduced-motion shows destination directly. |
+| `accordion-toggle` | `faq` | click | `base` 250 open / `fast` 150 close | `in-out-quad` | `fast` 150 | `in-out-quad` | — | **instant** — open / close, no slide | Familiar affordance; small motion confirms click. |
+| `final-cta-wave` | `final-cta` | mount loop | `bg-loop` 30000 | `linear-loop` | — | — | — | **static gradient** — `landing.gradient.cta` | Closes page with calm motion; static gradient carries energy. |
+| `card-hover-lift` | `pillars`, `deploy`, `pricing-teaser`, `features-*` | hover | `base` 250 | `in-out-quad` | `fast` 150 | `in-out-quad` | — | **none** — colour shift only, no translate | Card invites click without behaving like a button. |
+
+---
+
+## 2. Notes
+
+- **`hero-h1-reveal`.** Text Generate Effect with `filter={false}` — at 56–64 px, blur reads as a mistake. 30 ms / word ≈ "spoken," not "typed." Total ≈ 920 ms — inside the 1.2 s LCP budget on a wired laptop.
+- **`hero-bg-grid` + `hero-spotlight-pulse`.** Coprime periods (30 s / 8 s) so the visual never lands on a frame the eye has cached.
+- **`hero-cta-shimmer`.** Hover-gated — never on mount (would compete with the H1 reveal). Loops indefinitely on hover (the cursor is the user's commitment).
+- **`pillar-card-stagger`.** Single intersection-observer fire at 30% viewport. 80 ms × 4 = 320 ms cascade. If a fifth pillar lands later, drop to 60 ms so total cascade stays under 400 ms.
+- **`agent-beam`.** Most important motion. Draws once on scroll (1.5 s, custom curve settling into the final node), then loops every 6 s, fading just-drawn path to 30% before re-drawing. Reinforces "Respond is the terminus." Static SVG path is the default render, so the section never breaks.
+- **`connector-marquee`.** Two rows at 60 s / 75 s. Hover pauses both — losing both rows together stops the cursor-boundary stutter.
+- **`number-ticker-benchmark`.** 200 ms gap between tiles. Tile 2 is a string ("Sub-minute"), no ticker. Numeric tiles use `out-expo` so count settles on target, no overshoot.
+- **`accordion-toggle`.** Asymmetric: open 250 ms, close 150 ms. Close-faster feels in-control; open-slower lets content reveal readably.
+- **`final-cta-wave`.** Pick one of Wavy Background or Background Boxes in recipes — do not stack. Both reduce to the same fallback.
+- **`card-hover-lift`.** 2 px translate-Y + swap `landing.shadow.1` → `.2`. Reduced-motion drops translate, keeps shadow swap + icon-colour shift.
+
+---
+
+## 3. `prefers-reduced-motion` policy
+
+The global rule in `globals.css` clamps every animation to 0.01 ms.
+On top, **per-section JS gates** check
+`window.matchMedia('(prefers-reduced-motion: reduce)').matches` and
+skip mounting:
+
+- All Marquee → static grid.
+- All Number Ticker → final value.
+- All Animated Beam → static SVG path.
+- All Border Beam → static border.
+- All Wavy Background / Background Boxes / Particles → static gradient or solid surface.
+
+Subagent F lifts the check into a single `useReducedMotion()` hook
+from framer-motion (existing dep). Every animated component reads
+the hook and self-disables.
+
+---
+
+## 4. Animation budget
+
+| Metric | Budget |
+|-------------------------------------------------|----------------------|
+| Animations mounted on initial paint (`hero`) | ≤ 3 |
+| Animations mounted before LCP fires | ≤ 3 |
+| Total animations on the page | ≤ 12 |
+| Total motion JS (gzip, lazy-loaded) | ≤ 35 KB |
+| Frame budget per active animation | ≤ 4 ms / 60 Hz frame |
+| Loops that run infinitely | 5 (`hero-bg-grid`, `hero-spotlight-pulse`, `connector-marquee`, `agent-beam`, `final-cta-wave`) |
+| Reduced-motion fallback coverage | 12 / 12 (100%) |
+
+A thirteenth animation is gated on this table — propose here first.
+
+---
+
+## 5. Hand-off checklist
+
+Before opening the implementation PR for a given section:
+
+1. Every animation maps to a row above.
+2. Every duration / easing literal resolves to a `landing.duration.*` / `landing.ease.*` token.
+3. Page rendered under `prefers-reduced-motion: reduce` shows the listed fallback.
+4. `useReducedMotion()` is the single source of truth — no per-component `matchMedia()`.
+5. Section animations fit under 4 ms / frame on a 4-year-old MacBook.
+
+---
+
+*End of motion spec. Hold this table next to brief §6 (IA) and the
+recipes doc's primitive list while implementing.*
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 97fa0502b..8dbb9c6af 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -5899,51 +5899,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
- /api/v1/metrics/funnel:
- get:
- tags:
- - metrics
- summary: Get Funnel Metrics
- description: 'Return the live tenant funnel for the SOC Console (v1.5).
-
-
- Funnel: events_of_interest → correlation_instances → alerts_generated →
-
- analyst_queue_depth, plus efficiency ratios and MITRE coverage.
-
-
- ``deltas`` compares the current window to the immediately preceding window
-
- of the same length (e.g. for ``period=24h`` we compare to the 24h ending
-
- 24h ago). Values are percentage changes rounded to two decimals; a delta
-
- of ``0.0`` means "no meaningful baseline" (the previous window was empty).'
- operationId: get_funnel_metrics_api_v1_metrics_funnel_get
- security:
- - HTTPBearer: []
- parameters:
- - name: period
- in: query
- required: false
- schema:
- type: string
- pattern: ^(1h|24h|7d|30d)$
- default: 24h
- title: Period
- responses:
- '200':
- description: Successful Response
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/FunnelMetrics'
- '422':
- description: Validation Error
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/HTTPValidationError'
/api/v1/insights/soc:
get:
tags:
@@ -5987,38 +5942,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
- /api/v1/health/pipeline:
- get:
- tags:
- - health
- summary: Get Pipeline Health
- description: 'Return a 5-stage health snapshot of the SOC pipeline for the tenant.
-
-
- Stages: ``ingest → normalize → fuse → correlate → alert``. See the
-
- module docstring for what each cell measures and why some columns
-
- are intentionally ``0`` until deeper instrumentation lands.
-
-
- The window for latency / backlog computations is the last hour.
-
- The ``status`` ladder is ``unknown | green | yellow | red`` and
-
- follows the same convention as
-
- ``app.services.connector_freshness``.'
- operationId: get_pipeline_health_api_v1_health_pipeline_get
- responses:
- '200':
- description: Successful Response
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/PipelineHealth'
- security:
- - HTTPBearer: []
/api/v1/sla/metrics:
get:
tags:
@@ -25496,11 +25419,6 @@ components:
type:
type: string
title: Error Type
- input:
- title: Input
- ctx:
- type: object
- title: Context
type: object
required:
- loc
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 242f0fc6e..63498b827 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -114,6 +114,9 @@ importers:
swr:
specifier: ^2.2.4
version: 2.4.1([email protected])
+ tailwind-merge:
+ specifier: ^3.6.0
+ version: 3.6.0
zustand:
specifier: ^5.0.13
version: 5.0.13(@types/[email protected])([email protected])
@@ -15147,6 +15150,10 @@ packages:
resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
dev: true
+ resolution: {integrity: sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w==}
+ dev: false
+
resolution: {integrity: sha512-HhKppgO81FQof5m6TEnuBWCZGgfRAWbaeOaGT00KOy/Pf/j6oUihdvBpA7ltCeAvZpFhW3j0PTclkxsd4IXYDA==}
dev: true
diff --git a/scripts/aisoc-demo.ts b/scripts/aisoc-demo.ts
index 3e1fa1dca..59106d624 100644
--- a/scripts/aisoc-demo.ts
+++ b/scripts/aisoc-demo.ts
@@ -41,7 +41,7 @@
*/
import { execSync, spawnSync } from "node:child_process";
import { writeFileSync } from "node:fs";
-import { createConnection } from "node:net";
+import { createConnection, createServer } from "node:net";
import { join } from "node:path";
import { platform } from "node:os";
@@ -238,6 +238,94 @@ async function probePort(host: string, port: number, timeoutMs = 1500): Promise<
});
}
+// ---------- Port allocation ----------
+//
+// Why this exists: every prior failed `pnpm aisoc:demo` run can leave
+// behind a half-spawned container (or a stale com.docker proxy) that
+// still holds the canonical host port — the symptom the user sees is
+// `failed to bind port 127.0.0.1:3000/tcp: bind: address already in
+// use` deep in a docker-compose error wall. A unrelated `next dev` on
+// 3000, a local Postgres on 5432, or a Kafka broker on 9092 produce the
+// same opaque failure. We solve that by checking each host-published
+// port up front and falling forward to the next free port in a small
+// window if the canonical one is taken. The compose file uses these
+// values via AISOC_*_PORT env vars (with defaults), so manual `docker
+// compose up` outside this script still binds the canonical ports.
+
+interface PortMap {
+ web: number;
+ api: number;
+ realtime: number;
+ postgres: number;
+ redis: number;
+ kafka: number;
+}
+
+const DEFAULT_PORTS: PortMap = {
+ web: 3000,
+ api: 8000,
+ realtime: 8086,
+ postgres: 5432,
+ redis: 6379,
+ kafka: 9092,
+};
+
+// `allocatedPorts` is module-level because half a dozen call sites
+// (waitForHealth, findSeededCase, kickoffInvestigation, openInBrowser,
+// the final banner) need the resolved values. Threading them through
+// every signature would be more code than the values are worth.
+let allocatedPorts: PortMap = { ...DEFAULT_PORTS };
+
+// Tests an actual bind on 127.0.0.1. Connect-based probes give false
+// negatives for ports whose owner doesn't accept() fast enough; binding
+// is the same test Docker is going to run, so the answer is authoritative.
+function isPortFree(port: number): Promise<boolean> {
+ return new Promise((resolve) => {
+ const tester = createServer();
+ tester.once("error", () => resolve(false));
+ tester.once("listening", () => {
+ tester.close(() => resolve(true));
+ });
+ try {
+ tester.listen(port, "127.0.0.1");
+ } catch {
+ resolve(false);
+ }
+ });
+}
+
+// Scan upward from `start` for a free port. The window is intentionally
+// small (50) because a host that has 50 consecutive ports in this range
+// busy is almost certainly misconfigured and silently rerouting the user
+// would create more confusion than failing fast.
+async function pickFreePort(start: number, max = 50): Promise<number> {
+ for (let p = start; p < start + max; p++) {
+ if (await isPortFree(p)) return p;
+ }
+ throw new Error(
+ `no free TCP port near ${start} (checked ${start}..${start + max - 1}). ` +
+ `Free one of them or stop the conflicting process and retry.`,
+ );
+}
+
+async function allocatePorts(): Promise<{
+ ports: PortMap;
+ reassigned: Array<{ service: keyof PortMap; from: number; to: number }>;
+}> {
+ // Allocate sequentially so each service can drift independently — a
+ // taken 3000 doesn't push api off 8000. Each starts from its canonical
+ // default and only moves if forced.
+ const ports = { ...DEFAULT_PORTS };
+ const reassigned: Array<{ service: keyof PortMap; from: number; to: number }> = [];
+ for (const service of Object.keys(DEFAULT_PORTS) as Array<keyof PortMap>) {
+ const def = DEFAULT_PORTS[service];
+ const free = await pickFreePort(def);
+ ports[service] = free;
+ if (free !== def) reassigned.push({ service, from: def, to: free });
+ }
+ return { ports, reassigned };
+}
+
async function fetchJson(url: string, timeoutMs = 5000): Promise<any | null> {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
@@ -410,11 +498,51 @@ function pullImages(flags: Flags): boolean {
return true;
}
-function startStack(flags: Flags): boolean {
+function portEnv(ports: PortMap): NodeJS.ProcessEnv {
+ return {
+ AISOC_WEB_PORT: String(ports.web),
+ AISOC_API_PORT: String(ports.api),
+ AISOC_REALTIME_PORT: String(ports.realtime),
+ AISOC_POSTGRES_PORT: String(ports.postgres),
+ AISOC_REDIS_PORT: String(ports.redis),
+ AISOC_KAFKA_PORT: String(ports.kafka),
+ };
+}
+
+async function startStack(flags: Flags): Promise<boolean> {
step(3, 7, "Starting AiSOC demo stack");
+
+ // Pick host ports BEFORE compose up so any conflict (lingering
+ // aisoc-demo-* container, unrelated dev server, local Postgres) is
+ // surfaced in the script's own output instead of buried in a docker
+ // compose error wall. Module-level so the rest of the script can read
+ // the resolved values without threading them through every signature.
+ let reassigned: Array<{ service: keyof PortMap; from: number; to: number }> = [];
+ try {
+ const alloc = await allocatePorts();
+ allocatedPorts = alloc.ports;
+ reassigned = alloc.reassigned;
+ } catch (e: any) {
+ console.error(c.red(`port allocation failed: ${e?.message ?? e}`));
+ return false;
+ }
+ if (reassigned.length > 0) {
+ for (const r of reassigned) {
+ log(
+ c.yellow("port") +
+ ` ${r.service} ${c.dim(String(r.from))} in use → using ${c.bold(String(r.to))}`,
+ );
+ }
+ } else {
+ log(c.green("ok") + " all canonical ports free");
+ }
+
const args = ["compose", "-f", COMPOSE_FILE, "up", "-d"];
if (flags.rebuild) args.push("--build");
- const code = runStream("docker", args, { AISOC_TAG: flags.tag });
+ const code = runStream("docker", args, {
+ AISOC_TAG: flags.tag,
+ ...portEnv(allocatedPorts),
+ });
if (code !== 0) {
console.error(c.red("docker compose up failed. See output above."));
return false;
@@ -427,7 +555,7 @@ async function waitForHealth(): Promise<boolean> {
const postgresUp = await waitFor(
"postgres",
- async () => probePort("127.0.0.1", 5432),
+ async () => probePort("127.0.0.1", allocatedPorts.postgres),
60_000,
1000,
);
@@ -436,7 +564,10 @@ async function waitForHealth(): Promise<boolean> {
const apiUp = await waitFor(
"api /health",
async () => {
- const j = await fetchJson("http://localhost:8000/health", 1500);
+ const j = await fetchJson(
+ `http://localhost:${allocatedPorts.api}/health`,
+ 1500,
+ );
return j !== null;
},
120_000,
@@ -448,7 +579,7 @@ async function waitForHealth(): Promise<boolean> {
"web",
async () => {
try {
- const res = await fetch("http://localhost:3000", {
+ const res = await fetch(`http://localhost:${allocatedPorts.web}`, {
signal: AbortSignal.timeout(1500),
});
return res.status > 0;
@@ -550,7 +681,10 @@ async function findSeededCase(
// larger than the seed's ~16 cases). Filtering server-side by
// case_number would be cleaner but the cases list endpoint doesn't
// currently expose that filter, and the volume is trivially small.
- const res = await fetchJson("http://localhost:8000/v1/cases?page_size=50", 4000);
+ const res = await fetchJson(
+ `http://localhost:${allocatedPorts.api}/v1/cases?page_size=50`,
+ 4000,
+ );
if (res && Array.isArray(res.items) && res.items.length > 0) {
const found = res.items.find(
(item: any) => item.case_number === showcase,
@@ -586,7 +720,7 @@ async function kickoffInvestigation(caseId: string): Promise<boolean> {
// a heuristic plan, which is still demo-worthy.
log(c.dim("kicking off agent investigation…"));
const result = await postJson(
- `http://localhost:8000/v1/cases/${caseId}/investigate`,
+ `http://localhost:${allocatedPorts.api}/v1/cases/${caseId}/investigate`,
{},
10000,
);
@@ -617,12 +751,13 @@ async function openInBrowser(
// all land in the same place. The Next.js [id] route resolves both
// case_number and UUID via the API's case_number_or_id lookup
// (services/api/app/api/v1/endpoints/cases.py).
+ const webBase = `http://localhost:${allocatedPorts.web}`;
const safeNumber = seeded ? sanitizeCaseNumber(seeded.case_number) : null;
const url = seeded
? safeNumber
- ? `http://localhost:3000/cases/${safeNumber}?tab=ledger`
- : `http://localhost:3000/cases/${seeded.id}?tab=ledger`
- : "http://localhost:3000/cases";
+ ? `${webBase}/cases/${safeNumber}?tab=ledger`
+ : `${webBase}/cases/${seeded.id}?tab=ledger`
+ : `${webBase}/cases`;
step(7, 7, `Opening browser at ${url}`);
if (flags.noOpen) {
log(c.dim("--no-open: not launching browser"));
@@ -637,8 +772,8 @@ async function openInBrowser(
console.log(`
${c.bold(c.green("AiSOC demo is up."))}
${c.bold("Web:")} ${url}
- ${c.bold("API:")} http://localhost:8000/docs
- ${c.bold("Realtime:")} ws://localhost:8086
+ ${c.bold("API:")} http://localhost:${allocatedPorts.api}/docs
+ ${c.bold("Realtime:")} ws://localhost:${allocatedPorts.realtime}
${c.dim("Useful commands:")}
pnpm aisoc:doctor ${c.dim("# health check")}
@@ -776,7 +911,7 @@ async function main() {
if (!checkDocker()) process.exit(1);
if (!pullImages(flags)) process.exit(1);
- if (!startStack(flags)) process.exit(1);
+ if (!(await startStack(flags))) process.exit(1);
if (!(await waitForHealth())) {
console.error(c.red("\nstack failed to come up healthy. Run `pnpm aisoc:doctor` for details."));
process.exit(1);
diff --git a/scripts/export_graph_schema.py b/scripts/export_graph_schema.py
index ef29a8cdf..886fcc596 100755
--- a/scripts/export_graph_schema.py
+++ b/scripts/export_graph_schema.py
@@ -42,7 +42,6 @@ Exit codes
from __future__ import annotations
import argparse
-import contextlib
import json
import os
import re
@@ -221,8 +220,10 @@ def parse_live_neo4j() -> tuple[set[str], set[str]] | None:
except Exception:
return None
finally:
- with contextlib.suppress(Exception):
+ try:
driver.close()
+ except Exception:
+ pass
return labels, rels
diff --git a/scripts/render_eval_charts.py b/scripts/render_eval_charts.py
index 6bf3da33d..d2f73ca90 100755
--- a/scripts/render_eval_charts.py
+++ b/scripts/render_eval_charts.py
@@ -260,11 +260,9 @@ def _render_wet_eval_real(wet: dict[str, Any]) -> str:
"# Wet eval — latency / tokens / USD",
"",
":::tip Wet eval (live agent, real LLM)",
- (
- "Numbers below are from a real `services/agents` LangGraph run with"
- " live LLM calls. See the [methodology page](../../../apps/docs/docs/benchmark-methodology.md)"
- " for the substrate-vs-wet distinction."
- ),
+ "Numbers below are from a real `services/agents` LangGraph run with"
+ " live LLM calls. See the [methodology page](../../../apps/docs/docs/benchmark-methodology.md)"
+ " for the substrate-vs-wet distinction.",
":::",
"",
]
diff --git a/scripts/run_evals.py b/scripts/run_evals.py
index 41a18285f..a5a177eb8 100755
--- a/scripts/run_evals.py
+++ b/scripts/run_evals.py
@@ -66,6 +66,7 @@ _AGENTS_ROOT = _REPO_ROOT / "services" / "agents"
# `from tests.test_adversary_eval import ...` resolves to the substrate tests.
sys.path.insert(0, str(_REPO_ROOT / "scripts"))
sys.path.insert(0, str(_AGENTS_ROOT))
+sys.path.insert(0, str(_REPO_ROOT / "scripts"))
# The per-investigation token/USD/latency telemetry block (T2.4) is stdlib-only
# and lives in ``scripts/eval_telemetry.py`` so it can run on hosts that
@@ -76,32 +77,6 @@ from eval_telemetry import ( # type: ignore # noqa: E402
compute_per_investigation_telemetry,
)
-
-def _print_import_error_hint(exc: BaseException) -> None:
- """Friendly message when ``services/agents`` deps aren't installed.
-
- The quickstart video walks new contributors through a fresh clone, so
- when ``run_evals.py`` fails on import we owe them the exact two-command
- fix rather than a raw ``ModuleNotFoundError`` traceback.
-
- H-7: When the substrate is required (i.e. ``--telemetry-only`` is not
- set), the caller invokes ``sys.exit(3)`` after printing this hint so
- CI surfaces the missing-deps state as a distinct exit code.
- """
- print(
- "ERROR: run_evals.py could not import the AiSOC eval substrate.\n"
- f" Underlying cause: {exc.__class__.__name__}: {exc}\n"
- "\n"
- " This usually means services/agents Python deps aren't\n"
- " installed in your current venv. Install them with:\n"
- "\n"
- " python -m venv .venv && source .venv/bin/activate\n"
- " pip install -e services/agents\n"
- "\n"
- " Then re-run `python scripts/run_evals.py --suite all`.",
- file=sys.stderr,
- )
-
# Wet-eval shim (T5.5). Dry-run path is stdlib-only; live path imports the
# agent stack lazily and degrades cleanly if it isn't available. Lives in
# ``scripts/wet_eval.py`` to keep the wet-eval shape decoupled from the
@@ -762,24 +737,6 @@ def _build_per_investigation_block(model: str, *, keep_records: bool) -> dict:
return block
-# Ordered suite registry — keeps CLI --suite choices, the report layout,
-# and the human-readable summary in lockstep.
-_SUITE_RUNNERS: dict[str, callable] = {
- "mitre_accuracy": _run_mitre,
- "alert_reduction": _run_alert_reduction,
- "investigation_completeness": _run_completeness,
- "response_quality": _run_response_quality,
- "hunt_corpus": _run_hunt_corpus,
- "adversary_eval": _run_adversary,
- "confidence_calibration": _run_confidence_calibration,
- "memory_recall": _run_memory_recall,
- "override_accuracy": _run_override_accuracy,
- "playbook_completion_rate": _run_playbook_completion,
- "detection_fp_rate": _run_detection_fp_rate,
-}
-_SUITE_NAMES = tuple(_SUITE_RUNNERS.keys())
-
-
def main() -> None:
parser = argparse.ArgumentParser(description="AiSOC Pillar-1 unified evaluation runner.")
parser.add_argument(
@@ -949,19 +906,16 @@ def main() -> None:
sys.exit(0)
if not args.telemetry_only and not _SUBSTRATE_AVAILABLE:
- # H-7: Substrate suites need pydantic / langchain etc. If they're not
- # installed we can still emit the telemetry block — print the friendly
- # hint and surface a distinct exit code (3) so CI / scripts can tell
- # "missing deps" apart from "substrate failed".
- if _SUBSTRATE_IMPORT_ERROR is not None:
- _print_import_error_hint(_SUBSTRATE_IMPORT_ERROR)
- else:
- print(
- "Substrate-suite imports failed. "
- "Pass --telemetry-only to emit just the T2.4 token/USD/latency block.",
- file=sys.stderr,
- )
- sys.exit(3)
+ # Substrate suites need pydantic / langchain etc. If they're not
+ # installed we can still emit the telemetry block — surface the
+ # original ImportError so operators know what to fix.
+ msg = (
+ "Substrate-suite imports failed (likely missing agent dev deps "
+ f"such as pydantic): {_SUBSTRATE_IMPORT_ERROR!r}. "
+ "Pass --telemetry-only to emit just the T2.4 token/USD/latency block."
+ )
+ print(msg, file=sys.stderr)
+ sys.exit(2)
keep_records = not args.no_telemetry_records
per_investigation = _build_per_investigation_block(
@@ -978,14 +932,22 @@ def main() -> None:
}
summary["all_passed"] = True # telemetry-only never gates substrate
else:
- # Use the suite registry so ``--suite <name>`` can run a single suite.
- selected = _SUITE_NAMES if args.suite == "all" else (args.suite,)
- suites = {name: _SUITE_RUNNERS[name]() for name in selected}
summary = {
"generated_at": datetime.now(UTC).isoformat(),
"dataset": "synthetic_incidents.json (200 cases, deterministic)",
- "suite_filter": args.suite,
- "suites": suites,
+ "suites": {
+ "mitre_accuracy": _run_mitre(),
+ "alert_reduction": _run_alert_reduction(),
+ "investigation_completeness": _run_completeness(),
+ "response_quality": _run_response_quality(),
+ "hunt_corpus": _run_hunt_corpus(),
+ "adversary_eval": _run_adversary(),
+ "confidence_calibration": _run_confidence_calibration(),
+ "memory_recall": _run_memory_recall(),
+ "override_accuracy": _run_override_accuracy(),
+ "playbook_completion_rate": _run_playbook_completion(),
+ "detection_fp_rate": _run_detection_fp_rate(),
+ },
"telemetry": _summarise_telemetry(),
"per_investigation": per_investigation,
}
diff --git a/scripts/wet_eval_check.py b/scripts/wet_eval_check.py
index 927c59326..b1297da6f 100755
--- a/scripts/wet_eval_check.py
+++ b/scripts/wet_eval_check.py
@@ -143,16 +143,10 @@ def main(argv: list[str] | None = None) -> int:
elif args.dry_run:
print("[wet-eval-check] dry-run — no live API calls will be attempted.")
else:
- # We intentionally do NOT include the names of missing secrets in
- # stdout. The names themselves aren't credentials, but CodeQL's
- # py/clear-text-logging-sensitive-data taint analysis treats any
- # variable containing the substring "secret" as sensitive. The full
- # missing-secret list is still written to ``status.json`` (consumed
- # by the workflow) — that file is internal and is not echoed to the
- # public log.
print(
- "[wet-eval-check] SKIP — required secret(s) not configured. "
- "Workflow will exit cleanly."
+ "[wet-eval-check] SKIP — "
+ + reason.split(". ", 1)[0]
+ + ". Workflow will exit cleanly."
)
# Always exit 0 — missing secrets is *expected* on forks. The workflow
diff --git a/services/agents/app/agents/__init__.py b/services/agents/app/agents/__init__.py
index dbb4ca0f8..ca9ca6040 100644
--- a/services/agents/app/agents/__init__.py
+++ b/services/agents/app/agents/__init__.py
@@ -167,10 +167,10 @@ class TriageCapability:
self.name = name
self._runner = runner
- async def __call__(self, state: InvestigationState) -> InvestigationState:
+ async def __call__(self, state: "InvestigationState") -> "InvestigationState":
return await self._runner(state)
- async def run(self, state: InvestigationState) -> InvestigationState:
+ async def run(self, state: "InvestigationState") -> "InvestigationState":
return await self._runner(state)
def __repr__(self) -> str: # pragma: no cover - debug helper
@@ -214,7 +214,7 @@ class TriageAgent:
}
@staticmethod
- async def auto_triage(state: InvestigationState) -> InvestigationState:
+ async def auto_triage(state: "InvestigationState") -> "InvestigationState":
"""LLM-based auto-triage entry point.
Delegates to :func:`app.agents.auto_triage_agent.run_auto_triage`.
@@ -222,7 +222,7 @@ class TriageAgent:
return await _run_auto_triage(state)
@staticmethod
- async def heuristic_triage(state: InvestigationState) -> InvestigationState:
+ async def heuristic_triage(state: "InvestigationState") -> "InvestigationState":
"""Deterministic heuristic triage (severity scoring + IOC extraction).
Delegates to :func:`app.agents.triage_agent.run_triage`. Used by the
@@ -234,10 +234,10 @@ class TriageAgent:
@classmethod
async def analyse(
cls,
- state: InvestigationState,
+ state: "InvestigationState",
*,
capability: str,
- ) -> InvestigationState:
+ ) -> "InvestigationState":
"""Dispatch to a named sub-agent capability.
Args:
@@ -253,7 +253,7 @@ class TriageAgent:
# Convenience callable so ``await TriageAgent()(state)`` and
# ``await TriageAgent.auto_triage(state)`` both work.
- async def __call__(self, state: InvestigationState) -> InvestigationState:
+ async def __call__(self, state: "InvestigationState") -> "InvestigationState":
return await _run_auto_triage(state)
@classmethod
@@ -450,10 +450,10 @@ class _CapabilityShim:
cls.capability = capability
@classmethod
- async def run(cls, state: InvestigationState) -> InvestigationState:
+ async def run(cls, state: "InvestigationState") -> "InvestigationState":
return await cls.capability(state)
- async def __call__(self, state: InvestigationState) -> InvestigationState:
+ async def __call__(self, state: "InvestigationState") -> "InvestigationState":
return await type(self).capability(state)
diff --git a/services/agents/app/context/bundle.py b/services/agents/app/context/bundle.py
index 530cdfcfe..64edccc8a 100644
--- a/services/agents/app/context/bundle.py
+++ b/services/agents/app/context/bundle.py
@@ -237,10 +237,8 @@ class ThreatIntelMatch(BaseModel):
# Allowed top-level keys in ``summary_for_llm`` — kept here (not in
# ``app/llm/contract.py``) so the model is the source of truth and the
-# contract validator can import this whitelist. Public (no leading
-# underscore) because the contract tests and downstream validators
-# import this tuple directly.
-LLM_SAFE_KEYS = (
+# contract validator can import this whitelist.
+_LLM_SAFE_KEYS = (
"incident_id",
"alert_summary",
"entity_count",
@@ -298,7 +296,12 @@ class ContextBundle(BaseModel):
Used by sub-agents to decide whether to short-circuit to the
bundle-aware prompt or fall back to bare-alert reasoning.
"""
- return bool(self.entity_neighborhoods or self.peer_baselines or self.threat_intel or self.historical_similar_cases)
+ return bool(
+ self.entity_neighborhoods
+ or self.peer_baselines
+ or self.threat_intel
+ or self.historical_similar_cases
+ )
def prompt_context_lines(self) -> list[str]:
"""Render the bundle's safe summary fields as prompt-ready lines.
@@ -314,7 +317,10 @@ class ContextBundle(BaseModel):
s = self.summary_for_llm()
parts: list[str] = ["", "Pre-fetched investigation context (ContextBundle):"]
if s.get("entity_count"):
- parts.append(f"- Entities resolved: {s['entity_count']} ({', '.join(s.get('entity_types') or []) or 'unknown'})")
+ parts.append(
+ f"- Entities resolved: {s['entity_count']} "
+ f"({', '.join(s.get('entity_types') or []) or 'unknown'})"
+ )
if s.get("neighborhood_summaries"):
parts.append("- Graph neighbourhood:")
for line in s["neighborhood_summaries"]:
@@ -326,12 +332,16 @@ class ContextBundle(BaseModel):
(h["similarity"] for h in s.get("historical_verdicts") or []),
default=0.0,
)
- parts.append(f"- Similar historical cases: {s['historical_similar_count']} (top similarity={top:.2f})")
+ parts.append(
+ f"- Similar historical cases: {s['historical_similar_count']} "
+ f"(top similarity={top:.2f})"
+ )
for h in (s.get("historical_verdicts") or [])[:3]:
parts.append(f" * {h['key']} → {h['verdict']} (sim={h['similarity']:.2f})")
if s.get("ueba_entities_with_baseline"):
parts.append(
- f"- UEBA: {s['ueba_entities_with_baseline']} entities with baseline, max deviation={s.get('ueba_max_deviation', 0.0):.2f}"
+ f"- UEBA: {s['ueba_entities_with_baseline']} entities with baseline, "
+ f"max deviation={s.get('ueba_max_deviation', 0.0):.2f}"
)
if s.get("threat_intel_match_count"):
parts.append(
@@ -343,7 +353,7 @@ class ContextBundle(BaseModel):
def summary_for_llm(self) -> dict[str, Any]:
"""Pre-digested, contract-safe summary for LLM prompts.
- Every key returned here is on ``LLM_SAFE_KEYS`` and contains either
+ Every key returned here is on ``_LLM_SAFE_KEYS`` and contains either
a scalar, a small list of scalars, or a list of short string summaries
— never raw OCSF / log payloads. ``LLMInputContract`` (T2.3) treats
the output of this method as the canonical safe shape.
@@ -353,9 +363,15 @@ class ContextBundle(BaseModel):
+ (f", blast_radius={nbr.blast_radius_score:.2f}" if nbr.blast_radius_score is not None else "")
for key, nbr in sorted(self.entity_neighborhoods.items())
]
- blast_scores = [n.blast_radius_score for n in self.entity_neighborhoods.values() if n.blast_radius_score is not None]
+ blast_scores = [
+ n.blast_radius_score
+ for n in self.entity_neighborhoods.values()
+ if n.blast_radius_score is not None
+ ]
ueba_devs = [b.deviation_score for b in self.peer_baselines.values()]
- high_risk = sorted(ti.ioc for ti in self.threat_intel.values() if ti.risk == "high")
+ high_risk = sorted(
+ ti.ioc for ti in self.threat_intel.values() if ti.risk == "high"
+ )
ti_sources: set[str] = set()
for ti in self.threat_intel.values():
ti_sources.update(ti.sources)
@@ -420,7 +436,7 @@ def _ti_sources(payload: dict[str, Any]) -> list[str]:
if isinstance(sources, list):
return [str(s) for s in sources][:10]
if isinstance(sources, dict):
- return sorted(sources.keys())[:10]
+ return list(sorted(sources.keys()))[:10]
return []
@@ -444,7 +460,9 @@ class ContextBundleBuilder:
per_source_timeout: float = 3.5,
api_token: str | None = None,
) -> None:
- self.depth = depth if depth is not None else int(os.getenv("AISOC_CONTEXT_BUNDLE_DEPTH", str(self.DEFAULT_DEPTH)))
+ self.depth = depth if depth is not None else int(
+ os.getenv("AISOC_CONTEXT_BUNDLE_DEPTH", str(self.DEFAULT_DEPTH))
+ )
self.max_neighborhood_nodes = max_neighborhood_nodes
self.history_limit = history_limit
self.ti_concurrency = ti_concurrency
@@ -521,7 +539,9 @@ class ContextBundleBuilder:
# Source fetchers — each returns its own slice of the bundle
# ------------------------------------------------------------------
- async def _fetch_neighborhoods(self, entities: list[EntityRef]) -> dict[str, EntityNeighborhood]:
+ async def _fetch_neighborhoods(
+ self, entities: list[EntityRef]
+ ) -> dict[str, EntityNeighborhood]:
"""Walk the graph for each principal entity, depth-N."""
# Lazy import so ``services/agents`` modules without the API tool
# installed (e.g. eval harness) can still import this builder.
@@ -547,7 +567,10 @@ class ContextBundleBuilder:
blast = None
if isinstance(blast_payload, dict):
blast = blast_payload.get("blast_radius_score")
- summary = f"{len(nodes)} neighbors at depth {self.depth}" + (f", blast_radius={float(blast):.2f}" if blast is not None else "")
+ summary = (
+ f"{len(nodes)} neighbors at depth {self.depth}"
+ + (f", blast_radius={float(blast):.2f}" if blast is not None else "")
+ )
return entity.key, EntityNeighborhood(
entity=entity,
depth=self.depth,
@@ -598,7 +621,11 @@ class ContextBundleBuilder:
if not isinstance(value, dict):
value = {}
row_tags = {str(t).lower() for t in (row.get("tags") or [])}
- jaccard = len(own_set & row_tags) / max(1, len(own_set | row_tags)) if own_set or row_tags else 0.0
+ jaccard = (
+ len(own_set & row_tags) / max(1, len(own_set | row_tags))
+ if own_set or row_tags
+ else 0.0
+ )
out.append(
HistoricalCase(
key=str(row.get("key", "")),
@@ -628,7 +655,9 @@ class ContextBundleBuilder:
raise RuntimeError(f"httpx unavailable: {exc}") from exc
ueba_url = os.getenv("AISOC_UEBA_URL", "http://ueba:8086")
- principals = [e for e in entities if e.type in ("user", "email", "host", "ip")]
+ principals = [
+ e for e in entities if e.type in ("user", "email", "host", "ip")
+ ]
if not principals:
self._record_source("ueba")
return {}
@@ -636,7 +665,6 @@ class ContextBundleBuilder:
out: dict[str, UEBABaseline] = {}
async with httpx.AsyncClient(timeout=self.per_source_timeout) as client:
-
async def _one(entity: EntityRef) -> tuple[str, UEBABaseline] | None:
# The UEBA list endpoint takes tenant + entity_type, then we
# filter client-side. We accept that this is over-fetching
@@ -677,14 +705,18 @@ class ContextBundleBuilder:
self._record_source("ueba")
return out
- async def _fetch_threat_intel(self, entities: list[EntityRef]) -> dict[str, ThreatIntelMatch]:
+ async def _fetch_threat_intel(
+ self, entities: list[EntityRef]
+ ) -> dict[str, ThreatIntelMatch]:
"""Bulk-enrich every IOC-shaped entity in the alert."""
try:
from app.tools.enrichment import bulk_enrich_iocs
except Exception as exc: # noqa: BLE001
raise RuntimeError(f"enrichment tool unavailable: {exc}") from exc
- ioc_entities = [e for e in entities if e.type in ("ip", "domain", "hash", "url")]
+ ioc_entities = [
+ e for e in entities if e.type in ("ip", "domain", "hash", "url")
+ ]
if not ioc_entities:
self._record_source("threat_intel")
return {}
@@ -723,7 +755,7 @@ class ContextBundleBuilder:
"""Run ``coro`` with a per-source timeout; record errors instead of raising."""
try:
return await asyncio.wait_for(coro, timeout=self.per_source_timeout)
- except TimeoutError:
+ except asyncio.TimeoutError:
bundle.errors.append(f"{name}:timeout")
return None
except Exception as exc: # noqa: BLE001
diff --git a/services/agents/app/llm/contract.py b/services/agents/app/llm/contract.py
index 84c45ef96..946c455cc 100644
--- a/services/agents/app/llm/contract.py
+++ b/services/agents/app/llm/contract.py
@@ -223,7 +223,9 @@ def classify_message(content: str, *, role: str = "user") -> str | None:
elif isinstance(parsed, list) and parsed:
head = parsed[0]
if isinstance(head, dict):
- if len(head) > _MAX_JSON_LINE_KEYS and (_looks_like_ocsf(head) or _looks_like_raw_log(head)):
+ if len(head) > _MAX_JSON_LINE_KEYS and (
+ _looks_like_ocsf(head) or _looks_like_raw_log(head)
+ ):
return "raw event array detected (looks like log batch)"
return None
diff --git a/services/agents/app/orchestrator/router.py b/services/agents/app/orchestrator/router.py
index 49f13fa61..abc5c30c3 100644
--- a/services/agents/app/orchestrator/router.py
+++ b/services/agents/app/orchestrator/router.py
@@ -241,15 +241,15 @@ def _resolve_runner(name: str) -> _SubAgentRunner:
agents_pkg = importlib.import_module("app.agents")
if name == "auto_triage":
- return agents_pkg.run_auto_triage
+ return getattr(agents_pkg, "run_auto_triage")
if name == "phishing":
- return agents_pkg.run_phishing
+ return getattr(agents_pkg, "run_phishing")
if name == "identity":
- return agents_pkg.run_identity
+ return getattr(agents_pkg, "run_identity")
if name == "cloud":
- return agents_pkg.run_cloud
+ return getattr(agents_pkg, "run_cloud")
if name == "insider":
- return agents_pkg.run_insider_threat
+ return getattr(agents_pkg, "run_insider_threat")
raise KeyError(f"Unknown sub-agent capability: {name}")
@@ -380,7 +380,10 @@ async def _run_parallel(state: InvestigationState, signals: list[str]) -> Invest
copy.iteration_count = state.iteration_count
branch_inputs.append(copy)
- coros = [_resolve_runner(name)(branch_inputs[idx]) for idx, name in enumerate(signals)]
+ coros = [
+ _resolve_runner(name)(branch_inputs[idx])
+ for idx, name in enumerate(signals)
+ ]
branch_results = await asyncio.gather(*coros, return_exceptions=True)
successful: list[InvestigationState] = []
diff --git a/services/agents/tests/fidelity/cicids_loader.py b/services/agents/tests/fidelity/cicids_loader.py
index 2d2eddacc..6f14f7a36 100644
--- a/services/agents/tests/fidelity/cicids_loader.py
+++ b/services/agents/tests/fidelity/cicids_loader.py
@@ -25,7 +25,7 @@ import csv
import ipaddress
import logging
from collections.abc import Iterable, Iterator
-from datetime import UTC, datetime
+from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -46,10 +46,13 @@ _LABEL_ALIASES: dict[str, str] = {
"SSH-PATATOR": "brute_force",
"BOT": "bot",
"WEB ATTACK – BRUTE FORCE": "web_attack",
+ "WEB ATTACK \u2013 BRUTE FORCE": "web_attack",
"WEB ATTACK - BRUTE FORCE": "web_attack",
"WEB ATTACK – XSS": "web_attack",
+ "WEB ATTACK \u2013 XSS": "web_attack",
"WEB ATTACK - XSS": "web_attack",
"WEB ATTACK – SQL INJECTION": "web_attack",
+ "WEB ATTACK \u2013 SQL INJECTION": "web_attack",
"WEB ATTACK - SQL INJECTION": "web_attack",
"INFILTRATION": "infiltration",
"HEARTBLEED": "exploit",
@@ -170,13 +173,13 @@ def _parse_timestamp(value: str) -> str:
text = (value or "").strip()
if not text:
- return datetime.now(UTC).isoformat()
+ return datetime.now(timezone.utc).isoformat()
for fmt in ("%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M", "%Y-%m-%d %H:%M:%S"):
try:
parsed = datetime.strptime(text, fmt)
except ValueError:
continue
- return parsed.replace(tzinfo=UTC).isoformat()
+ return parsed.replace(tzinfo=timezone.utc).isoformat()
return text
@@ -221,7 +224,9 @@ def to_ocsf(row: dict[str, Any]) -> dict[str, Any]:
"""
bytes_in = int(max(row.get("flow_bytes_per_sec", 0.0), 0.0))
- packets_total = int(row.get("total_fwd_packets", 0)) + int(row.get("total_bwd_packets", 0))
+ packets_total = int(row.get("total_fwd_packets", 0)) + int(
+ row.get("total_bwd_packets", 0)
+ )
return {
"category_uid": 4,
diff --git a/services/agents/tests/fidelity/ctu13_loader.py b/services/agents/tests/fidelity/ctu13_loader.py
index 8b21b5189..4ad35345c 100644
--- a/services/agents/tests/fidelity/ctu13_loader.py
+++ b/services/agents/tests/fidelity/ctu13_loader.py
@@ -24,7 +24,7 @@ import csv
import ipaddress
import logging
from collections.abc import Iterator
-from datetime import UTC, datetime
+from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -102,7 +102,7 @@ def _coerce_ip(value: str) -> str:
def _parse_timestamp(value: str) -> str:
text = (value or "").strip()
if not text:
- return datetime.now(UTC).isoformat()
+ return datetime.now(timezone.utc).isoformat()
for fmt in (
"%Y/%m/%d %H:%M:%S.%f",
"%Y-%m-%d %H:%M:%S.%f",
@@ -113,7 +113,7 @@ def _parse_timestamp(value: str) -> str:
parsed = datetime.strptime(text, fmt)
except ValueError:
continue
- return parsed.replace(tzinfo=UTC).isoformat()
+ return parsed.replace(tzinfo=timezone.utc).isoformat()
return text
diff --git a/services/agents/tests/fidelity/runner.py b/services/agents/tests/fidelity/runner.py
index 7a7eee68d..e0bfd1cd0 100644
--- a/services/agents/tests/fidelity/runner.py
+++ b/services/agents/tests/fidelity/runner.py
@@ -224,7 +224,10 @@ class FidelityResult:
"rows_skipped": self.rows_skipped,
"accuracy": round(self.accuracy, 4),
"macro_f1": round(self.macro_f1, 4),
- "per_family": {family: {k: round(v, 4) for k, v in metrics.items()} for family, metrics in self.per_family.items()},
+ "per_family": {
+ family: {k: round(v, 4) for k, v in metrics.items()}
+ for family, metrics in self.per_family.items()
+ },
"confusion_matrix": self.confusion_matrix,
}
@@ -240,11 +243,23 @@ def _per_family_metrics(cm: ConfusionMatrix) -> dict[str, dict[str, float]]:
out: dict[str, dict[str, float]] = {}
for label in cm.labels:
tp = cm.matrix.get(label, {}).get(label, 0)
- fp = sum(cm.matrix.get(other, {}).get(label, 0) for other in cm.labels if other != label)
- fn = sum(cm.matrix.get(label, {}).get(other, 0) for other in cm.labels if other != label)
+ fp = sum(
+ cm.matrix.get(other, {}).get(label, 0)
+ for other in cm.labels
+ if other != label
+ )
+ fn = sum(
+ cm.matrix.get(label, {}).get(other, 0)
+ for other in cm.labels
+ if other != label
+ )
precision = tp / (tp + fp) if (tp + fp) else 0.0
recall = tp / (tp + fn) if (tp + fn) else 0.0
- f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0
+ f1 = (
+ 2 * precision * recall / (precision + recall)
+ if (precision + recall)
+ else 0.0
+ )
support = tp + fn
out[label] = {
"precision": precision,
@@ -337,7 +352,9 @@ def evaluate(
ocsf_event = _to_ocsf(dataset, row)
if mode == "wet":
if not endpoint:
- raise RuntimeError("wet mode requires --wet-endpoint or AISOC_WET_EVAL_ENDPOINT")
+ raise RuntimeError(
+ "wet mode requires --wet-endpoint or AISOC_WET_EVAL_ENDPOINT"
+ )
predicted = _classify_wet(ocsf_event, endpoint)
else:
predicted = classifier(row)
diff --git a/services/agents/tests/test_context_bundle.py b/services/agents/tests/test_context_bundle.py
index 7a6bfa20a..05d5b35fd 100644
--- a/services/agents/tests/test_context_bundle.py
+++ b/services/agents/tests/test_context_bundle.py
@@ -44,7 +44,7 @@ from app.context import ( # noqa: E402
EntityRef,
extract_entities,
)
-from app.context.bundle import LLM_SAFE_KEYS # noqa: E402
+from app.context.bundle import _LLM_SAFE_KEYS # noqa: E402
from app.models.state import InvestigationState # noqa: E402
_DATASET_PATH = _TESTS_DIR / "eval_data" / "synthetic_incidents.json"
@@ -62,7 +62,10 @@ _BUILD_P95_LATENCY_S = 5.0
def _load_dataset() -> list[dict[str, Any]]:
if not _DATASET_PATH.exists():
- raise FileNotFoundError(f"Eval dataset missing at {_DATASET_PATH}. Run `python3 scripts/generate_eval_incidents.py` to regenerate.")
+ raise FileNotFoundError(
+ f"Eval dataset missing at {_DATASET_PATH}. "
+ "Run `python3 scripts/generate_eval_incidents.py` to regenerate."
+ )
with _DATASET_PATH.open() as f:
return json.load(f)
@@ -117,7 +120,9 @@ async def _stub_blast(*_args: Any, **_kwargs: Any) -> dict[str, Any]:
async def _stub_bulk_enrich(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
# Echo the items back with a low-risk reputation so the threat-intel
# branch of the bundle exercises its post-processing path.
- return [{**item, "risk_score": 0.0, "sources": ["stub"]} for item in items[:32]]
+ return [
+ {**item, "risk_score": 0.0, "sources": ["stub"]} for item in items[:32]
+ ]
async def _stub_institutional_search(*_args: Any, **_kwargs: Any) -> list[dict[str, Any]]:
@@ -144,7 +149,7 @@ class _FakeUEBAClient:
self._args = args
self._kwargs = kwargs
- async def __aenter__(self) -> _FakeUEBAClient:
+ async def __aenter__(self) -> "_FakeUEBAClient":
return self
async def __aexit__(self, *args: Any) -> None:
@@ -197,7 +202,7 @@ class ContextBundleSummaryTests(unittest.TestCase):
)
summary = bundle.summary_for_llm()
for key in summary:
- self.assertIn(key, LLM_SAFE_KEYS, f"unexpected key in summary_for_llm: {key}")
+ self.assertIn(key, _LLM_SAFE_KEYS, f"unexpected key in summary_for_llm: {key}")
def test_prompt_context_lines_empty_when_bundle_empty(self) -> None:
bundle = ContextBundle(incident_id=uuid4())
@@ -261,9 +266,9 @@ class ContextBundleBuildLatencyTests(unittest.TestCase):
report = (
f"\nContextBundle build latency over {len(incidents)} incidents:\n"
- f" mean={mean * 1000:.1f}ms p50={p50 * 1000:.1f}ms "
- f"p95={p95 * 1000:.1f}ms p99={p99 * 1000:.1f}ms "
- f"max={max_latency * 1000:.1f}ms\n"
+ f" mean={mean*1000:.1f}ms p50={p50*1000:.1f}ms "
+ f"p95={p95*1000:.1f}ms p99={p99*1000:.1f}ms "
+ f"max={max_latency*1000:.1f}ms\n"
f" bundles fully populated: "
f"{sum(1 for b in bundles if b.build_completed_at is not None)}/{len(bundles)}"
)
@@ -273,11 +278,13 @@ class ContextBundleBuildLatencyTests(unittest.TestCase):
self.assertLess(
p95,
_BUILD_P95_LATENCY_S,
- f"ContextBundle p95 {p95 * 1000:.1f}ms exceeds 5000ms gate",
+ f"ContextBundle p95 {p95*1000:.1f}ms exceeds 5000ms gate",
)
@staticmethod
- async def _run_all(fn: Any, incidents: list[dict[str, Any]]) -> list[tuple[ContextBundle, float]]:
+ async def _run_all(
+ fn: Any, incidents: list[dict[str, Any]]
+ ) -> list[tuple[ContextBundle, float]]:
# Fan-out is bounded so a hung incident can't cascade across the
# whole 200-case sweep. ``asyncio.gather`` keeps order.
return list(await asyncio.gather(*[fn(inc) for inc in incidents]))
diff --git a/services/agents/tests/test_eval_telemetry.py b/services/agents/tests/test_eval_telemetry.py
index d0b86a341..adc239f80 100644
--- a/services/agents/tests/test_eval_telemetry.py
+++ b/services/agents/tests/test_eval_telemetry.py
@@ -147,7 +147,9 @@ class RateCardTests(unittest.TestCase):
crash. Keeps wet-eval re-rendering robust if the rate card is
renamed mid-run."""
unknown = _eval_telemetry.cost_usd(1_000_000, 0, model="not-a-real-model")
- gpt4o = _eval_telemetry.cost_usd(1_000_000, 0, model=_eval_telemetry.DEFAULT_MODEL)
+ gpt4o = _eval_telemetry.cost_usd(
+ 1_000_000, 0, model=_eval_telemetry.DEFAULT_MODEL
+ )
self.assertAlmostEqual(unknown, gpt4o, places=6)
def test_cost_usd_accepts_custom_rate_card(self) -> None:
@@ -203,18 +205,14 @@ class ComputePerInvestigationTests(unittest.TestCase):
wet-eval column (workspace rule: never present substrate as
agent metrics)."""
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path,
- model="gpt-4o",
- keep_records=True,
+ self.incidents_path, model="gpt-4o", keep_records=True,
)
d = rep.to_dict(include_records=True)
self.assertEqual(d["mode"], "deterministic_substrate")
def test_report_counts_incidents_and_templates(self) -> None:
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path,
- model="gpt-4o",
- keep_records=True,
+ self.incidents_path, model="gpt-4o", keep_records=True,
)
self.assertEqual(rep.incidents, 3)
self.assertEqual(rep.templates, 2)
@@ -222,9 +220,7 @@ class ComputePerInvestigationTests(unittest.TestCase):
def test_report_aggregate_has_required_fields(self) -> None:
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path,
- model="gpt-4o",
- keep_records=True,
+ self.incidents_path, model="gpt-4o", keep_records=True,
)
agg = rep.aggregate
self.assertIn("tokens", agg)
@@ -240,9 +236,7 @@ class ComputePerInvestigationTests(unittest.TestCase):
percentile helper this catches it before docs ship a chart with
p99 < median."""
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path,
- model="gpt-4o",
- keep_records=True,
+ self.incidents_path, model="gpt-4o", keep_records=True,
)
for kind in ("prompt", "completion", "total"):
block = rep.aggregate["tokens"][kind]
@@ -260,9 +254,7 @@ class ComputePerInvestigationTests(unittest.TestCase):
low-severity ones. INC-FIXT-001 (critical) vs INC-FIXT-003 (low)
in the fixture."""
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path,
- model="gpt-4o",
- keep_records=True,
+ self.incidents_path, model="gpt-4o", keep_records=True,
)
by_id = {r["incident_id"]: r for r in rep.incident_records}
self.assertGreater(
@@ -272,9 +264,7 @@ class ComputePerInvestigationTests(unittest.TestCase):
def test_keep_records_false_drops_per_incident_array(self) -> None:
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path,
- model="gpt-4o",
- keep_records=False,
+ self.incidents_path, model="gpt-4o", keep_records=False,
)
self.assertEqual(rep.incident_records, [])
d = rep.to_dict(include_records=False)
@@ -285,9 +275,7 @@ class ComputePerInvestigationTests(unittest.TestCase):
incident count. Stops bucketing bugs from quietly dropping
templates."""
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path,
- model="gpt-4o",
- keep_records=True,
+ self.incidents_path, model="gpt-4o", keep_records=True,
)
total = sum(t["incidents"] for t in rep.per_template)
self.assertEqual(total, rep.incidents)
@@ -315,24 +303,18 @@ def _build_renderable_report() -> dict[str, Any]:
usd = block["aggregate"]["usd"]
latency = block["aggregate"]["latency_ms"]
block["tokens_per_investigation"] = {
- "mean": total["mean"],
- "median": total["median"],
- "p95": total["p95"],
- "p99": total["p99"],
+ "mean": total["mean"], "median": total["median"],
+ "p95": total["p95"], "p99": total["p99"],
"prompt_mean": block["aggregate"]["tokens"]["prompt"]["mean"],
"completion_mean": block["aggregate"]["tokens"]["completion"]["mean"],
}
block["usd_per_investigation"] = {
- "mean": usd["mean"],
- "median": usd["median"],
- "p95": usd["p95"],
- "p99": usd["p99"],
+ "mean": usd["mean"], "median": usd["median"],
+ "p95": usd["p95"], "p99": usd["p99"],
}
block["latency_per_investigation_ms"] = {
- "p50": latency["p50"],
- "p95": latency["p95"],
- "p99": latency["p99"],
- "mean": latency["mean"],
+ "p50": latency["p50"], "p95": latency["p95"],
+ "p99": latency["p99"], "mean": latency["mean"],
}
return {"per_investigation": block}
diff --git a/services/agents/tests/test_fidelity_harness.py b/services/agents/tests/test_fidelity_harness.py
index 6f4aa1417..62e0a90f5 100644
--- a/services/agents/tests/test_fidelity_harness.py
+++ b/services/agents/tests/test_fidelity_harness.py
@@ -36,8 +36,12 @@ import pytest
from tests.fidelity import cicids_loader, ctu13_loader, runner
REPO_ROOT = Path(__file__).resolve().parents[3]
-MICRO_FIXTURE = REPO_ROOT / "services/agents/tests/eval_data/cicids_micro.csv"
-EXPECTED_RESULTS = REPO_ROOT / "services/agents/tests/fidelity/expected_results.yaml"
+MICRO_FIXTURE = (
+ REPO_ROOT / "services/agents/tests/eval_data/cicids_micro.csv"
+)
+EXPECTED_RESULTS = (
+ REPO_ROOT / "services/agents/tests/fidelity/expected_results.yaml"
+)
def _load_expected() -> dict[str, object]:
@@ -67,11 +71,8 @@ def _load_expected() -> dict[str, object]:
def test_cicids_micro_fixture_present() -> None:
assert MICRO_FIXTURE.exists(), MICRO_FIXTURE
- # 100 flows + 1 header row. Read the file outside the assert so the file
- # handle is properly closed (CodeQL ``py/side-effect-in-assert``).
- with MICRO_FIXTURE.open("r", encoding="utf-8") as handle:
- line_count = sum(1 for _ in handle)
- assert line_count == 101
+ # 100 flows + 1 header row.
+ assert sum(1 for _ in MICRO_FIXTURE.open("r", encoding="utf-8")) == 101
def test_cicids_loader_normalises_features() -> None:
@@ -249,7 +250,9 @@ def test_wet_mode_falls_back_to_benign_on_http_failure(
# is defensive on transport errors.
assert result.rows_scored == 2
benign_predicted = sum(
- cell.get("benign", 0) for actual, cell in result.confusion_matrix["matrix"].items() if actual in result.confusion_matrix["labels"]
+ cell.get("benign", 0)
+ for actual, cell in result.confusion_matrix["matrix"].items()
+ if actual in result.confusion_matrix["labels"]
)
assert benign_predicted == 2
diff --git a/services/agents/tests/test_four_agent_facade.py b/services/agents/tests/test_four_agent_facade.py
index 5d7971dd5..3d57c04f0 100644
--- a/services/agents/tests/test_four_agent_facade.py
+++ b/services/agents/tests/test_four_agent_facade.py
@@ -48,6 +48,7 @@ from app.agents import ( # noqa: E402
)
from app.models.state import AgentStatus, InvestigationState # noqa: E402
+
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@@ -118,7 +119,9 @@ def test_triage_capabilities_are_not_top_level_agents() -> None:
# And the package's "branded" set must only contain the four names.
branded_in_pkg = {
- name for name in agents_pkg.__all__ if name.endswith("Agent") and name not in {"AutoTriageAgent", "ResponderAgent"} | forbidden
+ name
+ for name in agents_pkg.__all__
+ if name.endswith("Agent") and name not in {"AutoTriageAgent", "ResponderAgent"} | forbidden
}
assert branded_in_pkg == branded
@@ -171,7 +174,7 @@ async def test_triage_heuristic_delegates(monkeypatch: pytest.MonkeyPatch) -> No
@pytest.mark.asyncio
async def test_triage_capability_dispatch(monkeypatch: pytest.MonkeyPatch) -> None:
"""Each capability dispatches to its underlying ``run_*`` function."""
- flags = dict.fromkeys(("phishing", "identity", "cloud", "insider"), False)
+ flags = {name: False for name in ("phishing", "identity", "cloud", "insider")}
def _make_fake(name: str):
async def _runner(state: InvestigationState) -> InvestigationState:
diff --git a/services/agents/tests/test_graph_freshness.py b/services/agents/tests/test_graph_freshness.py
index 45a34f714..79823f56e 100644
--- a/services/agents/tests/test_graph_freshness.py
+++ b/services/agents/tests/test_graph_freshness.py
@@ -44,7 +44,9 @@ pytestmark = pytest.mark.integration
# Test config — env-overridable so CI can point at the dockerised stack.
INGEST_BASE_URL = os.environ.get("AISOC_INGEST_URL", "http://localhost:8080")
-KAFKA_BOOTSTRAP = os.environ.get("KAFKA_BOOTSTRAP_SERVERS", os.environ.get("KAFKA_BROKERS", "localhost:9092"))
+KAFKA_BOOTSTRAP = os.environ.get(
+ "KAFKA_BOOTSTRAP_SERVERS", os.environ.get("KAFKA_BROKERS", "localhost:9092")
+)
NEO4J_URI = os.environ.get("AISOC_NEO4J_URI", "bolt://localhost:7687")
NEO4J_USER = os.environ.get("AISOC_NEO4J_USER", "neo4j")
NEO4J_PASSWORD = os.environ.get("AISOC_NEO4J_PASSWORD", "neo4j")
@@ -59,17 +61,13 @@ def _import_or_skip(mod_name: str, hint: str) -> Any:
The integration test should be invisible on a developer laptop that
hasn't installed the stack yet — skip beats fail.
-
- ``pytest.skip()`` raises ``Skipped`` and never returns, but CodeQL
- (``py/mixed-returns``) does not model it as ``NoReturn``, so we add
- an explicit ``return None`` after it to make every control-flow path
- end in an explicit ``return``.
"""
try:
return __import__(mod_name)
except ImportError:
- pytest.skip(f"{mod_name} not installed locally — install {hint} to run this integration test")
- return None
+ pytest.skip(
+ f"{mod_name} not installed locally — install {hint} to run this integration test"
+ )
def _build_event(idx: int) -> dict:
@@ -125,7 +123,6 @@ def _ingest_event(httpx: Any, event: dict, tenant: str) -> None:
)
except Exception as exc: # noqa: BLE001
pytest.skip(f"ingest service unreachable at {INGEST_BASE_URL}: {exc}")
- return # pytest.skip raises; this satisfies static analysers that ``resp`` is always bound below
if resp.status_code >= 500:
pytest.skip(f"ingest service unhealthy: {resp.status_code} {resp.text}")
assert resp.status_code < 400, resp.text
@@ -145,7 +142,9 @@ def test_graph_freshness_p95_under_2s() -> None:
tenant = f"test-{uuid.uuid4().hex[:8]}"
try:
- driver = neo4j_pkg.GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
+ driver = neo4j_pkg.GraphDatabase.driver(
+ NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD)
+ )
driver.verify_connectivity()
except Exception as exc: # noqa: BLE001
pytest.skip(f"Neo4j unreachable at {NEO4J_URI}: {exc}")
@@ -158,9 +157,9 @@ def test_graph_freshness_p95_under_2s() -> None:
start = time.monotonic()
_ingest_event(httpx, event, tenant)
deadline = start + P95_LATENCY_BUDGET_S * 2
- assert _query_neo4j_for_resource(driver, arn, deadline), (
- f"Resource {arn} never appeared in graph within {deadline - start:.2f}s"
- )
+ assert _query_neo4j_for_resource(
+ driver, arn, deadline
+ ), f"Resource {arn} never appeared in graph within {deadline - start:.2f}s"
latencies.append(time.monotonic() - start)
finally:
driver.close()
@@ -177,7 +176,9 @@ def test_graph_freshness_p95_under_2s() -> None:
}
)
)
- assert p95 < P95_LATENCY_BUDGET_S, f"graph freshness p95={p95:.3f}s exceeds budget {P95_LATENCY_BUDGET_S}s"
+ assert p95 < P95_LATENCY_BUDGET_S, (
+ f"graph freshness p95={p95:.3f}s exceeds budget {P95_LATENCY_BUDGET_S}s"
+ )
def test_graph_writer_does_not_block_fusion_on_failure() -> None:
@@ -210,9 +211,10 @@ def test_graph_writer_does_not_block_fusion_on_failure() -> None:
)
except Exception as exc: # noqa: BLE001
pytest.skip(f"ingest service unreachable at {INGEST_BASE_URL}: {exc}")
- return # pytest.skip raises; satisfies static analysers that ``resp`` is bound below
- assert resp.status_code < 400, f"ingest returned {resp.status_code} — fusion should never block on graph: {resp.text}"
+ assert resp.status_code < 400, (
+ f"ingest returned {resp.status_code} — fusion should never block on graph: {resp.text}"
+ )
# TODO(T1.1+): expand to the 360-event synthetic corpus referenced in the
diff --git a/services/agents/tests/test_latency.py b/services/agents/tests/test_latency.py
index c78be4acf..c92caa6a4 100644
--- a/services/agents/tests/test_latency.py
+++ b/services/agents/tests/test_latency.py
@@ -176,8 +176,12 @@ async def test_parallel_topology_latency_substrate(monkeypatch: pytest.MonkeyPat
f"\n p95 = {p95_ms:.2f} ms"
f"\n p99 = {p99_ms:.2f} ms"
f"\n mean = {mean_ms:.2f} ms"
- f"\n budget: p50 < {P50_BUDGET_SECONDS * 1000:.0f} ms, p95 < {P95_BUDGET_SECONDS * 1000:.0f} ms (substrate)"
+ f"\n budget: p50 < {P50_BUDGET_SECONDS*1000:.0f} ms, p95 < {P95_BUDGET_SECONDS*1000:.0f} ms (substrate)"
)
- assert p50_ms < P50_BUDGET_SECONDS * 1000.0, f"p50 substrate latency over budget: {p50_ms:.2f} ms >= {P50_BUDGET_SECONDS * 1000:.0f} ms"
- assert p95_ms < P95_BUDGET_SECONDS * 1000.0, f"p95 substrate latency over budget: {p95_ms:.2f} ms >= {P95_BUDGET_SECONDS * 1000:.0f} ms"
+ assert p50_ms < P50_BUDGET_SECONDS * 1000.0, (
+ f"p50 substrate latency over budget: {p50_ms:.2f} ms >= {P50_BUDGET_SECONDS*1000:.0f} ms"
+ )
+ assert p95_ms < P95_BUDGET_SECONDS * 1000.0, (
+ f"p95 substrate latency over budget: {p95_ms:.2f} ms >= {P95_BUDGET_SECONDS*1000:.0f} ms"
+ )
diff --git a/services/agents/tests/test_llm_resolver.py b/services/agents/tests/test_llm_resolver.py
index 5bbbe5c54..92c14458c 100644
--- a/services/agents/tests/test_llm_resolver.py
+++ b/services/agents/tests/test_llm_resolver.py
@@ -459,18 +459,6 @@ def _stub_ledger(monkeypatch: pytest.MonkeyPatch, pool: MagicMock | None) -> Non
if parent is not None:
monkeypatch.setattr(parent, "ledger", ledger, raising=False)
- # If another test (e.g. ``test_audit_helpers``) previously loaded the
- # real ``app.investigator`` package, its ``__init__`` ran
- # ``from .orchestrator import …``, which transitively executed
- # ``from . import ledger`` and bound the *real* ledger module as the
- # ``ledger`` attribute on the package object. Python's
- # ``from app.investigator import ledger as _ledger`` resolves that
- # attribute first and only falls back to ``sys.modules`` when the
- # attribute is missing — so swapping ``sys.modules`` is not enough.
- # Force the attribute to our stub so the resolver consumes it.
- pkg_obj = sys.modules[pkg_name]
- monkeypatch.setattr(pkg_obj, "ledger", ledger, raising=False)
-
class TestResolveWithTenant:
@pytest.mark.asyncio
diff --git a/services/api/app/api/v1/endpoints/attack_chain.py b/services/api/app/api/v1/endpoints/attack_chain.py
index 9868aa81f..23f665e7c 100644
--- a/services/api/app/api/v1/endpoints/attack_chain.py
+++ b/services/api/app/api/v1/endpoints/attack_chain.py
@@ -68,7 +68,11 @@ async def get_attack_chain(
# but a future schema change could relax that — fail closed.
raise HTTPException(status_code=400, detail=f"unknown window: {window}")
- case_row = (await db.execute(select(Case).where(Case.id == case_id, Case.tenant_id == user.tenant_id))).scalar_one_or_none()
+ case_row = (
+ await db.execute(
+ select(Case).where(Case.id == case_id, Case.tenant_id == user.tenant_id)
+ )
+ ).scalar_one_or_none()
if case_row is None:
raise HTTPException(status_code=404, detail="case_not_found")
@@ -78,7 +82,10 @@ async def get_attack_chain(
# case still resolves.
seed_alert_id: uuid.UUID | None = None
if case_row.alert_ids:
- candidate_ids = [uuid.UUID(str(a)) if not isinstance(a, uuid.UUID) else a for a in case_row.alert_ids]
+ candidate_ids = [
+ uuid.UUID(str(a)) if not isinstance(a, uuid.UUID) else a
+ for a in case_row.alert_ids
+ ]
seed_row = (
await db.execute(
select(Alert)
@@ -140,7 +147,7 @@ async def get_attack_chain(
text(
"""
INSERT INTO aisoc_attack_chains (
- tenant_id, seed_alert_id, case_id, time_window,
+ tenant_id, seed_alert_id, case_id, window,
chain, entity_graph, chain_signature, confidence,
updated_at
) VALUES (
@@ -148,7 +155,7 @@ async def get_attack_chain(
CAST(:chain AS JSONB), CAST(:entity_graph AS JSONB),
:signature, :confidence, NOW()
)
- ON CONFLICT (tenant_id, seed_alert_id, time_window, chain_signature)
+ ON CONFLICT (tenant_id, seed_alert_id, window, chain_signature)
DO UPDATE SET
case_id = EXCLUDED.case_id,
chain = EXCLUDED.chain,
diff --git a/services/api/app/api/v1/endpoints/business_context.py b/services/api/app/api/v1/endpoints/business_context.py
index 0e83fce6c..2a694dc4f 100644
--- a/services/api/app/api/v1/endpoints/business_context.py
+++ b/services/api/app/api/v1/endpoints/business_context.py
@@ -97,7 +97,7 @@ class RuleConditionWire(BaseModel):
op: str | None = None
value: Any = None
logical: str | None = None
- children: list[RuleConditionWire] = Field(default_factory=list)
+ children: list["RuleConditionWire"] = Field(default_factory=list)
class RuleActionWire(BaseModel):
@@ -455,7 +455,10 @@ async def update_rule(
if new_rule.id != rule_id:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
- detail=(f"rule id in URL ({rule_id!r}) must match rule id in body ({new_rule.id!r})"),
+ detail=(
+ f"rule id in URL ({rule_id!r}) must match rule id in body "
+ f"({new_rule.id!r})"
+ ),
)
existing_yaml = _load_for(user.tenant_id)["yaml"]
@@ -550,7 +553,9 @@ async def preview_rules(
alerts = alerts[:_MAX_PREVIEW_ALERTS]
start = time.perf_counter()
- evaluations = _engine().preview_against(user.tenant_id, alerts, rules=rules)
+ evaluations = _engine().preview_against(
+ user.tenant_id, alerts, rules=rules
+ )
elapsed_ms = (time.perf_counter() - start) * 1000
rows = [
diff --git a/services/api/app/api/v1/endpoints/effective_permissions.py b/services/api/app/api/v1/endpoints/effective_permissions.py
index ab6b92dd2..a61ec86ff 100644
--- a/services/api/app/api/v1/endpoints/effective_permissions.py
+++ b/services/api/app/api/v1/endpoints/effective_permissions.py
@@ -87,7 +87,8 @@ async def get_effective_permissions(
snapshot_b64: str | None = Query(
None,
description=(
- "Optional base64-encoded JSON snapshot for dry-run resolution. Only honoured when AISOC_ALLOW_INLINE_SNAPSHOT=1 is set."
+ "Optional base64-encoded JSON snapshot for dry-run resolution. "
+ "Only honoured when AISOC_ALLOW_INLINE_SNAPSHOT=1 is set."
),
),
_user: User = Depends(get_current_user),
@@ -101,7 +102,10 @@ async def get_effective_permissions(
if provider not in SUPPORTED_PROVIDERS:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
- detail=(f"unknown provider {provider!r}; supported: {sorted(SUPPORTED_PROVIDERS)}"),
+ detail=(
+ f"unknown provider {provider!r}; "
+ f"supported: {sorted(SUPPORTED_PROVIDERS)}"
+ ),
)
snapshot: dict[str, Any] | None = None
@@ -109,7 +113,8 @@ async def get_effective_permissions(
if os.getenv(_INLINE_SNAPSHOT_FLAG, "0") != "1":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
- detail=f"inline snapshots are disabled; set {_INLINE_SNAPSHOT_FLAG}=1 to dry-run.",
+ detail="inline snapshots are disabled; set "
+ f"{_INLINE_SNAPSHOT_FLAG}=1 to dry-run.",
)
try:
snapshot = json.loads(base64.b64decode(snapshot_b64).decode("utf-8"))
diff --git a/services/api/app/api/v1/endpoints/graph_ws.py b/services/api/app/api/v1/endpoints/graph_ws.py
new file mode 100644
index 000000000..8e52d7538
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/graph_ws.py
@@ -0,0 +1,309 @@
+"""Public-facing WebSocket proxy for graph-update streaming (T1.4 — v8.0).
+
+The browser opens ``wss://api.../v1/graph_ws/stream`` with the user's
+session bearer token. This endpoint authenticates the token, derives
+the tenant_id from the resolved user, then dials the *internal*
+ingest broadcaster at ``$AISOC_INGEST_GRAPH_WS_URL`` with the
+tenant_id bound in the URL. Every envelope the upstream sends is
+relayed verbatim to the browser; the browser cannot subscribe to
+another tenant because the proxy controls the upstream URL.
+
+Why a proxy and not direct?
+---------------------------
+Two reasons:
+
+ 1. **Auth boundary.** The ingest WebSocket runs on the internal
+ service network and has no notion of users. The API service
+ already owns the auth path (``app.api.v1.deps.get_current_user``)
+ and the RBAC model. Re-implementing JWT/API-key validation
+ inside the Go broadcaster would duplicate state and risk drift.
+ 2. **Tenant binding.** A browser-facing endpoint that respects an
+ attacker-supplied ``?tenant_id=...`` query param is a
+ cross-tenant leak waiting to happen. We rebind the tenant
+ server-side from ``current_user.tenant_id``.
+
+Registration
+------------
+The matching router-include lives in
+``services/api/app/api/v1/router.py``.
+
+Permission gate
+---------------
+``graph:read`` — same scope used by the relational /graph endpoints.
+We do not introduce a new permission; the live tail surfaces the
+same data the user can already query.
+
+Failure modes
+-------------
+* Upstream unreachable → 1011 close, structured log.
+* Auth fails → 401 close before upgrade.
+* Tenant_id missing from CurrentUser → 403.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+import uuid
+from typing import Annotated, Any
+from urllib.parse import quote, urlsplit, urlunsplit
+
+import httpx
+from fastapi import (
+ APIRouter,
+ Depends,
+ HTTPException,
+ Query,
+ WebSocket,
+ WebSocketDisconnect,
+ status,
+)
+from jose import JWTError
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.v1.deps import CurrentUser, _resolve_api_key
+from app.api.v1.dev_auth import (
+ DEMO_TENANT_ID,
+ DEMO_USER_EMAIL,
+ DEMO_USER_ID,
+ DEMO_USER_ROLE,
+ is_dev_mode,
+)
+from app.core.security import decode_token
+from app.db.database import get_db
+from app.models.tenant import User
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/graph_ws", tags=["graph", "realtime"])
+
+# Default upstream — matches the ingest binary's default port (8080)
+# and the route registered by services/ingest/internal/server/server.go.
+# Operators override per-deployment with AISOC_INGEST_GRAPH_WS_URL,
+# e.g. ws://ingest.aisoc.svc.cluster.local:8080/v1/graph_ws/stream.
+_DEFAULT_UPSTREAM = "ws://ingest:8080/v1/graph_ws/stream"
+
+
+def _upstream_url(tenant_id: uuid.UUID) -> str:
+ """Build the upstream URL with the resolved tenant bound."""
+
+ base = os.environ.get("AISOC_INGEST_GRAPH_WS_URL", _DEFAULT_UPSTREAM)
+ parts = urlsplit(base)
+ qs = parts.query
+ binding = f"tenant_id={quote(str(tenant_id), safe='')}"
+ qs = f"{qs}&{binding}" if qs else binding
+ return urlunsplit((parts.scheme, parts.netloc, parts.path, qs, parts.fragment))
+
+
+async def _authenticate_ws(
+ websocket: WebSocket,
+ token: str | None,
+ db: AsyncSession,
+) -> CurrentUser | None:
+ """Resolve a CurrentUser from a websocket token query param.
+
+ FastAPI's ``Depends(get_current_user)`` only works for HTTP — for
+ WebSocket connections we have to do the resolution by hand because
+ the upgrade response cannot carry a ``WWW-Authenticate`` header
+ and the bearer-scheme middleware sees no Authorization header on
+ the upgrade. We reuse the same helpers ``get_current_user`` uses
+ so the auth contract is identical.
+
+ Returns ``None`` after closing the websocket on failure.
+ """
+
+ if not token:
+ if is_dev_mode():
+ return CurrentUser(
+ user_id=DEMO_USER_ID,
+ tenant_id=DEMO_TENANT_ID,
+ role=DEMO_USER_ROLE,
+ email=DEMO_USER_EMAIL,
+ )
+ await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="not authenticated")
+ return None
+
+ # API key path
+ if token.startswith("aisoc_"):
+ try:
+ return await _resolve_api_key(token, db)
+ except HTTPException as exc:
+ await websocket.close(
+ code=status.WS_1008_POLICY_VIOLATION,
+ reason=str(exc.detail)[:120],
+ )
+ return None
+
+ # JWT path
+ try:
+ payload = decode_token(token)
+ except JWTError:
+ await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="invalid token")
+ return None
+ sub = payload.get("sub")
+ token_type = payload.get("type", "access")
+ if not sub or token_type != "access":
+ await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="invalid token")
+ return None
+ try:
+ user_uuid = uuid.UUID(sub)
+ except ValueError:
+ await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="invalid subject")
+ return None
+ result = await db.execute(select(User).where(User.id == user_uuid, User.is_active.is_(True)))
+ user = result.scalar_one_or_none()
+ if user is None:
+ await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="user not found")
+ return None
+ return CurrentUser(
+ user_id=user.id,
+ tenant_id=user.tenant_id,
+ role=user.role,
+ email=user.email,
+ )
+
+
+async def graph_updates_stream(
+ websocket: WebSocket,
+ token: Annotated[str | None, Query()] = None,
+ db: AsyncSession = Depends(get_db),
+) -> None:
+ """WebSocket: live graph-update stream scoped to the caller's tenant.
+
+ The browser opens this with a ``?token=<jwt|api_key>`` query
+ parameter (browsers can't set ``Authorization`` headers on a
+ WebSocket open). After authentication, the connection is proxied
+ to the internal ingest broadcaster with ``tenant_id`` bound from
+ the resolved user — the client cannot influence which tenant they
+ subscribe to.
+
+ Closes with policy-violation if auth fails. Closes with
+ internal-error if the upstream is unreachable.
+ """
+
+ await websocket.accept()
+ user = await _authenticate_ws(websocket, token, db)
+ if user is None:
+ return
+
+ # Enforce the ``graph:read`` permission — same scope as the
+ # relational graph endpoints.
+ try:
+ user.require_permission("graph:read")
+ except HTTPException as exc:
+ await websocket.close(
+ code=status.WS_1008_POLICY_VIOLATION,
+ reason=str(exc.detail)[:120],
+ )
+ return
+
+ upstream_url = _upstream_url(user.tenant_id)
+ logger.info(
+ "graph_ws: proxying for tenant=%s upstream=%s user=%s",
+ user.tenant_id,
+ _redact_url(upstream_url),
+ user.email,
+ )
+
+ try:
+ await _relay(websocket, upstream_url)
+ except WebSocketDisconnect:
+ logger.debug("graph_ws: client disconnected tenant=%s", user.tenant_id)
+ except Exception as exc: # pragma: no cover — defensive
+ logger.warning(
+ "graph_ws: relay error tenant=%s err=%s",
+ user.tenant_id,
+ exc,
+ )
+ try:
+ await websocket.close(code=status.WS_1011_INTERNAL_ERROR, reason="upstream error")
+ except RuntimeError:
+ pass
+
+
+async def _relay(websocket: WebSocket, upstream_url: str) -> None:
+ """Pipe envelopes from the internal broadcaster to the browser.
+
+ We use ``httpx`` for the upstream WebSocket because the existing
+ API service already depends on httpx. The implementation is
+ deliberately stripped-down: we only need server→client streaming,
+ not bidirectional message passing.
+ """
+
+ # httpx's WebSocket API is exposed via ``httpx.AsyncClient`` +
+ # ``ws_connect``; the import sits inside the function so a
+ # production environment that lacks the optional ws extras still
+ # imports the module successfully (the WS endpoint just becomes
+ # 503 at connect time).
+ try:
+ from httpx_ws import aconnect_ws # type: ignore[import-not-found]
+ except ImportError:
+ await websocket.close(
+ code=status.WS_1011_INTERNAL_ERROR,
+ reason="server missing httpx-ws extra",
+ )
+ return
+
+ try:
+ async with aconnect_ws(upstream_url) as upstream:
+ done: asyncio.Event = asyncio.Event()
+
+ async def client_to_upstream() -> None:
+ try:
+ while not done.is_set():
+ # The browser is read-only for this stream;
+ # we still drain frames so a polite client
+ # close propagates cleanly.
+ msg = await websocket.receive()
+ if msg.get("type") == "websocket.disconnect":
+ return
+ except WebSocketDisconnect:
+ return
+ except Exception: # pragma: no cover
+ return
+
+ async def upstream_to_client() -> None:
+ try:
+ while not done.is_set():
+ envelope = await upstream.receive_text()
+ await websocket.send_text(envelope)
+ except Exception:
+ return
+
+ tasks = [
+ asyncio.create_task(client_to_upstream()),
+ asyncio.create_task(upstream_to_client()),
+ ]
+ try:
+ await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
+ finally:
+ done.set()
+ for t in tasks:
+ if not t.done():
+ t.cancel()
+ try:
+ await t
+ except (asyncio.CancelledError, Exception):
+ pass
+ except httpx.HTTPError as exc:
+ logger.warning("graph_ws: upstream dial failed url=%s err=%s", _redact_url(upstream_url), exc)
+ await websocket.close(code=status.WS_1011_INTERNAL_ERROR, reason="upstream unreachable")
+ except Exception as exc: # pragma: no cover — defensive
+ logger.warning("graph_ws: upstream error url=%s err=%s", _redact_url(upstream_url), exc)
+ try:
+ await websocket.close(code=status.WS_1011_INTERNAL_ERROR, reason="upstream error")
+ except RuntimeError:
+ pass
+
+
+def _redact_url(url: str) -> str:
+ """Drop the query string from a URL before logging."""
+
+ parts = urlsplit(url)
+ return urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
+
+
+__all__: list[Any] = ["router"]
diff --git a/services/api/app/api/v1/endpoints/insights.py b/services/api/app/api/v1/endpoints/insights.py
index 26719ffd6..b08296403 100644
--- a/services/api/app/api/v1/endpoints/insights.py
+++ b/services/api/app/api/v1/endpoints/insights.py
@@ -117,7 +117,10 @@ class InsightTile(BaseModel):
)
)
previous_value: float = Field(
- description=("Value of the same metric over the immediately preceding window of equal length. Used to compute the delta.")
+ description=(
+ "Value of the same metric over the immediately preceding "
+ "window of equal length. Used to compute the delta."
+ )
)
delta_pct: float | None = Field(
default=None,
@@ -185,7 +188,9 @@ async def _mean_hours(
end_col.isnot(None),
]
filters.extend(extra_filters)
- result = await db.scalar(select(func.avg(func.extract("epoch", end_col - start_col) / 3600)).where(and_(*filters)))
+ result = await db.scalar(
+ select(func.avg(func.extract("epoch", end_col - start_col) / 3600)).where(and_(*filters))
+ )
return round(float(result or 0.0), 2)
@@ -315,15 +320,11 @@ async def _llm_cost_aggregate(
)
try:
row = (
- (
- await db.execute(
- sql,
- {"tenant_id": str(tenant_id), "start_at": start, "end_at": end},
- )
+ await db.execute(
+ sql,
+ {"tenant_id": str(tenant_id), "start_at": start, "end_at": end},
)
- .mappings()
- .first()
- )
+ ).mappings().first()
if not row:
return 0.0, 0
return float(row["cost"] or 0.0), int(row["runs"] or 0)
diff --git a/services/api/app/api/v1/endpoints/saved_hunts.py b/services/api/app/api/v1/endpoints/saved_hunts.py
index 40110a39b..c10d91946 100644
--- a/services/api/app/api/v1/endpoints/saved_hunts.py
+++ b/services/api/app/api/v1/endpoints/saved_hunts.py
@@ -51,15 +51,16 @@ from sqlalchemy import and_, delete, select, update
from sqlalchemy.exc import IntegrityError
from app.api.v1.deps import AuthUser
+from app.db.rls import TenantDBSession
+from app.models.saved_hunt import SavedHunt
# Defer import of the NL translator helpers — `nl_query.py` already does the
# vendored-tree resolution dance at import time and we want the same module
# instance so a future LLM enhancement applies uniformly.
from app.api.v1.endpoints.nl_query import ( # noqa: E402
+ NLQuery,
deterministic_translate,
)
-from app.db.rls import TenantDBSession
-from app.models.saved_hunt import SavedHunt
logger = structlog.get_logger()
@@ -270,7 +271,13 @@ async def list_saved_hunts(
first; the UI renders this list as the "Saved hunts" sidebar.
"""
rows = (
- (await db.execute(select(SavedHunt).where(SavedHunt.tenant_id == user.tenant_id).order_by(SavedHunt.updated_at.desc())))
+ (
+ await db.execute(
+ select(SavedHunt)
+ .where(SavedHunt.tenant_id == user.tenant_id)
+ .order_by(SavedHunt.updated_at.desc())
+ )
+ )
.scalars()
.all()
)
diff --git a/services/api/app/api/v1/endpoints/tenant_provision.py b/services/api/app/api/v1/endpoints/tenant_provision.py
index d9887573a..dda58b18a 100644
--- a/services/api/app/api/v1/endpoints/tenant_provision.py
+++ b/services/api/app/api/v1/endpoints/tenant_provision.py
@@ -1,7 +1,5 @@
"""Admin tenant-provisioning endpoints — T6.1 (`app.aisoc.dev` managed beta).
-# TODO(T6.1): wire into v1 router after Subagent A's stabilization push lands.
-
Exposes the bridge between the waitlist (built in commit 1 of this
work) and the live ``tenants`` table:
@@ -43,8 +41,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.deps import AuthUser, DBSession
from app.models.tenant import Tenant
from app.services.tenant_provision import (
- ProvisioningError,
ProvisionResult,
+ ProvisioningError,
SlugCollisionError,
WaitlistEntryNotFoundError,
WaitlistEntryNotPromotableError,
@@ -187,7 +185,9 @@ def _tenant_to_wire(row: Tenant) -> TenantListEntry:
plan=row.plan or "starter",
is_active=bool(row.is_active),
is_managed=bool(settings_blob.get("managed", False)),
- provisioned_from_waitlist_id=settings_blob.get("provisioned_from_waitlist_id"),
+ provisioned_from_waitlist_id=settings_blob.get(
+ "provisioned_from_waitlist_id"
+ ),
provisioned_at=settings_blob.get("provisioned_at"),
created_at=row.created_at.isoformat() if row.created_at else "",
)
diff --git a/services/api/app/api/v1/endpoints/waitlist.py b/services/api/app/api/v1/endpoints/waitlist.py
index f802347aa..abafeb709 100644
--- a/services/api/app/api/v1/endpoints/waitlist.py
+++ b/services/api/app/api/v1/endpoints/waitlist.py
@@ -1,7 +1,5 @@
"""Managed-instance waitlist endpoints — T6.1.
-# TODO(T6.1): wire into v1 router after Subagent A's stabilization push lands.
-
Three endpoints, one public + two admin-only:
* ``POST /v1/waitlist/signup`` — public, rate-limited per IP.
@@ -191,7 +189,9 @@ class WaitlistPatchRequest(BaseModel):
def _validate_status(cls, value: str) -> str:
v = value.strip().lower()
if v not in ALLOWED_WAITLIST_STATUSES:
- raise ValueError(f"status must be one of: {sorted(ALLOWED_WAITLIST_STATUSES)}")
+ raise ValueError(
+ f"status must be one of: {sorted(ALLOWED_WAITLIST_STATUSES)}"
+ )
return v
@@ -229,7 +229,9 @@ def _to_wire(row: WaitlistEntry) -> WaitlistEntryWire:
soc_stack=list(row.soc_stack or []),
motivation=row.motivation,
status=row.status,
- provisioned_tenant_id=(str(row.provisioned_tenant_id) if row.provisioned_tenant_id else None),
+ provisioned_tenant_id=(
+ str(row.provisioned_tenant_id) if row.provisioned_tenant_id else None
+ ),
created_at=row.created_at.isoformat(),
contacted_at=row.contacted_at.isoformat() if row.contacted_at else None,
onboarded_at=row.onboarded_at.isoformat() if row.onboarded_at else None,
@@ -291,7 +293,9 @@ async def signup(
# path — only the admin PATCH endpoint moves an entry off ``new``.
entry: WaitlistEntry | None = None
try:
- existing = (await db.execute(select(WaitlistEntry).where(WaitlistEntry.email == payload.email))).scalar_one_or_none()
+ existing = (
+ await db.execute(select(WaitlistEntry).where(WaitlistEntry.email == payload.email))
+ ).scalar_one_or_none()
if existing is not None:
return WaitlistSignupResponse(entry_id=str(existing.id))
@@ -310,7 +314,9 @@ async def signup(
# Race: another request inserted between SELECT and commit.
# Treat as idempotent success and look the row back up.
await db.rollback()
- existing = (await db.execute(select(WaitlistEntry).where(WaitlistEntry.email == payload.email))).scalar_one_or_none()
+ existing = (
+ await db.execute(select(WaitlistEntry).where(WaitlistEntry.email == payload.email))
+ ).scalar_one_or_none()
if existing is not None:
return WaitlistSignupResponse(entry_id=str(existing.id))
# If we still can't find it, fall through to a generic success
@@ -391,9 +397,13 @@ async def patch_entry(
user: AuthUser,
) -> WaitlistEntryWire:
await _require_admin(user, db)
- row = (await db.execute(select(WaitlistEntry).where(WaitlistEntry.id == entry_id))).scalar_one_or_none()
+ row = (
+ await db.execute(select(WaitlistEntry).where(WaitlistEntry.id == entry_id))
+ ).scalar_one_or_none()
if row is None:
- raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="waitlist_entry_not_found")
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND, detail="waitlist_entry_not_found"
+ )
now = datetime.now(UTC)
previous = row.status
@@ -420,29 +430,13 @@ async def patch_entry(
detail="Could not update waitlist entry.",
) from exc
- # CodeQL py/log-injection: sanitise every value inline so the taint
- # tracker sees the .replace() chain directly at the call site.
- #
- # - ``previous`` / ``payload.status`` are Pydantic-validated against
- # ``ALLOWED_WAITLIST_STATUSES`` (short identifiers, no CR/LF), and
- # - ``entry_id`` / ``user.user_id`` are typed as ``uuid.UUID`` so the
- # string form is always ``[0-9a-f-]{36}``,
- #
- # but CodeQL's taint tracker treats path params and DB-derived
- # strings as user-controlled regardless. Making the cleansing
- # explicit at the call site silences the alert without weakening
- # any existing guarantee.
- safe_previous = (previous or "").replace("\r", "").replace("\n", " ")[:32]
- safe_next = (payload.status or "").replace("\r", "").replace("\n", " ")[:32]
- safe_entry_id = str(entry_id).replace("\r", "").replace("\n", " ")[:36]
- safe_actor = str(user.user_id).replace("\r", "").replace("\n", " ")[:36]
logger.info(
"waitlist_status_transition",
extra={
- "entry_id": safe_entry_id,
- "previous": safe_previous,
- "next": safe_next,
- "actor": safe_actor,
+ "entry_id": str(entry_id),
+ "previous": previous,
+ "next": payload.status,
+ "actor": str(user.user_id),
},
)
return _to_wire(row)
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index 4ce734ad2..28598fcdc 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -31,6 +31,7 @@ from app.api.v1.endpoints import (
feedback,
fusion,
graph,
+ graph_ws,
health,
hunts,
identity_graph,
@@ -60,15 +61,16 @@ from app.api.v1.endpoints import (
rbac,
remediation,
reports,
- rule_tuning,
saved_hunts,
saved_views,
shifts,
sla,
stix_taxii,
+ tenant_provision,
tenants,
threat_intel,
translation,
+ waitlist,
)
api_router = APIRouter(prefix="/api/v1")
@@ -118,11 +120,6 @@ api_router.include_router(metrics.router)
# single deterministic payload (7 tiles + sparklines + delta vs the
# preceding window) so the dashboard can render in one round trip.
api_router.include_router(insights.router)
-# v1.5 SOC Console parity — per-stage health strip for the operator
-# dashboard. Lives at /api/v1/health/pipeline and returns the
-# ingest → normalize → fuse → correlate → alert snapshot defined in
-# endpoints/health.py.
-api_router.include_router(health.router)
api_router.include_router(sla.router)
api_router.include_router(investigations.router)
# Effective permissions resolver (T3.2 — v8.0 parallel team plan).
@@ -265,3 +262,19 @@ api_router.include_router(inbox_itsm.router)
# allowlisted table catalog so operators (and LLM agents) can author
# queries without column-name guesswork.
api_router.include_router(lake.router)
+
+# Managed-instance onboarding — T6.1 (`app.aisoc.dev` beta).
+# /waitlist exposes the public signup + admin entries CRUD that feeds
+# the sales funnel; /admin/tenants promotes approved entries into live
+# tenants. Admin endpoints gate on `admin:waitlist` / `admin:tenants`
+# (falling back to `settings:write` for tenants whose RBAC rows have
+# not been migrated to the granular admin scope yet).
+api_router.include_router(waitlist.router)
+api_router.include_router(tenant_provision.router)
+
+# Public-facing graph-update WebSocket proxy — T1.4 (v8.0 parallel team plan).
+# /graph_ws/stream authenticates the browser's session token, rebinds the
+# tenant_id from the resolved user, and proxies to the internal ingest
+# broadcaster (AISOC_INGEST_GRAPH_WS_URL). Backs the RealtimeGraph
+# Cytoscape view; gates on graph:read.
+api_router.include_router(graph_ws.router)
diff --git a/services/api/app/core/config.py b/services/api/app/core/config.py
index 8474ecf69..245239cc5 100644
--- a/services/api/app/core/config.py
+++ b/services/api/app/core/config.py
@@ -10,14 +10,7 @@ import warnings
from functools import lru_cache
from typing import Any, Final
-from pydantic import (
- AliasChoices,
- Field,
- PostgresDsn,
- RedisDsn,
- field_validator,
- model_validator,
-)
+from pydantic import AliasChoices, Field, PostgresDsn, RedisDsn, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
# Default placeholders shipped in source. Anything matching these in a
@@ -253,7 +246,9 @@ class Settings(BaseSettings):
# ------------------------------------------------------------------
HUNT_SCHEDULER_ENABLED: bool = Field(
default=False,
- validation_alias=AliasChoices("HUNT_SCHEDULER_ENABLED", "AISOC_HUNT_SCHEDULER_ENABLED"),
+ validation_alias=AliasChoices(
+ "HUNT_SCHEDULER_ENABLED", "AISOC_HUNT_SCHEDULER_ENABLED"
+ ),
)
HUNT_SCHEDULER_POLL_INTERVAL_SECONDS: int = 30
diff --git a/services/api/app/main.py b/services/api/app/main.py
index 73853f445..a4d78b8df 100644
--- a/services/api/app/main.py
+++ b/services/api/app/main.py
@@ -133,7 +133,9 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
hunt_scheduler_task: asyncio.Task | None = None
if settings.HUNT_SCHEDULER_ENABLED:
try:
- hunt_scheduler_task = asyncio.create_task(run_hunt_scheduler(), name="hunt_scheduler_worker")
+ hunt_scheduler_task = asyncio.create_task(
+ run_hunt_scheduler(), name="hunt_scheduler_worker"
+ )
logger.info("hunt_scheduler worker started")
except Exception as exc:
logger.warning("hunt_scheduler worker failed to start", error=str(exc))
diff --git a/services/api/app/models/waitlist.py b/services/api/app/models/waitlist.py
index d71e4ff9e..701e8ec7f 100644
--- a/services/api/app/models/waitlist.py
+++ b/services/api/app/models/waitlist.py
@@ -39,6 +39,7 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.db.database import Base
+
# Status ladder. Kept in sync with the CHECK constraint in
# ``migrations/042_waitlist.sql`` — adding a new state requires both an
# entry here AND a migration to widen the constraint.
@@ -72,7 +73,11 @@ class WaitlistEntry(Base):
# ForeignKey here so the import graph stays free of circular deps
# with the tenant model; the migration adds the actual FK at the
# database layer.
- provisioned_tenant_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True, index=True)
- created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC), nullable=False)
+ provisioned_tenant_id: Mapped[uuid.UUID | None] = mapped_column(
+ UUID(as_uuid=True), nullable=True, index=True
+ )
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), default=lambda: datetime.now(UTC), nullable=False
+ )
contacted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
onboarded_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
diff --git a/services/api/app/scripts/seed_demo.py b/services/api/app/scripts/seed_demo.py
index d131b4418..bb5a19735 100644
--- a/services/api/app/scripts/seed_demo.py
+++ b/services/api/app/scripts/seed_demo.py
@@ -2410,13 +2410,10 @@ _DEMO_QUICK_DEFAULT_CLOCK_ISO = "2026-05-13T19:00:00+00:00"
# The constant has no security meaning — it's just a fixed seed.
_DEMO_QUICK_UUID_NS = uuid.UUID("a15a1c00-0000-4d04-8000-000000000064")
-# Per-invocation deterministic jitter source was previously declared here
-# (``_quick_rng = random.Random(20260513)``) for alert offset and ``ai_score``
-# perturbations. It has been removed because no call site reads from it any
-# more — keeping a global, never-used RNG drew a CodeQL
-# ``py/unused-global-variable`` warning and provided no behavioural value.
-# If deterministic jitter is reintroduced, declare the RNG inside the helper
-# that actually consumes it so it stays scoped and analysable.
+# Per-invocation deterministic jitter source. Used sparingly — alert
+# offsets and tiny `ai_score` perturbations only — so re-runs stay
+# byte-identical even when the underlying random sequence is touched.
+_quick_rng = random.Random(20260513)
def _parse_clock(value: str | None) -> datetime:
@@ -2948,11 +2945,16 @@ async def _seed_demo_quick_connectors(
created = 0
for connector_type in sorted(needed):
existing = await session.execute(
- select(Connector).where(Connector.tenant_id == tenant.id).where(Connector.connector_type == connector_type).limit(1)
+ select(Connector)
+ .where(Connector.tenant_id == tenant.id)
+ .where(Connector.connector_type == connector_type)
+ .limit(1)
)
if existing.scalar_one_or_none() is not None:
continue
- display, category = _DEMO_QUICK_CONNECTOR_PROFILES.get(connector_type, (connector_type, "siem"))
+ display, category = _DEMO_QUICK_CONNECTOR_PROFILES.get(
+ connector_type, (connector_type, "siem")
+ )
session.add(
Connector(
id=_demo_quick_uuid("connector", connector_type),
@@ -2983,13 +2985,19 @@ async def _purge_demo_quick(session, tenant: Tenant) -> tuple[int, int, int]:
keys = [incident["key"] for incident in _DEMO_QUICK_INCIDENTS]
# Collect existing case IDs first so we can scope the timeline delete.
- case_rows = await session.execute(select(Case.id).where(Case.tenant_id == tenant.id).where(Case.case_number.in_(keys)))
+ case_rows = await session.execute(
+ select(Case.id)
+ .where(Case.tenant_id == tenant.id)
+ .where(Case.case_number.in_(keys))
+ )
case_ids = [row[0] for row in case_rows.all()]
deleted_timelines = 0
if case_ids:
result = await session.execute(
- delete(CaseTimeline).where(CaseTimeline.tenant_id == tenant.id).where(CaseTimeline.case_id.in_(case_ids))
+ delete(CaseTimeline)
+ .where(CaseTimeline.tenant_id == tenant.id)
+ .where(CaseTimeline.case_id.in_(case_ids))
)
deleted_timelines = result.rowcount or 0
@@ -2997,12 +3005,20 @@ async def _purge_demo_quick(session, tenant: Tenant) -> tuple[int, int, int]:
# tag, but case-scoped deletion is the safer ON DELETE path.
deleted_alerts = 0
if case_ids:
- result = await session.execute(delete(Alert).where(Alert.tenant_id == tenant.id).where(Alert.case_id.in_(case_ids)))
+ result = await session.execute(
+ delete(Alert)
+ .where(Alert.tenant_id == tenant.id)
+ .where(Alert.case_id.in_(case_ids))
+ )
deleted_alerts = result.rowcount or 0
deleted_cases = 0
if case_ids:
- result = await session.execute(delete(Case).where(Case.tenant_id == tenant.id).where(Case.id.in_(case_ids)))
+ result = await session.execute(
+ delete(Case)
+ .where(Case.tenant_id == tenant.id)
+ .where(Case.id.in_(case_ids))
+ )
deleted_cases = result.rowcount or 0
await session.flush()
@@ -3152,8 +3168,12 @@ async def _run_quick_seed(clock: datetime) -> None:
tenant = await _ensure_tenant(session)
user = await _ensure_user(session, tenant)
connectors = await _seed_demo_quick_connectors(session, tenant, clock=clock)
- deleted_cases, deleted_alerts, deleted_timelines = await _purge_demo_quick(session, tenant)
- cases, alerts, timelines = await _seed_demo_quick(session, tenant, clock=clock)
+ deleted_cases, deleted_alerts, deleted_timelines = await _purge_demo_quick(
+ session, tenant
+ )
+ cases, alerts, timelines = await _seed_demo_quick(
+ session, tenant, clock=clock
+ )
await session.commit()
except Exception:
await session.rollback()
@@ -3162,11 +3182,16 @@ async def _run_quick_seed(clock: datetime) -> None:
print(f"[seed] tenant: {tenant.id} ({tenant.slug})")
print(f"[seed] user: {user.email} (role={user.role})")
print(f"[seed] connectors upserted: {connectors}")
- print(f"[seed] purged DEMO-* — cases:{deleted_cases} alerts:{deleted_alerts} timelines:{deleted_timelines}")
+ print(
+ "[seed] purged DEMO-* — cases:%d alerts:%d timelines:%d"
+ % (deleted_cases, deleted_alerts, deleted_timelines)
+ )
print(f"[seed] DEMO-* cases seeded: {cases}")
print(f"[seed] DEMO-* alerts seeded: {alerts}")
print(f"[seed] DEMO-* timelines seeded: {timelines}")
- print("[seed] showcase case: DEMO-004 — http://localhost:3000/cases/DEMO-004?tab=ledger")
+ print(
+ "[seed] showcase case: DEMO-004 — http://localhost:3000/cases/DEMO-004?tab=ledger"
+ )
print("[seed] done — four-case demo set is live")
diff --git a/services/api/app/services/attack_chain.py b/services/api/app/services/attack_chain.py
index d398c06c6..15da2ba4e 100644
--- a/services/api/app/services/attack_chain.py
+++ b/services/api/app/services/attack_chain.py
@@ -223,8 +223,9 @@ class AttackChainLoader(Protocol):
set passed in.
"""
- async def load_seed(self, alert_id: uuid.UUID, tenant_id: uuid.UUID) -> CandidateAlert | None:
- """Return the seed alert if it exists in the given tenant, else None."""
+ async def load_seed(
+ self, alert_id: uuid.UUID, tenant_id: uuid.UUID
+ ) -> CandidateAlert | None: ...
async def load_candidates_for_entities(
self,
@@ -233,8 +234,7 @@ class AttackChainLoader(Protocol):
start: datetime,
end: datetime,
exclude_ids: set[uuid.UUID],
- ) -> list[CandidateAlert]:
- """Return candidate alerts sharing entities with the seed in ``[start, end]``."""
+ ) -> list[CandidateAlert]: ...
# ---------------------------------------------------------------------------
@@ -242,7 +242,9 @@ class AttackChainLoader(Protocol):
# ---------------------------------------------------------------------------
-def _temporal_score(seed_time: datetime, candidate_time: datetime, window: timedelta) -> tuple[float, float]:
+def _temporal_score(
+ seed_time: datetime, candidate_time: datetime, window: timedelta
+) -> tuple[float, float]:
"""Return (score, |Δt| in seconds). Score is in [0, 1] — closer in
time → higher score. ``|Δt|`` is exposed in the response so the UI
can render the absolute time delta beside the chain link."""
@@ -369,7 +371,9 @@ def _entity_graph_payload(
_add_alert_node(seed)
for kind, value in sorted(seed.entities()):
_add_entity_node(kind, value)
- edges.append({"source": f"alert:{seed.id}", "target": f"{kind.lower()}:{value}", "kind": "TOUCHES"})
+ edges.append(
+ {"source": f"alert:{seed.id}", "target": f"{kind.lower()}:{value}", "kind": "TOUCHES"}
+ )
for link in chain:
cand = candidate_index.get(link.alert_id)
@@ -515,12 +519,15 @@ class PostgresAttackChainLoader:
def __init__(self, db: Any) -> None:
self._db = db
- async def load_seed(self, alert_id: uuid.UUID, tenant_id: uuid.UUID) -> CandidateAlert | None:
+ async def load_seed(
+ self, alert_id: uuid.UUID, tenant_id: uuid.UUID
+ ) -> CandidateAlert | None:
from sqlalchemy import select # local import keeps the module
-
from app.models.alert import Alert # test-importable w/o DB
- result = await self._db.execute(select(Alert).where(Alert.id == alert_id, Alert.tenant_id == tenant_id))
+ result = await self._db.execute(
+ select(Alert).where(Alert.id == alert_id, Alert.tenant_id == tenant_id)
+ )
row = result.scalar_one_or_none()
if row is None:
return None
@@ -535,7 +542,6 @@ class PostgresAttackChainLoader:
exclude_ids: set[uuid.UUID],
) -> list[CandidateAlert]:
from sqlalchemy import and_, or_, select, text
-
from app.models.alert import Alert
users: list[str] = []
diff --git a/services/api/app/services/business_context/engine.py b/services/api/app/services/business_context/engine.py
index f0b168c91..3a3e8055d 100644
--- a/services/api/app/services/business_context/engine.py
+++ b/services/api/app/services/business_context/engine.py
@@ -217,8 +217,12 @@ class EngineSnapshot:
return tuple(r for r in self.rules if r.enabled)
-def _compile_snapshot(tenant_id: UUID, version: int, rules: Iterable[BusinessContextRule]) -> EngineSnapshot:
- sorted_rules = tuple(sorted(rules, key=lambda r: (r.priority, r.id)))
+def _compile_snapshot(
+ tenant_id: UUID, version: int, rules: Iterable[BusinessContextRule]
+) -> EngineSnapshot:
+ sorted_rules = tuple(
+ sorted(rules, key=lambda r: (r.priority, r.id))
+ )
idx: dict[str, list[str]] = {}
for r in sorted_rules:
for f in r.when.fields_referenced():
diff --git a/services/api/app/services/business_context/models.py b/services/api/app/services/business_context/models.py
index 26cc38735..9cdf5710d 100644
--- a/services/api/app/services/business_context/models.py
+++ b/services/api/app/services/business_context/models.py
@@ -19,8 +19,7 @@ language the editor speaks.
from __future__ import annotations
import re
-from dataclasses import dataclass
-from dataclasses import field as dc_field
+from dataclasses import dataclass, field as dc_field
from typing import Any, Literal
import yaml
@@ -152,7 +151,12 @@ class RuleAction:
suppress: bool = False # if true, alert is dropped before triage
def is_noop(self) -> bool:
- return self.set_severity is None and self.route_to is None and self.tag is None and not self.suppress
+ return (
+ self.set_severity is None
+ and self.route_to is None
+ and self.tag is None
+ and not self.suppress
+ )
# ---------------------------------------------------------------------------
@@ -202,23 +206,34 @@ def _parse_condition(raw: Any, *, path: str) -> RuleCondition:
children_raw = raw[key]
if key == "not":
if not isinstance(children_raw, dict):
- raise RuleParseError(f"{path}.not: expected a mapping for the negated condition")
+ raise RuleParseError(
+ f"{path}.not: expected a mapping for the negated condition"
+ )
child = _parse_condition(children_raw, path=f"{path}.not")
return RuleCondition(logical="not", children=(child,))
if not isinstance(children_raw, list) or not children_raw:
- raise RuleParseError(f"{path}.{key}: must be a non-empty list of conditions")
- children = tuple(_parse_condition(c, path=f"{path}.{key}[{i}]") for i, c in enumerate(children_raw))
+ raise RuleParseError(
+ f"{path}.{key}: must be a non-empty list of conditions"
+ )
+ children = tuple(
+ _parse_condition(c, path=f"{path}.{key}[{i}]")
+ for i, c in enumerate(children_raw)
+ )
return RuleCondition(logical=key, children=children)
# Leaf form
field_name = raw.get("field")
op = raw.get("op")
if field_name is None or op is None:
- raise RuleParseError(f"{path}: leaf condition must include 'field' and 'op' (got {sorted(raw.keys())})")
+ raise RuleParseError(
+ f"{path}: leaf condition must include 'field' and 'op' (got {sorted(raw.keys())})"
+ )
if not isinstance(field_name, str) or not field_name:
raise RuleParseError(f"{path}.field: must be a non-empty string")
if op not in ALLOWED_OPS:
- raise RuleParseError(f"{path}.op: {op!r} is not one of {sorted(ALLOWED_OPS)}")
+ raise RuleParseError(
+ f"{path}.op: {op!r} is not one of {sorted(ALLOWED_OPS)}"
+ )
# ``exists`` / ``not_exists`` are unary — value is ignored if present.
if op in {"exists", "not_exists"}:
@@ -233,33 +248,45 @@ def _parse_condition(raw: Any, *, path: str) -> RuleCondition:
if isinstance(value, (str, bytes)):
value = [value]
if not isinstance(value, (list, tuple)) or not value:
- raise RuleParseError(f"{path}.value: op={op!r} requires a non-empty list")
+ raise RuleParseError(
+ f"{path}.value: op={op!r} requires a non-empty list"
+ )
value = list(value)
return RuleCondition(field=field_name, op=op, value=value)
def _parse_action(raw: Any, *, rule_id: str) -> RuleAction:
if not isinstance(raw, dict):
- raise RuleParseError(f"rule {rule_id!r}: 'then' must be a mapping (got {type(raw).__name__})")
+ raise RuleParseError(
+ f"rule {rule_id!r}: 'then' must be a mapping (got {type(raw).__name__})"
+ )
sev = raw.get("set_severity")
if sev is not None:
if not isinstance(sev, str) or sev not in ALLOWED_SEVERITIES:
- raise RuleParseError(f"rule {rule_id!r}: 'set_severity' must be one of {ALLOWED_SEVERITIES}")
+ raise RuleParseError(
+ f"rule {rule_id!r}: 'set_severity' must be one of {ALLOWED_SEVERITIES}"
+ )
route = raw.get("route_to")
if route is not None:
if not isinstance(route, str) or route not in ALLOWED_ROUTES:
- raise RuleParseError(f"rule {rule_id!r}: 'route_to' must be one of {sorted(ALLOWED_ROUTES)}")
+ raise RuleParseError(
+ f"rule {rule_id!r}: 'route_to' must be one of {sorted(ALLOWED_ROUTES)}"
+ )
tag = raw.get("tag")
if tag is not None:
if not isinstance(tag, str) or not _TAG_RE.match(tag):
- raise RuleParseError(f"rule {rule_id!r}: 'tag' must be a kebab-case slug (got {tag!r})")
+ raise RuleParseError(
+ f"rule {rule_id!r}: 'tag' must be a kebab-case slug (got {tag!r})"
+ )
suppress = raw.get("suppress", False)
if not isinstance(suppress, bool):
- raise RuleParseError(f"rule {rule_id!r}: 'suppress' must be a boolean (got {type(suppress).__name__})")
+ raise RuleParseError(
+ f"rule {rule_id!r}: 'suppress' must be a boolean (got {type(suppress).__name__})"
+ )
return RuleAction(
set_severity=sev,
@@ -271,11 +298,15 @@ def _parse_action(raw: Any, *, rule_id: str) -> RuleAction:
def _parse_one_rule(raw: Any, *, source_yaml: str) -> BusinessContextRule:
if not isinstance(raw, dict):
- raise RuleParseError(f"top-level rule must be a mapping, got {type(raw).__name__}")
+ raise RuleParseError(
+ f"top-level rule must be a mapping, got {type(raw).__name__}"
+ )
rid = raw.get("id")
if not isinstance(rid, str) or not _RULE_ID_RE.match(rid):
- raise RuleParseError("rule.id must be a kebab-case slug 3-63 chars (e.g. 'prod-iam-critical')")
+ raise RuleParseError(
+ "rule.id must be a kebab-case slug 3-63 chars (e.g. 'prod-iam-critical')"
+ )
description = raw.get("description", "") or ""
if not isinstance(description, str):
@@ -291,7 +322,10 @@ def _parse_one_rule(raw: Any, *, source_yaml: str) -> BusinessContextRule:
raise RuleParseError(f"rule {rid!r}: 'then' clause is required")
then = _parse_action(then_raw, rule_id=rid)
if then.is_noop():
- raise RuleParseError(f"rule {rid!r}: 'then' clause must set at least one of set_severity / route_to / tag / suppress")
+ raise RuleParseError(
+ f"rule {rid!r}: 'then' clause must set at least one of "
+ "set_severity / route_to / tag / suppress"
+ )
enabled = raw.get("enabled", True)
if not isinstance(enabled, bool):
@@ -299,7 +333,9 @@ def _parse_one_rule(raw: Any, *, source_yaml: str) -> BusinessContextRule:
priority = raw.get("priority", 100)
if not isinstance(priority, int) or not 0 <= priority <= 1000:
- raise RuleParseError(f"rule {rid!r}: 'priority' must be an int in [0, 1000]")
+ raise RuleParseError(
+ f"rule {rid!r}: 'priority' must be an int in [0, 1000]"
+ )
return BusinessContextRule(
id=rid,
@@ -356,14 +392,18 @@ def load_rules_from_yaml(source: str) -> list[BusinessContextRule]:
# Single-rule shorthand.
rules_raw = [data]
else:
- raise RuleParseError(f"top-level YAML must be a list or mapping, got {type(data).__name__}")
+ raise RuleParseError(
+ f"top-level YAML must be a list or mapping, got {type(data).__name__}"
+ )
parsed: list[BusinessContextRule] = []
seen_ids: set[str] = set()
for raw in rules_raw:
rule = _parse_one_rule(raw, source_yaml=text)
if rule.id in seen_ids:
- raise RuleParseError(f"duplicate rule id {rule.id!r} (rule ids must be unique)")
+ raise RuleParseError(
+ f"duplicate rule id {rule.id!r} (rule ids must be unique)"
+ )
seen_ids.add(rule.id)
parsed.append(rule)
diff --git a/services/api/app/services/effective_permissions/aws.py b/services/api/app/services/effective_permissions/aws.py
index a01cac497..94e823ca7 100644
--- a/services/api/app/services/effective_permissions/aws.py
+++ b/services/api/app/services/effective_permissions/aws.py
@@ -121,7 +121,9 @@ def _resource_matches(statement_resource: Any, resource_arn: str) -> bool:
return False
-def _condition_matches(condition: dict[str, Any] | None, context: dict[str, Any]) -> bool:
+def _condition_matches(
+ condition: dict[str, Any] | None, context: dict[str, Any]
+) -> bool:
"""Evaluate the subset of IAM condition operators the resolver models.
Returns ``True`` when no condition is present. Supports
@@ -204,20 +206,30 @@ class AwsIamResolver(Resolver):
) -> ResolverResult:
snap = snapshot if snapshot is not None else self._snapshot
if snap is None:
- raise ResolverError("AwsIamResolver.resolve called without a snapshot")
+ raise ResolverError(
+ "AwsIamResolver.resolve called without a snapshot"
+ )
principals_by_id = {p["id"]: p for p in snap.get("principals", [])}
- principals_by_arn = {p["arn"]: p for p in snap.get("principals", []) if "arn" in p}
- principal = principals_by_id.get(principal_id) or principals_by_arn.get(principal_id)
+ principals_by_arn = {
+ p["arn"]: p for p in snap.get("principals", []) if "arn" in p
+ }
+ principal = principals_by_id.get(principal_id) or principals_by_arn.get(
+ principal_id
+ )
if principal is None:
- raise ResolverError(f"principal {principal_id!r} not present in snapshot")
+ raise ResolverError(
+ f"principal {principal_id!r} not present in snapshot"
+ )
policies_by_id = {p["id"]: p for p in snap.get("policies", [])}
groups_by_id = {g["id"]: g for g in snap.get("groups", [])}
scp_ids = list(snap.get("scps", []))
action_catalogue: dict[str, list[str]] = snap.get("action_catalogue", {})
- identity_policy_refs = self._collect_identity_policies(principal, groups_by_id)
+ identity_policy_refs = self._collect_identity_policies(
+ principal, groups_by_id
+ )
notes: list[str] = []
decisions: list[ResolvedPermission] = []
@@ -234,7 +246,10 @@ class AwsIamResolver(Resolver):
decisions.append(decision)
if any(p.get("permissions_boundary") for p in [principal]):
- notes.append("permissions-boundary present on principal — not modelled; deny-side may over-permit")
+ notes.append(
+ "permissions-boundary present on principal — not modelled; "
+ "deny-side may over-permit"
+ )
return ResolverResult(
provider=self.provider,
@@ -285,7 +300,9 @@ class AwsIamResolver(Resolver):
) -> ResolvedPermission | None:
resource_arn = resource["arn"]
resource_service = resource.get("service") or resource_arn.split(":")[2]
- service_catalogue = resource.get("service_actions") or action_catalogue.get(resource_service, [])
+ service_catalogue = (
+ resource.get("service_actions") or action_catalogue.get(resource_service, [])
+ )
context = resource.get("context", {})
chain: list[PolicyChainStep] = []
@@ -342,7 +359,9 @@ class AwsIamResolver(Resolver):
kind="policy",
id=resource_policy_id,
name=resource_policy.get("name", resource_policy_id),
- effect="deny" if resource_deny and not resource_allow else "allow",
+ effect="deny"
+ if resource_deny and not resource_allow
+ else "allow",
)
)
@@ -436,7 +455,9 @@ class AwsIamResolver(Resolver):
if not isinstance(statement, dict):
continue
if principal_match_required:
- if not _principal_matches(statement.get("Principal"), principal_arn):
+ if not _principal_matches(
+ statement.get("Principal"), principal_arn
+ ):
continue
if not _resource_matches(statement.get("Resource", "*"), resource_arn):
continue
diff --git a/services/api/app/services/effective_permissions/base.py b/services/api/app/services/effective_permissions/base.py
index aefeabeed..1298d155c 100644
--- a/services/api/app/services/effective_permissions/base.py
+++ b/services/api/app/services/effective_permissions/base.py
@@ -111,7 +111,9 @@ class ResolverResult:
provider: str
principal_id: str
coverage: Coverage
- last_resolved: datetime = field(default_factory=lambda: datetime.now(tz=UTC))
+ last_resolved: datetime = field(
+ default_factory=lambda: datetime.now(tz=UTC)
+ )
decisions: list[ResolvedPermission] = field(default_factory=list)
resolver_version: str = RESOLVER_VERSION
notes: list[str] = field(default_factory=list)
diff --git a/services/api/app/services/effective_permissions/service.py b/services/api/app/services/effective_permissions/service.py
index 330ad7aa9..6746fe815 100644
--- a/services/api/app/services/effective_permissions/service.py
+++ b/services/api/app/services/effective_permissions/service.py
@@ -63,14 +63,9 @@ def _default_snapshot_loader(provider: str) -> dict[str, Any]:
surfaces a 412 Precondition Failed ("no policy snapshot ingested yet").
"""
- # ``provider`` is validated against ``SUPPORTED_PROVIDERS`` upstream, but
- # CodeQL's ``py/log-injection`` taint analysis does not recognise the
- # membership check as a sanitiser. Strip CR/LF explicitly so the value
- # entering the log record cannot forge log lines.
- safe_provider = provider.replace("\r", "").replace("\n", " ")
logger.warning(
"no production snapshot loader wired for provider=%s — returning {}",
- safe_provider,
+ provider,
)
return {}
@@ -97,7 +92,10 @@ def resolve_effective_permissions(
resolver_cls = SUPPORTED_PROVIDERS.get(provider)
if resolver_cls is None:
- raise ValueError(f"unknown provider {provider!r}; supported: {sorted(SUPPORTED_PROVIDERS)}")
+ raise ValueError(
+ f"unknown provider {provider!r}; supported: "
+ f"{sorted(SUPPORTED_PROVIDERS)}"
+ )
resolver = resolver_cls()
if snapshot is None:
diff --git a/services/api/app/services/email_approval.py b/services/api/app/services/email_approval.py
index 293dcf72f..5102e7cb2 100644
--- a/services/api/app/services/email_approval.py
+++ b/services/api/app/services/email_approval.py
@@ -222,7 +222,7 @@ class MailDeliveryClient(Protocol):
text: str,
from_addr: str | None = None,
) -> dict[str, Any]:
- """Deliver an email and return a provider-specific response payload."""
+ ...
class MailgunClient:
@@ -321,10 +321,8 @@ def render_approval_email(
f"<tr><td><strong>Rationale</strong></td><td>{rationale}</td></tr>"
f"</table>"
f"<p style='margin-top:16px'>"
- f"<a href='{approve_url}' style='background:#16a34a;color:#fff;padding:8px 14px;"
- f"border-radius:6px;text-decoration:none;margin-right:8px'>Approve</a>"
- f"<a href='{reject_url}' style='background:#dc2626;color:#fff;padding:8px 14px;"
- f"border-radius:6px;text-decoration:none'>Deny</a>"
+ f"<a href='{approve_url}' style='background:#16a34a;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none;margin-right:8px'>Approve</a>"
+ f"<a href='{reject_url}' style='background:#dc2626;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none'>Deny</a>"
f"</p>"
f"<p style='color:#6b7280;font-size:12px'>This link expires in 60 minutes.</p>"
)
@@ -383,7 +381,9 @@ async def send_approval_email(
reject_url=reject,
web_base_url=web_base_url,
)
- response = await mailer.send(to=recipients, subject=subject, html=html_body, text=text_body)
+ response = await mailer.send(
+ to=recipients, subject=subject, html=html_body, text=text_body
+ )
log.info(
"email_approval.sent",
action_id=action_id,
diff --git a/services/api/app/services/tenant_provision/__init__.py b/services/api/app/services/tenant_provision/__init__.py
index 19961352e..090c131f6 100644
--- a/services/api/app/services/tenant_provision/__init__.py
+++ b/services/api/app/services/tenant_provision/__init__.py
@@ -17,8 +17,8 @@ from __future__ import annotations
from app.services.tenant_provision.provisioner import (
AdminInvite,
InitialAdminUser,
- ProvisioningError,
ProvisionResult,
+ ProvisioningError,
SlugCollisionError,
WaitlistEntryNotFoundError,
WaitlistEntryNotPromotableError,
diff --git a/services/api/app/services/tenant_provision/provisioner.py b/services/api/app/services/tenant_provision/provisioner.py
index cff968748..2b859ca20 100644
--- a/services/api/app/services/tenant_provision/provisioner.py
+++ b/services/api/app/services/tenant_provision/provisioner.py
@@ -53,10 +53,9 @@ import logging
import re
import secrets
import uuid
-from collections.abc import Callable
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
-from typing import Any
+from typing import Any, Callable
from cryptography.fernet import Fernet
from sqlalchemy import select, text
@@ -217,7 +216,10 @@ async def _allocate_slug(
if await _slug_is_available(db, candidate):
return candidate
- raise SlugCollisionError(f"could not allocate a unique slug for '{company_name}' after {_SLUG_RETRY_LIMIT} attempts")
+ raise SlugCollisionError(
+ f"could not allocate a unique slug for '{company_name}' after "
+ f"{_SLUG_RETRY_LIMIT} attempts"
+ )
def generate_credential_key() -> tuple[str, str]:
@@ -272,11 +274,8 @@ def _build_admin_invite(
# Type alias for the seed-demo callback so tests can pass in a stub
-# that doesn't need a real database session. ``Any`` is referenced
-# unquoted so CodeQL (``py/unused-import``) sees the import as used —
-# the surrounding ``Callable[...]`` is a runtime expression, not a
-# stringified annotation, so the name must resolve at evaluation time.
-DemoSeederCallable = Callable[[AsyncSession, Tenant], Any]
+# that doesn't need a real database session.
+DemoSeederCallable = Callable[[AsyncSession, Tenant], "Any"]
async def provision_from_waitlist(
@@ -331,11 +330,15 @@ async def provision_from_waitlist(
)
if entry.status == "declined":
- raise WaitlistEntryNotPromotableError(f"waitlist entry {entry.id} is declined; refusing to promote")
+ raise WaitlistEntryNotPromotableError(
+ f"waitlist entry {entry.id} is declined; refusing to promote"
+ )
bundle = templates or get_default_template_bundle()
- slug = await _allocate_slug(db, company_name=entry.company, shard_factory=shard_factory)
+ slug = await _allocate_slug(
+ db, company_name=entry.company, shard_factory=shard_factory
+ )
credential_key, key_fingerprint = generate_credential_key()
provisioned_at = datetime.now(UTC)
@@ -427,7 +430,9 @@ async def provision_from_waitlist(
exc,
)
- invite = _build_admin_invite(tenant_slug=tenant.slug, invite_base_url=invite_base_url)
+ invite = _build_admin_invite(
+ tenant_slug=tenant.slug, invite_base_url=invite_base_url
+ )
# Patch the waitlist row last so the entry's stamped timestamps
# only flip after every dependent write has succeeded.
@@ -455,7 +460,9 @@ async def provision_from_waitlist(
tenant_name=tenant.name,
waitlist_entry_id=entry.id,
admin_invite=invite,
- admin_user=InitialAdminUser(id=admin_user.id, email=admin_user.email, role=admin_user.role),
+ admin_user=InitialAdminUser(
+ id=admin_user.id, email=admin_user.email, role=admin_user.role
+ ),
demo_seeded=demo_seeded,
aisoc_credential_key_fingerprint=key_fingerprint,
)
@@ -484,7 +491,12 @@ async def _persist_provisioning_columns(
"""
try:
await db.execute(
- text("UPDATE tenants SET provisioned_from_waitlist_id = :wl_id, provisioned_at = :pa WHERE id = :tid"),
+ text(
+ "UPDATE tenants "
+ "SET provisioned_from_waitlist_id = :wl_id, "
+ " provisioned_at = :pa "
+ "WHERE id = :tid"
+ ),
{
"wl_id": waitlist_entry_id,
"pa": provisioned_at,
@@ -502,10 +514,16 @@ async def _persist_provisioning_columns(
)
-async def _load_waitlist_entry(db: AsyncSession, entry_id: uuid.UUID) -> WaitlistEntry:
- row = (await db.execute(select(WaitlistEntry).where(WaitlistEntry.id == entry_id))).scalar_one_or_none()
+async def _load_waitlist_entry(
+ db: AsyncSession, entry_id: uuid.UUID
+) -> WaitlistEntry:
+ row = (
+ await db.execute(select(WaitlistEntry).where(WaitlistEntry.id == entry_id))
+ ).scalar_one_or_none()
if row is None:
- raise WaitlistEntryNotFoundError(f"waitlist entry {entry_id} not found")
+ raise WaitlistEntryNotFoundError(
+ f"waitlist entry {entry_id} not found"
+ )
return row
@@ -521,30 +539,42 @@ async def _result_for_existing(
entry; instead the API surfaces the existing tenant id + a fresh
invite link the operator can email out if the first one was lost.
"""
- tenant = (await db.execute(select(Tenant).where(Tenant.id == entry.provisioned_tenant_id))).scalar_one_or_none()
+ tenant = (
+ await db.execute(
+ select(Tenant).where(Tenant.id == entry.provisioned_tenant_id)
+ )
+ ).scalar_one_or_none()
if tenant is None:
# The waitlist row claims it's provisioned but the tenant is
# gone. Treat as if it was never provisioned so the operator
# can recover.
entry.provisioned_tenant_id = None
- raise WaitlistEntryNotPromotableError(f"waitlist entry {entry.id} pointed at a deleted tenant; cleared the pointer")
+ raise WaitlistEntryNotPromotableError(
+ f"waitlist entry {entry.id} pointed at a deleted tenant; cleared the pointer"
+ )
admin_row = (
- (await db.execute(select(User).where(User.tenant_id == tenant.id, User.email == entry.email).order_by(User.created_at.asc())))
- .scalars()
- .first()
- )
+ await db.execute(
+ select(User)
+ .where(User.tenant_id == tenant.id, User.email == entry.email)
+ .order_by(User.created_at.asc())
+ )
+ ).scalars().first()
admin_email = admin_row.email if admin_row else entry.email
admin_role = admin_row.role if admin_row else "tenant_admin"
admin_id = admin_row.id if admin_row else uuid.uuid4()
- fingerprint = (tenant.settings or {}).get("aisoc_credential_key_fingerprint", "") or ""
+ fingerprint = (
+ (tenant.settings or {}).get("aisoc_credential_key_fingerprint", "") or ""
+ )
return ProvisionResult(
tenant_id=tenant.id,
tenant_slug=tenant.slug,
tenant_name=tenant.name,
waitlist_entry_id=entry.id,
- admin_invite=_build_admin_invite(tenant_slug=tenant.slug, invite_base_url=invite_base_url),
+ admin_invite=_build_admin_invite(
+ tenant_slug=tenant.slug, invite_base_url=invite_base_url
+ ),
admin_user=InitialAdminUser(id=admin_id, email=admin_email, role=admin_role),
demo_seeded=False,
aisoc_credential_key_fingerprint=fingerprint,
diff --git a/services/api/app/services/tenant_provision/templates.py b/services/api/app/services/tenant_provision/templates.py
index 7ce9a67d4..708f8fc2b 100644
--- a/services/api/app/services/tenant_provision/templates.py
+++ b/services/api/app/services/tenant_provision/templates.py
@@ -38,6 +38,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
+
# ---------------------------------------------------------------------------
# RBAC seed roles
# ---------------------------------------------------------------------------
diff --git a/services/api/app/services/waitlist/rate_limit.py b/services/api/app/services/waitlist/rate_limit.py
index 7ad9d57e3..a5195eafd 100644
--- a/services/api/app/services/waitlist/rate_limit.py
+++ b/services/api/app/services/waitlist/rate_limit.py
@@ -104,9 +104,13 @@ class SignupRateLimiter:
capacity: float | None = None,
refill_per_hour: float | None = None,
) -> None:
- cap = capacity if capacity is not None else _env_float("AISOC_WAITLIST_RATE_CAPACITY", _DEFAULT_CAPACITY)
+ cap = capacity if capacity is not None else _env_float(
+ "AISOC_WAITLIST_RATE_CAPACITY", _DEFAULT_CAPACITY
+ )
per_hour = (
- refill_per_hour if refill_per_hour is not None else _env_float("AISOC_WAITLIST_RATE_REFILL_PER_HOUR", _DEFAULT_REFILL_PER_HOUR)
+ refill_per_hour
+ if refill_per_hour is not None
+ else _env_float("AISOC_WAITLIST_RATE_REFILL_PER_HOUR", _DEFAULT_REFILL_PER_HOUR)
)
if cap <= 0:
raise ValueError("capacity must be positive")
@@ -122,7 +126,9 @@ class SignupRateLimiter:
if cost <= 0:
raise ValueError("cost must be positive")
if cost > self._capacity:
- raise ValueError(f"cost {cost} exceeds capacity {self._capacity}; would never succeed")
+ raise ValueError(
+ f"cost {cost} exceeds capacity {self._capacity}; would never succeed"
+ )
bucket = await self._get_bucket(source)
async with bucket.lock:
diff --git a/services/api/app/services/waitlist/slack_notify.py b/services/api/app/services/waitlist/slack_notify.py
index e2970ab94..1ecf6ed74 100644
--- a/services/api/app/services/waitlist/slack_notify.py
+++ b/services/api/app/services/waitlist/slack_notify.py
@@ -128,7 +128,9 @@ class SlackNotifier:
return False
webhook = self._resolve_webhook()
if not webhook:
- logger.info("waitlist slack notification skipped: %s not configured", _WEBHOOK_ENV_VAR)
+ logger.info(
+ "waitlist slack notification skipped: %s not configured", _WEBHOOK_ENV_VAR
+ )
return False
try:
body = json.dumps(payload).encode("utf-8")
@@ -141,7 +143,9 @@ class SlackNotifier:
with urllib_request.urlopen(req, timeout=self._timeout) as resp: # noqa: S310
if 200 <= resp.status < 300:
return True
- logger.warning("waitlist slack webhook returned non-2xx: %s", resp.status)
+ logger.warning(
+ "waitlist slack webhook returned non-2xx: %s", resp.status
+ )
return False
except urllib_error.URLError as exc:
logger.warning("waitlist slack webhook URLError: %s", exc)
diff --git a/services/api/app/workers/hunt_scheduler.py b/services/api/app/workers/hunt_scheduler.py
index 12d9891e1..0ab44ab09 100644
--- a/services/api/app/workers/hunt_scheduler.py
+++ b/services/api/app/workers/hunt_scheduler.py
@@ -165,7 +165,8 @@ async def _open_case_for_hits(db: AsyncSession, hunt: SavedHunt, hit_count: int)
case_number=f"HUNT-{hunt.id.hex[:8].upper()}-{int(datetime.now(UTC).timestamp())}",
title=f"Scheduled hunt fired: {hunt.name}",
description=(
- f"Saved hunt {hunt.name!r} returned {hit_count} hit(s) on its scheduled run.\n\nOriginal NL question: {hunt.nl_query}"
+ f"Saved hunt {hunt.name!r} returned {hit_count} hit(s) on its "
+ f"scheduled run.\n\nOriginal NL question: {hunt.nl_query}"
),
case_type="hunt_finding",
priority="medium",
@@ -243,7 +244,11 @@ async def run_once(
# tenant before each per-hunt write to keep RLS enforcement intact
# for the case insert.
await db.execute(text("SET LOCAL row_security = off"))
- rows = (await db.execute(select(SavedHunt).where(SavedHunt.schedule.is_not(None)))).scalars().all()
+ rows = (
+ (await db.execute(select(SavedHunt).where(SavedHunt.schedule.is_not(None))))
+ .scalars()
+ .all()
+ )
for hunt in rows:
if not _is_due(hunt, now):
continue
@@ -258,7 +263,11 @@ async def run_once(
hits = await runner(db, hunt)
await callback(db, hunt, hits)
# Stamp last_run_at so we don't re-fire on the next tick.
- await db.execute(update(SavedHunt).where(SavedHunt.id == hunt.id).values(last_run_at=now, updated_at=now))
+ await db.execute(
+ update(SavedHunt)
+ .where(SavedHunt.id == hunt.id)
+ .values(last_run_at=now, updated_at=now)
+ )
fired += 1
except Exception as exc: # pragma: no cover - defensive
logger.exception(
diff --git a/services/api/migrations/041_attack_chains.sql b/services/api/migrations/041_attack_chains.sql
index 27cb8c409..5d43525ba 100644
--- a/services/api/migrations/041_attack_chains.sql
+++ b/services/api/migrations/041_attack_chains.sql
@@ -56,10 +56,7 @@ CREATE TABLE IF NOT EXISTS aisoc_attack_chains (
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
seed_alert_id UUID NOT NULL,
case_id UUID,
- -- NB: ``window`` is a reserved keyword in PostgreSQL (used by SQL window
- -- functions), so the SQL column is named ``time_window`` even though the
- -- service layer / API surface continues to call it ``window``.
- time_window VARCHAR(8) NOT NULL,
+ window VARCHAR(8) NOT NULL,
chain JSONB NOT NULL DEFAULT '[]'::jsonb,
entity_graph JSONB NOT NULL DEFAULT '{}'::jsonb,
chain_signature VARCHAR(64) NOT NULL,
@@ -67,9 +64,9 @@ CREATE TABLE IF NOT EXISTS aisoc_attack_chains (
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT aisoc_attack_chains_window_check
- CHECK (time_window IN ('1h', '6h', '24h', '72h', '7d', '30d')),
+ CHECK (window IN ('1h', '6h', '24h', '72h', '7d', '30d')),
CONSTRAINT aisoc_attack_chains_unique_signature
- UNIQUE (tenant_id, seed_alert_id, time_window, chain_signature)
+ UNIQUE (tenant_id, seed_alert_id, window, chain_signature)
);
CREATE INDEX IF NOT EXISTS aisoc_attack_chains_seed_idx
diff --git a/services/api/tests/test_attack_chain.py b/services/api/tests/test_attack_chain.py
index 1be13469a..c9141dab6 100644
--- a/services/api/tests/test_attack_chain.py
+++ b/services/api/tests/test_attack_chain.py
@@ -32,6 +32,7 @@ from collections.abc import Iterable
from datetime import datetime, timedelta
import pytest
+
from app.services.attack_chain import (
DEFAULT_WINDOW,
CandidateAlert,
@@ -43,6 +44,7 @@ from app.services.attack_chain import (
score_candidate,
)
+
# ---------------------------------------------------------------------------
# Fixture: the 5-alert LockBit chain
# ---------------------------------------------------------------------------
@@ -140,7 +142,9 @@ class _InMemoryLoader:
self._by_id = {a.id: a for a in alerts}
self._all = alerts
- async def load_seed(self, alert_id: uuid.UUID, tenant_id: uuid.UUID) -> CandidateAlert | None:
+ async def load_seed(
+ self, alert_id: uuid.UUID, tenant_id: uuid.UUID
+ ) -> CandidateAlert | None:
row = self._by_id.get(alert_id)
if row is None or row.tenant_id != tenant_id:
return None
diff --git a/services/api/tests/test_business_context.py b/services/api/tests/test_business_context.py
index 9e552a02c..2b5a3d4ac 100644
--- a/services/api/tests/test_business_context.py
+++ b/services/api/tests/test_business_context.py
@@ -64,6 +64,8 @@ from app.services.business_context import (
load_rules_from_yaml,
)
from app.services.business_context.engine import (
+ AlertEvaluation,
+ EngineSnapshot,
_apply_action,
_projection,
evaluate_condition,
@@ -75,11 +77,13 @@ from app.services.business_context.models import (
ALLOWED_OPS,
ALLOWED_ROUTES,
ALLOWED_SEVERITIES,
+ BusinessContextRule,
RuleAction,
RuleCondition,
)
from fastapi import HTTPException
+
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@@ -152,8 +156,7 @@ class TestParser:
assert load_rules_from_yaml(" \n ") == []
def test_single_rule_shorthand(self) -> None:
- rules = load_rules_from_yaml(
- _yaml("""
+ rules = load_rules_from_yaml(_yaml("""
id: prod-iam-critical
description: Critical for prod IAM
when:
@@ -162,8 +165,7 @@ class TestParser:
value: prod
then:
set_severity: critical
- """)
- )
+ """))
assert len(rules) == 1
rule = rules[0]
assert rule.id == "prod-iam-critical"
@@ -173,8 +175,7 @@ class TestParser:
assert rule.when.value == "prod"
def test_rules_list_form(self) -> None:
- rules = load_rules_from_yaml(
- _yaml("""
+ rules = load_rules_from_yaml(_yaml("""
rules:
- id: rule-a
when: { field: alert.severity, op: eq, value: high }
@@ -182,14 +183,12 @@ class TestParser:
- id: rule-b
when: { field: alert.source, op: eq, value: aws }
then: { route_to: cloud }
- """)
- )
+ """))
assert [r.id for r in rules] == ["rule-a", "rule-b"]
assert rules[1].then.route_to == "cloud"
def test_aggregator_all_any_not(self) -> None:
- rules = load_rules_from_yaml(
- _yaml("""
+ rules = load_rules_from_yaml(_yaml("""
id: nested
when:
all:
@@ -202,8 +201,7 @@ class TestParser:
value: dev
then:
tag: cloud-prod
- """)
- )
+ """))
when = rules[0].when
assert when.logical == "all"
assert when.children[0].logical == "any"
@@ -213,13 +211,11 @@ class TestParser:
assert when.fields_referenced() == {"alert.source", "alert.target.tag"}
def test_in_op_coerces_single_string_to_list(self) -> None:
- rules = load_rules_from_yaml(
- _yaml("""
+ rules = load_rules_from_yaml(_yaml("""
id: route-aws
when: { field: alert.source, op: in, value: aws }
then: { route_to: cloud }
- """)
- )
+ """))
assert rules[0].when.value == ["aws"]
@pytest.mark.parametrize(
@@ -227,22 +223,25 @@ class TestParser:
[
("id: BAD\nwhen: { field: x, op: eq, value: y }\nthen: { tag: t }", "kebab-case"),
("id: ok-id\nthen: { set_severity: high }", "'when' clause is required"),
- ("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: { set_severity: nope }", "set_severity"),
+ ("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: { set_severity: nope }",
+ "set_severity"),
("id: ok-id\nwhen: { field: x, op: like, value: y }\nthen: { tag: t }", "is not one of"),
("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: {}", "must set at least one"),
("id: ok-id\nwhen: { field: x, op: in }\nthen: { tag: t }", "required for op="),
- ("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: { route_to: nope }", "route_to"),
+ ("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: { route_to: nope }",
+ "route_to"),
],
)
- def test_invalid_inputs_raise_with_actionable_messages(self, yaml_text: str, marker: str) -> None:
+ def test_invalid_inputs_raise_with_actionable_messages(
+ self, yaml_text: str, marker: str
+ ) -> None:
with pytest.raises(RuleParseError) as exc_info:
load_rules_from_yaml(yaml_text)
assert marker in str(exc_info.value)
def test_duplicate_ids_rejected(self) -> None:
with pytest.raises(RuleParseError, match="duplicate rule id"):
- load_rules_from_yaml(
- _yaml("""
+ load_rules_from_yaml(_yaml("""
rules:
- id: dup-rule
when: { field: a, op: eq, value: 1 }
@@ -250,8 +249,7 @@ class TestParser:
- id: dup-rule
when: { field: b, op: eq, value: 2 }
then: { set_severity: high }
- """)
- )
+ """))
def test_constants_are_locked_down(self) -> None:
# Catches accidental edits that broaden the action vocabulary —
@@ -272,13 +270,11 @@ class TestEvaluation:
tenant = uuid.uuid4()
engine.replace(
tenant,
- load_rules_from_yaml(
- _yaml("""
+ load_rules_from_yaml(_yaml("""
id: prod-critical
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical }
- """)
- ),
+ """)),
)
result = engine.evaluate(tenant, _alert(severity="medium", target_tag="prod"))
assert result.before["severity"] == "medium"
@@ -291,13 +287,11 @@ class TestEvaluation:
tenant = uuid.uuid4()
engine.replace(
tenant,
- load_rules_from_yaml(
- _yaml("""
+ load_rules_from_yaml(_yaml("""
id: prod-only
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical }
- """)
- ),
+ """)),
)
result = engine.evaluate(tenant, _alert(target_tag="dev", severity="medium"))
assert result.before == result.after
@@ -309,8 +303,7 @@ class TestEvaluation:
tenant = uuid.uuid4()
engine.replace(
tenant,
- load_rules_from_yaml(
- _yaml("""
+ load_rules_from_yaml(_yaml("""
rules:
- id: maintenance-window
priority: 1
@@ -320,8 +313,7 @@ class TestEvaluation:
priority: 50
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical }
- """)
- ),
+ """)),
)
result = engine.evaluate(tenant, _alert(target_tag="prod", severity="medium"))
assert result.suppressed is True
@@ -334,8 +326,7 @@ class TestEvaluation:
tenant = uuid.uuid4()
engine.replace(
tenant,
- load_rules_from_yaml(
- _yaml("""
+ load_rules_from_yaml(_yaml("""
rules:
- id: aws-baseline
priority: 10
@@ -345,8 +336,7 @@ class TestEvaluation:
priority: 50
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical, tag: prod }
- """)
- ),
+ """)),
)
result = engine.evaluate(tenant, _alert(source="aws", target_tag="prod"))
assert result.matched_rule_ids == ["aws-baseline", "prod-bump"]
@@ -395,8 +385,7 @@ class TestSnapshots:
tenant = uuid.uuid4()
snap = engine.replace(
tenant,
- load_rules_from_yaml(
- _yaml("""
+ load_rules_from_yaml(_yaml("""
rules:
- id: zzz
priority: 5
@@ -410,8 +399,7 @@ class TestSnapshots:
priority: 5
when: { field: z, op: eq, value: 1 }
then: { tag: mmm }
- """)
- ),
+ """)),
)
assert [r.id for r in snap.rules] == ["mmm", "zzz", "aaa"]
# Field reverse-index records all leaf paths.
@@ -429,13 +417,11 @@ class TestSnapshots:
a, b = uuid.uuid4(), uuid.uuid4()
engine.replace(
a,
- load_rules_from_yaml(
- _yaml("""
+ load_rules_from_yaml(_yaml("""
id: only-a
when: { field: x, op: eq, value: 1 }
then: { tag: a }
- """)
- ),
+ """)),
)
engine.replace(b, [])
assert engine.snapshot_for(a).rules[0].id == "only-a"
@@ -459,13 +445,11 @@ class TestPreview:
# Register an empty rule set.
engine.replace(tenant, [])
# Preview a rule that would, if registered, mutate severity.
- candidate = load_rules_from_yaml(
- _yaml("""
+ candidate = load_rules_from_yaml(_yaml("""
id: would-bump
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical }
- """)
- )
+ """))
results = engine.preview_against(
tenant,
[_alert(target_tag="prod", severity="medium")],
@@ -478,13 +462,11 @@ class TestPreview:
def test_preview_returns_one_row_per_alert(self) -> None:
engine = BusinessContextEngine()
tenant = uuid.uuid4()
- rules = load_rules_from_yaml(
- _yaml("""
+ rules = load_rules_from_yaml(_yaml("""
id: prod-critical
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical }
- """)
- )
+ """))
alerts = [
_alert("a", target_tag="prod"),
_alert("b", target_tag="dev"),
@@ -584,7 +566,11 @@ class TestEndpoints:
endpoint.update_rule(
"rule-a",
endpoint.UpdateRuleRequest(
- yaml=("id: rule-a\nwhen: { field: alert.severity, op: eq, value: high }\nthen: { route_to: tier3 }\n")
+ yaml=(
+ "id: rule-a\n"
+ "when: { field: alert.severity, op: eq, value: high }\n"
+ "then: { route_to: tier3 }\n"
+ )
),
user,
MagicMock(),
@@ -602,7 +588,13 @@ class TestEndpoints:
_run(
endpoint.update_rule(
"rule-a",
- endpoint.UpdateRuleRequest(yaml=("id: rule-other\nwhen: { field: x, op: eq, value: 1 }\nthen: { tag: t }\n")),
+ endpoint.UpdateRuleRequest(
+ yaml=(
+ "id: rule-other\n"
+ "when: { field: x, op: eq, value: 1 }\n"
+ "then: { tag: t }\n"
+ )
+ ),
user,
MagicMock(),
)
@@ -642,7 +634,11 @@ class TestEndpoints:
def test_preview_against_supplied_alerts(self) -> None:
user = _user()
req = endpoint.PreviewRequest(
- yaml=("id: prod-critical\nwhen: { field: alert.target.tag, op: eq, value: prod }\nthen: { set_severity: critical }\n"),
+ yaml=(
+ "id: prod-critical\n"
+ "when: { field: alert.target.tag, op: eq, value: prod }\n"
+ "then: { set_severity: critical }\n"
+ ),
alerts=[
_alert("a", target_tag="prod", severity="medium"),
_alert("b", target_tag="dev", severity="medium"),
@@ -680,7 +676,11 @@ class TestEndpoints:
db = MagicMock()
db.execute = AsyncMock(side_effect=RuntimeError("no schema"))
req = endpoint.PreviewRequest(
- yaml=("id: noop-tag\nwhen: { field: alert.target.tag, op: eq, value: prod }\nthen: { tag: noop }\n"),
+ yaml=(
+ "id: noop-tag\n"
+ "when: { field: alert.target.tag, op: eq, value: prod }\n"
+ "then: { tag: noop }\n"
+ ),
alerts=[],
)
resp = _run(endpoint.preview_rules(req, user, db))
@@ -707,7 +707,11 @@ class TestEndpoints:
when: { field: alert.source, op: eq, value: aws }
then: { route_to: cloud, tag: aws }
""")
- alerts = [_alert(f"alert-{i}", target_tag="prod" if i % 2 else "dev", source="aws" if i % 3 == 0 else "okta") for i in range(100)]
+ alerts = [
+ _alert(f"alert-{i}", target_tag="prod" if i % 2 else "dev",
+ source="aws" if i % 3 == 0 else "okta")
+ for i in range(100)
+ ]
start = time.perf_counter()
_run(
@@ -722,7 +726,8 @@ class TestEndpoints:
elapsed = time.perf_counter() - start
assert elapsed < 1.0, (
- f"save → evaluate round-trip took {elapsed:.3f}s, exceeds 1s budget (eval slice = {elapsed_eval:.3f}s for 100 alerts)"
+ f"save → evaluate round-trip took {elapsed:.3f}s, exceeds 1s budget "
+ f"(eval slice = {elapsed_eval:.3f}s for 100 alerts)"
)
# Sanity check: at least the prod alerts got bumped.
diff --git a/services/api/tests/test_demo_seed.py b/services/api/tests/test_demo_seed.py
index 132ae9cf6..b8ccd9c11 100644
--- a/services/api/tests/test_demo_seed.py
+++ b/services/api/tests/test_demo_seed.py
@@ -37,6 +37,7 @@ import uuid
from typing import Any
import pytest
+
from app.scripts.seed_demo import (
_DEMO_QUICK_DEFAULT_CLOCK_ISO,
_DEMO_QUICK_INCIDENTS,
@@ -104,7 +105,10 @@ def test_demo_quick_connector_sources_match_contract() -> None:
key = incident["key"]
actual = set(incident["connector_sources"])
expected = EXPECTED_CONNECTOR_SOURCES[key]
- assert actual == expected, f"{key}: connector_sources drifted. expected {sorted(expected)}, got {sorted(actual)}"
+ assert actual == expected, (
+ f"{key}: connector_sources drifted. "
+ f"expected {sorted(expected)}, got {sorted(actual)}"
+ )
def test_demo_quick_alerts_reference_declared_connectors() -> None:
@@ -188,10 +192,11 @@ def test_demo_quick_seed_persists_four_cases() -> None:
# Local import so the heavy SQLAlchemy + asyncpg dependency chain
# doesn't load when the integration test is skipped (which is the
# common case on a developer laptop).
+ from sqlalchemy import select
+
from app.db.database import AsyncSessionLocal
from app.models.case import Case
from app.scripts.seed_demo import _parse_clock, _run_quick_seed
- from sqlalchemy import select
async def _run_and_count() -> list[Case]:
await _run_quick_seed(clock=_parse_clock(None))
@@ -203,7 +208,8 @@ def test_demo_quick_seed_persists_four_cases() -> None:
cases = asyncio.run(_run_and_count())
by_key: dict[str, Case] = {c.key: c for c in cases}
assert set(by_key.keys()) == set(EXPECTED_DEMO_KEYS), (
- f"Quick seed did not produce exactly the four DEMO-* cases. Got keys: {sorted(by_key.keys())}"
+ f"Quick seed did not produce exactly the four DEMO-* cases. "
+ f"Got keys: {sorted(by_key.keys())}"
)
# Walk the persisted metadata to confirm connector_sources made it
@@ -214,5 +220,6 @@ def test_demo_quick_seed_persists_four_cases() -> None:
meta: dict[str, Any] = case.case_metadata or {}
sources = set(meta.get("connector_sources") or [])
assert sources == EXPECTED_CONNECTOR_SOURCES[key], (
- f"{key}: persisted connector_sources={sorted(sources)} does not match contract={sorted(EXPECTED_CONNECTOR_SOURCES[key])}"
+ f"{key}: persisted connector_sources={sorted(sources)} "
+ f"does not match contract={sorted(EXPECTED_CONNECTOR_SOURCES[key])}"
)
diff --git a/services/api/tests/test_effective_permissions_aws.py b/services/api/tests/test_effective_permissions_aws.py
index bf95d679a..e5b5049ee 100644
--- a/services/api/tests/test_effective_permissions_aws.py
+++ b/services/api/tests/test_effective_permissions_aws.py
@@ -106,7 +106,9 @@ def _action_match(stmt_actions: Any, action: str) -> bool:
return False
-def _gather_identity_policies(principal: dict[str, Any], snap: dict[str, Any]) -> list[dict[str, Any]]:
+def _gather_identity_policies(
+ principal: dict[str, Any], snap: dict[str, Any]
+) -> list[dict[str, Any]]:
policies_by_id = {p["id"]: p for p in snap["policies"]}
groups_by_id = {g["id"]: g for g in snap.get("groups", [])}
refs: list[str] = []
@@ -141,7 +143,9 @@ def reference_is_allowed(
resource_arn = resource["arn"]
# 1. Explicit deny across identity / resource / SCP wins outright.
- deny_sources: list[dict[str, Any]] = list(_gather_identity_policies(principal, snapshot))
+ deny_sources: list[dict[str, Any]] = list(
+ _gather_identity_policies(principal, snapshot)
+ )
rp_id = resource.get("resource_policy_id")
if rp_id and rp_id in policies_by_id:
deny_sources.append(policies_by_id[rp_id])
@@ -154,7 +158,9 @@ def reference_is_allowed(
for stmt in _as_list(policy.get("document", {}).get("Statement")):
if stmt.get("Effect") != "Deny":
continue
- if is_resource_policy and not _principal_match(stmt.get("Principal"), principal["arn"]):
+ if is_resource_policy and not _principal_match(
+ stmt.get("Principal"), principal["arn"]
+ ):
continue
if not _resource_match(stmt.get("Resource", "*"), resource_arn):
continue
@@ -222,7 +228,11 @@ def reference_decision(
resource = next(r for r in snapshot["resources"] if r["id"] == resource_id)
catalogue = resource.get("service_actions") or []
- return {action for action in catalogue if reference_is_allowed(snapshot, principal_id, resource_id, action)}
+ return {
+ action
+ for action in catalogue
+ if reference_is_allowed(snapshot, principal_id, resource_id, action)
+ }
# ---------------------------------------------------------------------------
@@ -239,7 +249,11 @@ def snapshot() -> dict[str, Any]:
def _all_pairs(snapshot: dict[str, Any]) -> list[tuple[str, str]]:
"""Generate the cartesian product of principals × resources."""
- return [(p["id"], r["id"]) for p in snapshot["principals"] for r in snapshot["resources"]]
+ return [
+ (p["id"], r["id"])
+ for p in snapshot["principals"]
+ for r in snapshot["resources"]
+ ]
# ---------------------------------------------------------------------------
@@ -274,7 +288,10 @@ def reference_pairs(snapshot: dict[str, Any]) -> list[tuple[str, str, set[str]]]
]
pairs = base + extras
assert len(pairs) >= 50, f"expected ≥50 pairs, got {len(pairs)}"
- return [(pid, rid, reference_decision(snapshot, pid, rid)) for pid, rid in pairs[:50]]
+ return [
+ (pid, rid, reference_decision(snapshot, pid, rid))
+ for pid, rid in pairs[:50]
+ ]
def test_resolver_matches_reference_simulator_on_50_pairs(
@@ -297,10 +314,15 @@ def test_resolver_matches_reference_simulator_on_50_pairs(
)
actual = set(match.actions) if match is not None else set()
if actual != expected:
- mismatches.append(f"{principal_id} ↔ {resource_id}: resolver={sorted(actual)} simulator={sorted(expected)}")
+ mismatches.append(
+ f"{principal_id} ↔ {resource_id}: "
+ f"resolver={sorted(actual)} simulator={sorted(expected)}"
+ )
assert not mismatches, (
- f"resolver disagreed with the reference simulator on {len(mismatches)} of {len(reference_pairs)} pairs:\n" + "\n".join(mismatches)
+ f"resolver disagreed with the reference simulator on "
+ f"{len(mismatches)} of {len(reference_pairs)} pairs:\n"
+ + "\n".join(mismatches)
)
@@ -313,7 +335,9 @@ def test_resolver_carries_policy_chain_for_every_decision(
for principal in snapshot["principals"]:
result = resolver.resolve(principal["id"])
for decision in result.decisions:
- assert decision.policy_chain, f"missing chain for {principal['id']} → {decision.resource_id}"
+ assert decision.policy_chain, (
+ f"missing chain for {principal['id']} → {decision.resource_id}"
+ )
def test_resolver_surfaces_shadowed_denies_on_kms_key(
@@ -326,11 +350,19 @@ def test_resolver_surfaces_shadowed_denies_on_kms_key(
"""
resolver = AwsIamResolver(snapshot=snapshot)
- alice = next(d for d in resolver.resolve("u-alice").decisions if d.resource_id == "res-key-finance")
+ alice = next(
+ d
+ for d in resolver.resolve("u-alice").decisions
+ if d.resource_id == "res-key-finance"
+ )
assert "kms:ScheduleKeyDeletion" not in alice.actions
assert "kms:ScheduleKeyDeletion" not in alice.deny_actions
- dave = next(d for d in resolver.resolve("u-dave").decisions if d.resource_id == "res-key-finance")
+ dave = next(
+ d
+ for d in resolver.resolve("u-dave").decisions
+ if d.resource_id == "res-key-finance"
+ )
assert "kms:ScheduleKeyDeletion" not in dave.actions
assert "kms:ScheduleKeyDeletion" in dave.deny_actions
@@ -340,7 +372,11 @@ def test_scp_caps_dave_admin_on_iam_writes(snapshot: dict[str, Any]) -> None:
Role / iam:DeleteRole / iam:AttachRolePolicy must still cap him."""
resolver = AwsIamResolver(snapshot=snapshot)
- dave_iam = next(d for d in resolver.resolve("u-dave").decisions if d.resource_id == "res-iam-role-readonly")
+ dave_iam = next(
+ d
+ for d in resolver.resolve("u-dave").decisions
+ if d.resource_id == "res-iam-role-readonly"
+ )
assert "iam:CreateRole" not in dave_iam.actions
assert "iam:DeleteRole" not in dave_iam.actions
assert "iam:AttachRolePolicy" not in dave_iam.actions
@@ -354,7 +390,11 @@ def test_resource_policy_unlocks_pipeline_on_artifacts(
the bucket policy allows ``s3:GetObject`` for ``Principal: *``."""
resolver = AwsIamResolver(snapshot=snapshot)
- pipeline = next(d for d in resolver.resolve("r-pipeline").decisions if d.resource_id == "res-bucket-artifacts")
+ pipeline = next(
+ d
+ for d in resolver.resolve("r-pipeline").decisions
+ if d.resource_id == "res-bucket-artifacts"
+ )
assert "s3:GetObject" in pipeline.actions
@@ -366,7 +406,11 @@ def test_condition_blocks_erin_in_other_region(
Flipping the context to a different region must drop her access."""
resolver = AwsIamResolver(snapshot=snapshot)
- erin = next(d for d in resolver.resolve("u-erin").decisions if d.resource_id == "res-bucket-reports")
+ erin = next(
+ d
+ for d in resolver.resolve("u-erin").decisions
+ if d.resource_id == "res-bucket-reports"
+ )
assert "s3:GetObject" in erin.actions
altered = json.loads(json.dumps(snapshot))
diff --git a/services/api/tests/test_insights_endpoint.py b/services/api/tests/test_insights_endpoint.py
index 57e1ccee8..529c9e1b4 100644
--- a/services/api/tests/test_insights_endpoint.py
+++ b/services/api/tests/test_insights_endpoint.py
@@ -37,6 +37,7 @@ from app.api.v1.endpoints.insights import (
)
from fastapi import HTTPException
+
# ---------------------------------------------------------------------------
# Pure helpers
# ---------------------------------------------------------------------------
diff --git a/services/api/tests/test_saved_hunts_endpoint.py b/services/api/tests/test_saved_hunts_endpoint.py
index c4017b903..d9559687c 100644
--- a/services/api/tests/test_saved_hunts_endpoint.py
+++ b/services/api/tests/test_saved_hunts_endpoint.py
@@ -56,6 +56,7 @@ from app.api.v1.endpoints.saved_hunts import (
from fastapi import HTTPException
from sqlalchemy.exc import IntegrityError
+
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@@ -106,7 +107,8 @@ def _saved_hunt_row(
created_by=created_by,
name=name,
nl_query=nl_query,
- translated_query=translated or {"esql": "FROM logs-* | LIMIT 10", "kql": "", "spl": "", "explanation": ""},
+ translated_query=translated
+ or {"esql": "FROM logs-* | LIMIT 10", "kql": "", "spl": "", "explanation": ""},
language=language,
schedule=schedule,
last_run_at=last_run_at,
@@ -221,9 +223,7 @@ def test_create_request_rejects_unknown_language() -> None:
"""Language is restricted to ``esql | kql | spl``."""
with pytest.raises(pydantic.ValidationError):
CreateSavedHuntRequest(
- name="x",
- nl_query="failed logins",
- language="xquery", # type: ignore[arg-type]
+ name="x", nl_query="failed logins", language="xquery" # type: ignore[arg-type]
)
@@ -331,12 +331,14 @@ def test_create_saved_hunt_translates_and_persists(monkeypatch: pytest.MonkeyPat
# Stub the translator so the test doesn't depend on the live grammar
# (the actual translator is exercised separately in nl_query tests).
fake_envelope = TranslatedQueryEnvelope(
- esql='FROM logs-* | WHERE source.geo.country_iso_code == "IR" | LIMIT 500',
- kql='SecurityEvent | where source_geo_country_iso_code == "IR" | take 500',
+ esql="FROM logs-* | WHERE source.geo.country_iso_code == \"IR\" | LIMIT 500",
+ kql="SecurityEvent | where source_geo_country_iso_code == \"IR\" | take 500",
spl='index=* source_geo_country_iso_code="IR"',
explanation="Translates the question by filtering on country code IR.",
)
- monkeypatch.setattr("app.api.v1.endpoints.saved_hunts._translate", lambda _q: fake_envelope)
+ monkeypatch.setattr(
+ "app.api.v1.endpoints.saved_hunts._translate", lambda _q: fake_envelope
+ )
captured: dict[str, Any] = {}
@@ -422,7 +424,9 @@ def test_create_saved_hunt_with_invalid_schedule_422s_before_db(
monkeypatch.setattr("app.api.v1.endpoints.saved_hunts._translate", _spy)
db = _mock_scalar_db(None)
- payload = CreateSavedHuntRequest(name="Iran inbound", nl_query="failed logins", schedule="not a cron")
+ payload = CreateSavedHuntRequest(
+ name="Iran inbound", nl_query="failed logins", schedule="not a cron"
+ )
with pytest.raises(HTTPException) as exc:
asyncio.run(create_saved_hunt(payload, user, db))
assert exc.value.status_code == 422
@@ -504,7 +508,7 @@ def test_run_saved_hunt_re_translates_and_stamps(monkeypatch: pytest.MonkeyPatch
row = _saved_hunt_row(tenant_id=user.tenant_id)
db = _mock_scalar_db(row)
fresh = TranslatedQueryEnvelope(
- esql='FROM logs-* | WHERE source.geo.country_iso_code == "IR" | LIMIT 500',
+ esql="FROM logs-* | WHERE source.geo.country_iso_code == \"IR\" | LIMIT 500",
)
monkeypatch.setattr("app.api.v1.endpoints.saved_hunts._translate", lambda _q: fresh)
@@ -552,7 +556,9 @@ def test_scheduler_picks_up_due_hunt_and_fires_callback() -> None:
captured: dict[str, Any] = {"executor": [], "callback": []}
- async def _fake_executor(_db: Any, hunt: Any) -> int: # noqa: ANN401
+ async def _fake_executor(
+ _db: Any, hunt: Any
+ ) -> int: # noqa: ANN401
captured["executor"].append(hunt.id)
return 7
diff --git a/services/api/tests/test_tenant_provision.py b/services/api/tests/test_tenant_provision.py
index 74018221e..2d0e702ad 100644
--- a/services/api/tests/test_tenant_provision.py
+++ b/services/api/tests/test_tenant_provision.py
@@ -26,6 +26,8 @@ from types import SimpleNamespace
from typing import Any
import pytest
+from fastapi import HTTPException
+
from app.api.v1.endpoints import tenant_provision as endpoint
from app.models.tenant import Tenant, User
from app.models.waitlist import (
@@ -55,7 +57,7 @@ from app.services.tenant_provision.templates import (
TenantTemplateBundle,
get_default_template_bundle,
)
-from fastapi import HTTPException
+
# ---------------------------------------------------------------------------
# Test helpers
@@ -194,7 +196,7 @@ class _MockExecuteResult:
def scalar_one_or_none(self) -> Any:
return self._rows[0] if self._rows else None
- def scalars(self) -> _MockExecuteResult:
+ def scalars(self) -> "_MockExecuteResult":
return self
def all(self) -> list[Any]:
@@ -324,7 +326,9 @@ class TestAdminInviteBuilder:
def test_zero_ttl_rejected(self) -> None:
with pytest.raises(ValueError):
- _build_admin_invite(tenant_slug="x", invite_base_url="x", ttl_hours=0)
+ _build_admin_invite(
+ tenant_slug="x", invite_base_url="x", ttl_hours=0
+ )
# ---------------------------------------------------------------------------
@@ -381,7 +385,9 @@ class TestProvisionFromWaitlist:
)
tenant = session.tenants[result.tenant_id]
- assert tenant.settings["aisoc_credential_key_fingerprint"] == (result.aisoc_credential_key_fingerprint)
+ assert tenant.settings["aisoc_credential_key_fingerprint"] == (
+ result.aisoc_credential_key_fingerprint
+ )
# The plaintext key must NEVER land in the settings blob.
for value in tenant.settings.values():
if isinstance(value, str):
@@ -585,7 +591,9 @@ class TestProvisionEndpoint:
response = _run(
endpoint.provision_tenant(
- endpoint.TenantProvisionRequest(waitlist_entry_id=entry.id, seed_demo=False),
+ endpoint.TenantProvisionRequest(
+ waitlist_entry_id=entry.id, seed_demo=False
+ ),
session, # type: ignore[arg-type]
user,
)
@@ -605,7 +613,9 @@ class TestProvisionEndpoint:
with pytest.raises(HTTPException) as exc_info:
_run(
endpoint.provision_tenant(
- endpoint.TenantProvisionRequest(waitlist_entry_id=entry.id, seed_demo=False),
+ endpoint.TenantProvisionRequest(
+ waitlist_entry_id=entry.id, seed_demo=False
+ ),
session, # type: ignore[arg-type]
user,
)
@@ -618,7 +628,9 @@ class TestProvisionEndpoint:
with pytest.raises(HTTPException) as exc_info:
_run(
endpoint.provision_tenant(
- endpoint.TenantProvisionRequest(waitlist_entry_id=uuid.uuid4(), seed_demo=False),
+ endpoint.TenantProvisionRequest(
+ waitlist_entry_id=uuid.uuid4(), seed_demo=False
+ ),
session, # type: ignore[arg-type]
user,
)
@@ -634,7 +646,9 @@ class TestProvisionEndpoint:
with pytest.raises(HTTPException) as exc_info:
_run(
endpoint.provision_tenant(
- endpoint.TenantProvisionRequest(waitlist_entry_id=entry.id, seed_demo=False),
+ endpoint.TenantProvisionRequest(
+ waitlist_entry_id=entry.id, seed_demo=False
+ ),
session, # type: ignore[arg-type]
user,
)
@@ -658,7 +672,9 @@ class TestProvisionEndpoint:
user,
)
)
- assert response.admin_invite.url.startswith("https://staging.aisoc.dev/invite/")
+ assert response.admin_invite.url.startswith(
+ "https://staging.aisoc.dev/invite/"
+ )
class TestListTenantsEndpoint:
diff --git a/services/api/tests/test_waitlist.py b/services/api/tests/test_waitlist.py
index 307ba029a..f2996aeb1 100644
--- a/services/api/tests/test_waitlist.py
+++ b/services/api/tests/test_waitlist.py
@@ -39,8 +39,11 @@ import uuid
from datetime import UTC, datetime
from types import SimpleNamespace
from typing import Any
+from unittest.mock import AsyncMock, MagicMock
import pytest
+from fastapi import HTTPException, Request, Response
+
from app.api.v1.endpoints import waitlist as endpoint
from app.models.waitlist import (
WAITLIST_STATUS_CONTACTED,
@@ -54,7 +57,7 @@ from app.services.waitlist import (
SlackNotifier,
build_signup_message,
)
-from fastapi import HTTPException, Request, Response
+
# ---------------------------------------------------------------------------
# Test helpers
@@ -131,7 +134,7 @@ class _MockSession:
rows = list(self.rows.values())
# WHERE id = :id
- for _clause in getattr(stmt, "whereclause", None) and [stmt.whereclause] or []:
+ for clause in getattr(stmt, "whereclause", None) and [stmt.whereclause] or []:
pass # SQLAlchemy compiled expressions don't easily yield bind values
# Easier: walk the stmt._where_criteria.
# We'll just inspect the compiled clause string.
@@ -184,7 +187,7 @@ class _MockExecuteResult:
def scalar_one_or_none(self) -> WaitlistEntry | None:
return self._rows[0] if self._rows else None
- def scalars(self) -> _MockExecuteResult:
+ def scalars(self) -> "_MockExecuteResult":
return self
def all(self) -> list[WaitlistEntry]:
@@ -226,7 +229,7 @@ class TestSignupRequestValidation:
assert payload.role == "SOC Manager"
def test_invalid_email_rejected(self) -> None:
- with pytest.raises(Exception): # noqa: B017 — Pydantic ValidationError surface
+ with pytest.raises(Exception):
endpoint.WaitlistSignupRequest(
email="not-an-email",
company="Acme",
@@ -255,7 +258,7 @@ class TestSignupRequestValidation:
assert len(payload.soc_stack) <= 20
def test_blank_motivation_rejected(self) -> None:
- with pytest.raises(Exception): # noqa: B017 — Pydantic ValidationError surface
+ with pytest.raises(Exception):
endpoint.WaitlistSignupRequest(
company="Acme",
@@ -588,7 +591,7 @@ class TestAdminPatchEndpoint:
assert exc_info.value.status_code == 404
def test_patch_invalid_status_rejected_at_payload_layer(self) -> None:
- with pytest.raises(Exception): # noqa: B017 — Pydantic ValidationError surface
+ with pytest.raises(Exception):
endpoint.WaitlistPatchRequest(status="nope")
diff --git a/services/connectors/app/connectors/aws_security_hub.py b/services/connectors/app/connectors/aws_security_hub.py
index 2e5674ec1..0286fce07 100644
--- a/services/connectors/app/connectors/aws_security_hub.py
+++ b/services/connectors/app/connectors/aws_security_hub.py
@@ -182,7 +182,9 @@ class AWSSecurityHubConnector(BaseConnector):
return {"error": "trail not found"}
trail = trails[0]
try:
- selectors = ct.get_event_selectors(TrailName=trail_arn).get("EventSelectors", [])
+ selectors = ct.get_event_selectors(TrailName=trail_arn).get(
+ "EventSelectors", []
+ )
except Exception: # noqa: BLE001
selectors = []
return {
@@ -236,7 +238,9 @@ class AWSSecurityHubConnector(BaseConnector):
break
if not chosen:
return {"error": "no policy versions"}
- doc = iam.get_policy_version(PolicyArn=policy_arn, VersionId=chosen["VersionId"]).get("PolicyVersion", {}).get("Document", {})
+ doc = iam.get_policy_version(
+ PolicyArn=policy_arn, VersionId=chosen["VersionId"]
+ ).get("PolicyVersion", {}).get("Document", {})
return {
"resource_type": "AWS::IAM::ManagedPolicy",
"policy_arn": policy_arn,
@@ -253,9 +257,8 @@ class AWSSecurityHubConnector(BaseConnector):
# and let it parse. If Config isn't recording the resource we get
# an empty configurationItems list and surface that cleanly.
try:
- from datetime import datetime as _dt
-
import boto3
+ from datetime import datetime as _dt
kwargs: dict[str, Any] = {"region_name": self._region}
if self._access_key and self._secret_key:
@@ -279,7 +282,9 @@ class AWSSecurityHubConnector(BaseConnector):
params["resourceType"] = "AWS::" + arn_parts[2].capitalize() + "::Resource"
if target:
params["laterTime"] = target
- items = cfgc.get_resource_config_history(**params).get("configurationItems", [])
+ items = cfgc.get_resource_config_history(**params).get(
+ "configurationItems", []
+ )
if not items:
return {"error": "not recorded"}
return {
diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.py
index d4c98372f..cb519c038 100644
--- a/services/connectors/app/connectors/base.py
+++ b/services/connectors/app/connectors/base.py
@@ -409,6 +409,37 @@ class BaseConnector(ABC):
# - Errors should propagate as exceptions; the snapshotter will
# log + skip without stalling ingest.
+ async def get_resource_config(
+ self, resource_id: str, ts: str
+ ) -> dict[str, Any]:
+ """Return the resource's configuration that was effective at ``ts``.
+
+ Args:
+ resource_id: Connector-native identifier (ARN for AWS, full
+ repo name for GitHub, app id for Okta, resource id for
+ Azure, asset name for GCP). The ingest writer pulls this
+ from the same property the T1.1 extractor stamped on the
+ ``:Resource`` / ``:Repo`` / ``:SaaSApp`` node.
+ ts: RFC3339 timestamp in UTC. Connectors that expose
+ configuration history (AWS Config, Azure Activity Log,
+ GitHub branch protection diffs) MUST return the snapshot
+ effective at this time. Connectors that expose only the
+ current config MAY ignore ``ts`` and return live state.
+
+ Returns:
+ JSON-serialisable dict with the configuration payload. Shape
+ is connector-defined; the ingest writer doesn't introspect
+ it. Empty dict means "no config available" — the snapshotter
+ treats that as a soft skip.
+
+ Raises:
+ NotImplementedError: connector does not implement T1.2 config
+ snapshots. Default for the base class.
+ """
+ raise NotImplementedError(
+ f"connector '{self.connector_id}' does not implement get_resource_config"
+ )
+
# ----------------------------- federated search --------------------------
# Connectors that opt into federated search override ``supports_federated_search``
diff --git a/services/connectors/app/connectors/cloudflare_zt.py b/services/connectors/app/connectors/cloudflare_zt.py
index 360b4d4bd..3e38fb1d3 100644
--- a/services/connectors/app/connectors/cloudflare_zt.py
+++ b/services/connectors/app/connectors/cloudflare_zt.py
@@ -71,7 +71,10 @@ class CloudflareZTConnector(BaseConnector):
{"value": "waf", "label": "WAF / firewall events"},
{"value": "access", "label": "Zero Trust Access audit"},
],
- help_text=("Pick which stream this instance pulls. Run two instances side-by-side for full coverage."),
+ help_text=(
+ "Pick which stream this instance pulls. Run two "
+ "instances side-by-side for full coverage."
+ ),
),
Field(
"account_id",
@@ -93,7 +96,9 @@ class CloudflareZTConnector(BaseConnector):
"secret",
"API Token",
help_text=(
- "Account-scoped token with Zone:Firewall Services:Read (WAF) AND Account:Access Audit Logs:Read (Zero Trust)."
+ "Account-scoped token with Zone:Firewall "
+ "Services:Read (WAF) AND Account:Access "
+ "Audit Logs:Read (Zero Trust)."
),
),
],
@@ -164,7 +169,10 @@ class CloudflareZTConnector(BaseConnector):
return {
"success": False,
"connector": self.connector_id,
- "error": (f"token verified but {self._mode} probe HTTP {probe.status_code}: {probe.text[:200]}"),
+ "error": (
+ f"token verified but {self._mode} probe HTTP "
+ f"{probe.status_code}: {probe.text[:200]}"
+ ),
}
return {
"success": True,
diff --git a/services/connectors/app/connectors/datadog.py b/services/connectors/app/connectors/datadog.py
index b29eae301..6b06eb660 100644
--- a/services/connectors/app/connectors/datadog.py
+++ b/services/connectors/app/connectors/datadog.py
@@ -43,13 +43,7 @@ _REGION_HOSTS: dict[str, str] = {
}
_LOGS_PER_PAGE = 100
-# Note: the Datadog Events v1 API (``GET /api/v1/events``) is windowed by
-# ``start``/``end`` epoch seconds, not by an explicit page-size knob, so we
-# do not pass a ``limit`` here. Previously this module also declared an
-# ``_EVENTS_PER_PAGE`` constant that was never read — CodeQL flagged it as
-# ``py/unused-global-variable`` and it has been removed. If pagination is
-# added later, wire it into ``_fetch_events`` rather than reintroducing an
-# unused global.
+_EVENTS_PER_PAGE = 500
_MAX_PAGES = 25
@@ -102,7 +96,10 @@ class DatadogConnector(BaseConnector):
"Filter query",
required=False,
default="status:error OR status:critical",
- help_text=("Logs Search query (logs mode) or tag filter (events mode, e.g. 'priority:all')."),
+ help_text=(
+ "Logs Search query (logs mode) or tag filter "
+ "(events mode, e.g. 'priority:all')."
+ ),
),
Field("api_key", "secret", "API Key"),
Field("application_key", "secret", "Application Key"),
diff --git a/services/connectors/app/connectors/dropbox.py b/services/connectors/app/connectors/dropbox.py
index 058b5dc33..7942c53b5 100644
--- a/services/connectors/app/connectors/dropbox.py
+++ b/services/connectors/app/connectors/dropbox.py
@@ -48,7 +48,11 @@ class DropboxConnector(BaseConnector):
connector_id=cls.connector_id,
connector_name=cls.connector_name,
category=cls.connector_category,
- description=("Dropbox Business team event log: sharing, sign-in, member role changes, OAuth-app authorisations, policy edits."),
+ description=(
+ "Dropbox Business team event log: sharing, sign-in, "
+ "member role changes, OAuth-app authorisations, "
+ "policy edits."
+ ),
docs_url="/docs/connectors/dropbox",
fields=[
Field(
@@ -56,7 +60,9 @@ class DropboxConnector(BaseConnector):
"secret",
"Team admin token",
help_text=(
- "OAuth 2.0 token for a Dropbox Business app with the ``team_data.governance.read`` and ``events.read`` scopes."
+ "OAuth 2.0 token for a Dropbox Business app "
+ "with the ``team_data.governance.read`` and "
+ "``events.read`` scopes."
),
),
],
@@ -104,8 +110,7 @@ class DropboxConnector(BaseConnector):
return {"success": False, "connector": self.connector_id, "error": str(exc)}
async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
- from datetime import UTC, datetime, timedelta
-
+ from datetime import datetime, timedelta, UTC
since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
out: list[dict[str, Any]] = []
cursor: str | None = None
@@ -167,9 +172,7 @@ class DropboxConnector(BaseConnector):
event_type = (raw.get("event_type") or {}).get(".tag") or raw.get("event_type", "")
if isinstance(event_type, dict):
event_type = event_type.get(".tag", "")
- category = (
- (raw.get("event_category") or {}).get(".tag") if isinstance(raw.get("event_category"), dict) else raw.get("event_category", "")
- )
+ category = (raw.get("event_category") or {}).get(".tag") if isinstance(raw.get("event_category"), dict) else raw.get("event_category", "")
actor = raw.get("actor") or {}
# actor is a tagged-union; flatten
actor_user = (actor.get("user") or {}) if isinstance(actor, dict) else {}
@@ -188,7 +191,10 @@ class DropboxConnector(BaseConnector):
"source": self.connector_id,
"external_id": raw.get("event_id") or "",
"title": event_type or "Dropbox event",
- "description": (f"event={event_type}; category={category}; actor={actor_email}"),
+ "description": (
+ f"event={event_type}; category={category}; "
+ f"actor={actor_email}"
+ ),
"severity": severity,
"actor": actor_email or actor_user.get("display_name"),
"actor_email": actor_email,
diff --git a/services/connectors/app/connectors/falco.py b/services/connectors/app/connectors/falco.py
index b5cd0dd42..cb48ec7c9 100644
--- a/services/connectors/app/connectors/falco.py
+++ b/services/connectors/app/connectors/falco.py
@@ -94,9 +94,7 @@ class FalcoConnector(BaseConnector):
{"value": "ALERT", "label": "ALERT"},
{"value": "EMERGENCY", "label": "EMERGENCY"},
],
- help_text=(
- "Drop events whose Falco priority is below this threshold. Defaults to DEBUG so nothing is filtered server-side."
- ),
+ help_text=("Drop events whose Falco priority is below this threshold. Defaults to DEBUG so nothing is filtered server-side."),
),
],
oauth=OAuthHints(supported_in_hosted=False),
diff --git a/services/connectors/app/connectors/github.py b/services/connectors/app/connectors/github.py
index 905286496..a86f4946e 100644
--- a/services/connectors/app/connectors/github.py
+++ b/services/connectors/app/connectors/github.py
@@ -380,7 +380,9 @@ class GitHubConnector(BaseConnector):
async with httpx.AsyncClient(timeout=15.0) as client:
try:
- repo_resp = await client.get(f"{_BASE}/repos/{owner_repo}", headers=self._headers())
+ repo_resp = await client.get(
+ f"{_BASE}/repos/{owner_repo}", headers=self._headers()
+ )
except Exception as exc: # noqa: BLE001
return {"error": str(exc), "snapshot_freshness": "unavailable"}
if repo_resp.status_code != 200:
diff --git a/services/connectors/app/connectors/lacework.py b/services/connectors/app/connectors/lacework.py
index 5b44980c7..a7a7a2c88 100644
--- a/services/connectors/app/connectors/lacework.py
+++ b/services/connectors/app/connectors/lacework.py
@@ -168,7 +168,9 @@ class LaceworkConnector(BaseConnector):
"startTime": start.strftime("%Y-%m-%dT%H:%M:%SZ"),
"endTime": end.strftime("%Y-%m-%dT%H:%M:%SZ"),
},
- "filters": [{"field": "status", "expression": "eq", "value": "NonCompliant"}],
+ "filters": [
+ {"field": "status", "expression": "eq", "value": "NonCompliant"}
+ ],
},
)
if ce_resp.status_code == 200:
@@ -197,9 +199,6 @@ class LaceworkConnector(BaseConnector):
kind = raw.get("_kind", "alert")
if kind == "policy":
return self._normalize_policy(raw)
- # Lacework alerts expose info/low/medium/high/critical. Mirror
- # all five tiers (including ``critical``) into AiSOC's ladder
- # rather than collapsing critical to high.
sev_raw = (raw.get("severity") or "").lower()
if sev_raw in ("info", "low", "medium", "high", "critical"):
sev = sev_raw
diff --git a/services/connectors/app/connectors/pagerduty.py b/services/connectors/app/connectors/pagerduty.py
index cf5d417bb..acffa8310 100644
--- a/services/connectors/app/connectors/pagerduty.py
+++ b/services/connectors/app/connectors/pagerduty.py
@@ -66,9 +66,7 @@ class PagerDutyConnector(BaseConnector):
"Subdomain (optional)",
required=False,
placeholder="acme",
- help_text=(
- "Your acme.pagerduty.com subdomain. Used to build clickable links in normalised events; not required for ingestion."
- ),
+ help_text=("Your acme.pagerduty.com subdomain. Used to build clickable links in normalised events; not required for ingestion."),
),
],
oauth=OAuthHints(
@@ -288,22 +286,15 @@ class PagerDutyConnector(BaseConnector):
assignees = raw.get("assignments") or []
assignee_email = None
if assignees and isinstance(assignees[0], dict):
- assignee_email = (
- ((assignees[0].get("assignee") or {}).get("summary")) if isinstance(assignees[0].get("assignee"), dict) else None
- )
+ assignee_email = ((assignees[0].get("assignee") or {}).get("summary")) if isinstance(assignees[0].get("assignee"), dict) else None
- link = raw.get("html_url") or (
- f"https://{self._subdomain}.pagerduty.com/incidents/{raw.get('id')}" if self._subdomain and raw.get("id") else None
- )
+ link = raw.get("html_url") or (f"https://{self._subdomain}.pagerduty.com/incidents/{raw.get('id')}" if self._subdomain and raw.get("id") else None)
return {
"source": self.connector_id,
"external_id": f"pagerduty-incident-{raw.get('id', raw.get('incident_number', ''))}",
"title": raw.get("title") or raw.get("description") or "PagerDuty incident",
- "description": (
- f"service={service or 'unknown'}; status={status}; "
- f"urgency={urgency}; priority={priority_name or 'none'}; url={link or 'n/a'}"
- ),
+ "description": (f"service={service or 'unknown'}; status={status}; urgency={urgency}; priority={priority_name or 'none'}; url={link or 'n/a'}"),
"severity": severity,
"actor": assignee_email,
"actor_email": assignee_email,
@@ -329,10 +320,7 @@ class PagerDutyConnector(BaseConnector):
"source": self.connector_id,
"external_id": f"pagerduty-audit-{raw.get('id', '')}",
"title": f"PagerDuty audit: {action}",
- "description": (
- f"actor={actor_email or 'unknown'}; action={action}; "
- f"method={raw.get('method', {}).get('type', '') if isinstance(raw.get('method'), dict) else ''}"
- ),
+ "description": (f"actor={actor_email or 'unknown'}; action={action}; method={raw.get('method', {}).get('type', '') if isinstance(raw.get('method'), dict) else ''}"),
"severity": severity,
"actor": actor_email,
"actor_email": actor_email,
diff --git a/services/connectors/app/connectors/snowflake.py b/services/connectors/app/connectors/snowflake.py
index 79b2668c2..0d0767957 100644
--- a/services/connectors/app/connectors/snowflake.py
+++ b/services/connectors/app/connectors/snowflake.py
@@ -141,10 +141,9 @@ class SnowflakeConnector(BaseConnector):
run without a real key."""
try:
from cryptography.hazmat.primitives.serialization import (
- Encoding,
- PublicFormat,
load_pem_private_key,
)
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
priv = load_pem_private_key(self._private_key_pem.encode(), password=None)
der = priv.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
@@ -170,7 +169,9 @@ class SnowflakeConnector(BaseConnector):
"exp": now + 3600,
}
signing_input = (
- _b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + _b64url(json.dumps(payload, separators=(",", ":")).encode())
+ _b64url(json.dumps(header, separators=(",", ":")).encode())
+ + "."
+ + _b64url(json.dumps(payload, separators=(",", ":")).encode())
).encode()
priv = serialization.load_pem_private_key(self._private_key_pem.encode(), password=None)
signature = priv.sign(signing_input, padding.PKCS1v15(), hashes.SHA256())
@@ -202,7 +203,7 @@ class SnowflakeConnector(BaseConnector):
payload = resp.json() or {}
cols = [c.get("name") for c in payload.get("resultSetMetaData", {}).get("rowType") or []]
rows = payload.get("data") or []
- return [dict(zip(cols, row, strict=False)) for row in rows]
+ return [dict(zip(cols, row)) for row in rows]
async def test_connection(self) -> dict[str, Any]:
try:
@@ -306,7 +307,10 @@ class SnowflakeConnector(BaseConnector):
"source": self.connector_id,
"stream": "login_history",
"external_id": raw.get("EVENT_ID") or "",
- "title": (f"Snowflake login {'success' if is_success else 'failure'} ({raw.get('USER_NAME')})"),
+ "title": (
+ f"Snowflake login {'success' if is_success else 'failure'} "
+ f"({raw.get('USER_NAME')})"
+ ),
"description": raw.get("ERROR_MESSAGE") or raw.get("REPORTED_CLIENT_TYPE"),
"severity": severity,
"actor": raw.get("USER_NAME"),
diff --git a/services/connectors/app/connectors/sublime_security.py b/services/connectors/app/connectors/sublime_security.py
index d3835f6ee..6d5bea73b 100644
--- a/services/connectors/app/connectors/sublime_security.py
+++ b/services/connectors/app/connectors/sublime_security.py
@@ -168,7 +168,10 @@ class SublimeSecurityConnector(BaseConnector):
"source": self.connector_id,
"external_id": raw.get("id") or raw.get("message_id") or "",
"title": raw.get("subject") or rule_name or "Sublime Security message",
- "description": (f"verdict={verdict}; rule={rule_name}; from={sender.get('email')}; to={recipient}"),
+ "description": (
+ f"verdict={verdict}; rule={rule_name}; "
+ f"from={sender.get('email')}; to={recipient}"
+ ),
"severity": severity,
"actor": sender.get("email"),
"actor_email": sender.get("email"),
diff --git a/services/connectors/app/connectors/sysdig.py b/services/connectors/app/connectors/sysdig.py
index 2f8b68b33..25e3a676c 100644
--- a/services/connectors/app/connectors/sysdig.py
+++ b/services/connectors/app/connectors/sysdig.py
@@ -76,7 +76,10 @@ class SysdigConnector(BaseConnector):
"api_token",
"secret",
"API Token",
- help_text=("Sysdig Secure API token. Settings → API → Tokens. Needs read access to Secure Events."),
+ help_text=(
+ "Sysdig Secure API token. Settings → API → Tokens. "
+ "Needs read access to Secure Events."
+ ),
),
],
)
@@ -211,7 +214,12 @@ class SysdigConnector(BaseConnector):
# canonical Falco "you do not want to see this in prod" signals and
# are never benign once they fire.
rule_lower = rule.lower()
- if "drift" in rule_lower or "tampering" in rule_lower or "terminal shell" in rule_lower or "shell in container" in rule_lower:
+ if (
+ "drift" in rule_lower
+ or "tampering" in rule_lower
+ or "terminal shell" in rule_lower
+ or "shell in container" in rule_lower
+ ):
sev = "high"
host = labels.get("host.hostname") or labels.get("kubernetes.node.name") or raw.get("hostname")
ns = labels.get("kubernetes.namespace.name")
diff --git a/services/connectors/app/connectors/tines.py b/services/connectors/app/connectors/tines.py
index 2bc139b37..bc642cc56 100644
--- a/services/connectors/app/connectors/tines.py
+++ b/services/connectors/app/connectors/tines.py
@@ -69,7 +69,8 @@ class TinesConnector(BaseConnector):
"Tines tenant URL",
placeholder="https://acme.tines.com",
help_text=(
- "Your Tines tenant URL, including scheme. For self-hosted deployments use the full HTTPS URL of the Rails app."
+ "Your Tines tenant URL, including scheme. For self-hosted "
+ "deployments use the full HTTPS URL of the Rails app."
),
),
Field(
@@ -332,9 +333,7 @@ class TinesConnector(BaseConnector):
"source": self.connector_id,
"external_id": f"tines-case-{raw.get('id', '')}",
"title": f"Tines case: {case_name}",
- "description": (
- f"status={status}; record_severity={record_sev}; story_id={raw.get('story_id', '')}; assignee={assignee or 'unassigned'}"
- ),
+ "description": (f"status={status}; record_severity={record_sev}; story_id={raw.get('story_id', '')}; assignee={assignee or 'unassigned'}"),
"severity": severity,
"actor": assignee or "unassigned",
"actor_email": assignee,
diff --git a/services/connectors/app/connectors/vault.py b/services/connectors/app/connectors/vault.py
index 18376f8f9..abdbe2f2c 100644
--- a/services/connectors/app/connectors/vault.py
+++ b/services/connectors/app/connectors/vault.py
@@ -198,7 +198,6 @@ class VaultConnector(BaseConnector):
if isinstance(ts, str):
try:
from datetime import datetime
-
parsed = datetime.fromisoformat(ts.replace("Z", "+00:00"))
ts_epoch = parsed.timestamp()
except Exception:
diff --git a/services/connectors/tests/connectors/test_cloudflare_zt.py b/services/connectors/tests/connectors/test_cloudflare_zt.py
index ba2d98ed3..dbbee4a12 100644
--- a/services/connectors/tests/connectors/test_cloudflare_zt.py
+++ b/services/connectors/tests/connectors/test_cloudflare_zt.py
@@ -108,8 +108,12 @@ async def test_fetch_alerts_uses_pagination(fixture):
@respx.mock
async def test_test_connection_success():
c = CloudflareZTConnector(mode="access", account_id="a", api_token="t")
- respx.get("https://api.cloudflare.com/client/v4/user/tokens/verify").respond(200, json={"result": {"status": "active"}})
- respx.get("https://api.cloudflare.com/client/v4/accounts/a/access/logs/access_requests").respond(200, json={"result": []})
+ respx.get("https://api.cloudflare.com/client/v4/user/tokens/verify").respond(
+ 200, json={"result": {"status": "active"}}
+ )
+ respx.get(
+ "https://api.cloudflare.com/client/v4/accounts/a/access/logs/access_requests"
+ ).respond(200, json={"result": []})
res = await c.test_connection()
assert res["success"] is True
assert res["mode"] == "access"
@@ -119,7 +123,9 @@ async def test_test_connection_success():
@respx.mock
async def test_test_connection_token_inactive():
c = CloudflareZTConnector(mode="access", account_id="a", api_token="t")
- respx.get("https://api.cloudflare.com/client/v4/user/tokens/verify").respond(200, json={"result": {"status": "disabled"}})
+ respx.get("https://api.cloudflare.com/client/v4/user/tokens/verify").respond(
+ 200, json={"result": {"status": "disabled"}}
+ )
res = await c.test_connection()
assert res["success"] is False
assert "disabled" in res["error"]
diff --git a/services/connectors/tests/connectors/test_confluence_audit.py b/services/connectors/tests/connectors/test_confluence_audit.py
index f73052300..065f5b24a 100644
--- a/services/connectors/tests/connectors/test_confluence_audit.py
+++ b/services/connectors/tests/connectors/test_confluence_audit.py
@@ -77,10 +77,7 @@ def test_normalize_creation_date_ms_to_iso(fixture):
@pytest.mark.asyncio
@respx.mock
-async def test_fetch_alerts_uses_pagination(
- fixture: dict,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
+async def test_fetch_alerts_uses_pagination(fixture):
calls = 0
def handler(request: httpx.Request) -> httpx.Response:
@@ -96,12 +93,15 @@ async def test_fetch_alerts_uses_pagination(
respx.get(f"{_SITE}/wiki/rest/api/audit").mock(side_effect=handler)
connector = ConfluenceAuditConnector(_SITE, _EMAIL, _TOKEN)
- # Lower the page size to match the fixture. ``monkeypatch`` rewrites the
- # module attribute and restores it automatically at teardown, so we keep
- # a single import style for the connector module (CodeQL
- # ``py/import-and-import-from``).
- monkeypatch.setattr("app.connectors.confluence_audit._PAGE_SIZE", 4)
- events = await connector.fetch_alerts(since_seconds=10**9)
+ # Lower the page size to match the fixture.
+ import app.connectors.confluence_audit as mod
+
+ monkey_orig = mod._PAGE_SIZE # noqa: SLF001
+ try:
+ mod._PAGE_SIZE = 4 # type: ignore[assignment]
+ events = await connector.fetch_alerts(since_seconds=10**9)
+ finally:
+ mod._PAGE_SIZE = monkey_orig # type: ignore[assignment]
# First page returned 4 items, second page returned []; pagination
# terminated cleanly.
diff --git a/services/connectors/tests/connectors/test_sysdig.py b/services/connectors/tests/connectors/test_sysdig.py
index aa95e2416..13214173f 100644
--- a/services/connectors/tests/connectors/test_sysdig.py
+++ b/services/connectors/tests/connectors/test_sysdig.py
@@ -75,7 +75,6 @@ async def test_fetch_alerts_uses_pagination(fixture):
# Pad page-1 to exactly _PER_PAGE=100 to force a second iteration via
# the cursor branch. _PER_PAGE is the connector's internal pagination size.
from app.connectors.sysdig import _PER_PAGE
-
fat_page = (fixture * 50)[:_PER_PAGE]
page1 = {"data": fat_page, "page": {"next": "cursor-2"}}
page2 = {"data": fixture[:1], "page": {}}
diff --git a/services/ingest/internal/config/config.go b/services/ingest/internal/config/config.go
index db1f32aab..77203dbdd 100644
--- a/services/ingest/internal/config/config.go
+++ b/services/ingest/internal/config/config.go
@@ -85,6 +85,23 @@ type Config struct {
// (T1.4) for live graph-update streaming. Empty means "don't publish".
GraphUpdatesTopic string
+ // GraphWSEnabled toggles the in-process T1.4 graph-update
+ // WebSocket broadcaster. When on, the ingest binary spins up a
+ // Kafka consumer against GraphUpdatesTopic and exposes
+ // /v1/graph_ws/stream for tenant-scoped fan-out. The Python API
+ // proxy at services/api/app/api/v1/endpoints/graph_ws.py is the
+ // public-facing entry point and is what end users connect to —
+ // the ingest endpoint is internal.
+ GraphWSEnabled bool
+ // GraphWSGroupID overrides the Kafka consumer group used by the
+ // broadcaster. Defaults to "graph-ws-<hostname>" so every pod
+ // sees every envelope (live-tail semantics, no partitioning).
+ GraphWSGroupID string
+ // GraphWSSubscriberBuffer is the per-client buffer size in
+ // envelopes. Healthy clients see every event; a slow client
+ // drops on full buffer.
+ GraphWSSubscriberBuffer int
+
// Config snapshots (T1.2 — v8.0).
//
// SnapshotEnabled toggles the per-event resource config snapshotter.
@@ -161,6 +178,14 @@ func Load() (*Config, error) {
GraphQueueSize: mustGetEnvInt("AISOC_GRAPH_QUEUE_SIZE", 2048),
GraphUpdatesTopic: getEnv("AISOC_GRAPH_UPDATES_TOPIC", "security.graph_updates"),
+ // Graph-update WebSocket fan-out (T1.4, v8.0). Disabled by
+ // default — operators flip AISOC_GRAPH_WS_ENABLED=true once
+ // the consumer side (Python API proxy + web hook) is
+ // rolled out.
+ GraphWSEnabled: getEnv("AISOC_GRAPH_WS_ENABLED", "false") == "true",
+ GraphWSGroupID: getEnv("AISOC_GRAPH_WS_GROUP_ID", ""),
+ GraphWSSubscriberBuffer: mustGetEnvInt("AISOC_GRAPH_WS_BUFFER", 256),
+
// Config snapshots (T1.2, v8.0). Disabled by default — operators
// flip AISOC_SNAPSHOT_ENABLED=true once the connectors service
// exposes the resource-config endpoint.
diff --git a/services/ingest/internal/graph_ws/broadcaster.go b/services/ingest/internal/graph_ws/broadcaster.go
new file mode 100644
index 000000000..ad36d5f02
--- /dev/null
+++ b/services/ingest/internal/graph_ws/broadcaster.go
@@ -0,0 +1,257 @@
+// Package graph_ws fans out security.graph_updates Kafka events to
+// connected WebSocket clients in real time (T1.4 — v8.0).
+//
+// The broadcaster owns three responsibilities:
+//
+// 1. Consume the Kafka topic the ingest-side graph writer (T1.1)
+// publishes to. Each message is a graph.GraphUpdate envelope.
+// 2. Demux per-tenant: the Kafka envelope carries tenant_id; the
+// broadcaster maintains a tenant -> subscribers map so a client
+// opened with ?tenant_id=X only receives updates whose tenant_id
+// matches X (or are unscoped, for the global cross-tenant admin
+// view which is currently not exposed to end users).
+// 3. Fan out with backpressure: each subscriber has a bounded buffer.
+// If the buffer is full (a slow client) the broadcaster drops the
+// in-flight message for that subscriber and increments
+// droppedDeliveries — it must NEVER block the Kafka consumer
+// loop, because that would back-pressure into the producer.
+//
+// The package is consumer-only and stateless across restarts; it does
+// not maintain Kafka offsets in any external store. A new pod that
+// joins the consumer group will start from the configured offset
+// (typically "latest"). This matches the realtime contract — the WS
+// is a live tail, not a replay surface.
+package graph_ws
+
+import (
+ "context"
+ "encoding/json"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/beenuar/aisoc/services/ingest/internal/graph"
+)
+
+// subscriberBufferDefault is the per-client buffer size. Keep small —
+// the goal is "live tail with backpressure", not "deliver every event
+// no matter what". A slow client will see drops; a healthy client sees
+// every event because the producer side runs ahead of any reasonable
+// consumer pace.
+const subscriberBufferDefault = 256
+
+// EnvelopeSource is anything that yields graph.GraphUpdate envelopes.
+// The production implementation wraps segmentio/kafka-go; tests inject
+// a channel-backed fake (see broadcaster_test.go) so the broadcaster's
+// fan-out semantics can be exercised without Kafka.
+type EnvelopeSource interface {
+ // Next blocks until the next envelope is available or ctx is
+ // cancelled. On cancellation it returns (zero, ctx.Err()).
+ Next(ctx context.Context) (graph.GraphUpdate, error)
+ // Close releases resources. Idempotent.
+ Close() error
+}
+
+// Subscriber represents a single connected WebSocket client. The
+// broadcaster owns the lifecycle of the channel — Subscribe creates
+// it, Unsubscribe drains and closes it.
+type Subscriber struct {
+ // TenantID is the scope this subscriber sees. Empty means "all
+ // tenants"; reserved for cross-tenant admin tools and never
+ // exposed via the tenant-scoped HTTP entry point.
+ TenantID string
+
+ // Updates is the read side. Each message is one envelope.
+ Updates chan graph.GraphUpdate
+
+ id uint64
+}
+
+// Broadcaster fans out envelopes from a single EnvelopeSource to many
+// Subscribers. Safe for concurrent use.
+type Broadcaster struct {
+ src EnvelopeSource
+
+ mu sync.RWMutex
+ subscribers map[uint64]*Subscriber
+
+ nextID atomic.Uint64
+
+ bufferSize int
+
+ dropped atomic.Uint64
+
+ stopCh chan struct{}
+ doneCh chan struct{}
+}
+
+// Options tunes broadcaster construction.
+type Options struct {
+ // BufferSize overrides subscriberBufferDefault. Zero falls back
+ // to the default; negative is rejected at construction.
+ BufferSize int
+}
+
+// New constructs a broadcaster wired to src. Call Start to begin
+// consuming; until then no envelopes flow.
+func New(src EnvelopeSource, opts Options) *Broadcaster {
+ buf := opts.BufferSize
+ if buf <= 0 {
+ buf = subscriberBufferDefault
+ }
+ return &Broadcaster{
+ src: src,
+ subscribers: make(map[uint64]*Subscriber),
+ bufferSize: buf,
+ stopCh: make(chan struct{}),
+ doneCh: make(chan struct{}),
+ }
+}
+
+// Start launches the consumer goroutine. It returns immediately; the
+// goroutine runs until ctx is cancelled or Stop is called. Calling
+// Start more than once is a programmer error.
+func (b *Broadcaster) Start(ctx context.Context) {
+ // Derive a child context we control so Stop() can unblock a
+ // consumer wedged inside src.Next without waiting for the
+ // caller's ctx to be cancelled. We propagate cancellation in
+ // both directions: parent ctx cancel propagates via the
+ // context.WithCancel chain, and our stopCh fan-out below
+ // triggers our local cancel.
+ derived, cancel := context.WithCancel(ctx)
+ go func() {
+ select {
+ case <-b.stopCh:
+ cancel()
+ case <-derived.Done():
+ }
+ }()
+ go func() {
+ defer cancel()
+ b.consumeLoop(derived)
+ }()
+}
+
+// Stop signals the consumer to exit and waits for it to finish.
+// Safe to call multiple times.
+func (b *Broadcaster) Stop() {
+ select {
+ case <-b.stopCh:
+ // already closed
+ default:
+ close(b.stopCh)
+ }
+ <-b.doneCh
+}
+
+// Subscribe registers a new client with the broadcaster using the
+// broadcaster's default buffer size. tenantID scopes which envelopes
+// the subscriber sees; empty tenantID means "all" (admin-only, not
+// reachable from the public HTTP path).
+func (b *Broadcaster) Subscribe(tenantID string) *Subscriber {
+ return b.SubscribeWithBuffer(tenantID, b.bufferSize)
+}
+
+// SubscribeWithBuffer is like Subscribe but lets the caller pick a
+// per-subscriber buffer size. Tests use this to compose a "slow"
+// subscriber (tiny buffer) alongside a "healthy" subscriber (large
+// buffer) so the backpressure contract can be exercised against a
+// single broadcaster.
+func (b *Broadcaster) SubscribeWithBuffer(tenantID string, buf int) *Subscriber {
+ if buf <= 0 {
+ buf = b.bufferSize
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ id := b.nextID.Add(1)
+ sub := &Subscriber{
+ TenantID: tenantID,
+ Updates: make(chan graph.GraphUpdate, buf),
+ id: id,
+ }
+ b.subscribers[id] = sub
+ return sub
+}
+
+// Unsubscribe removes the subscriber and closes its channel. Safe to
+// call multiple times.
+func (b *Broadcaster) Unsubscribe(sub *Subscriber) {
+ if sub == nil {
+ return
+ }
+ b.mu.Lock()
+ _, ok := b.subscribers[sub.id]
+ if ok {
+ delete(b.subscribers, sub.id)
+ }
+ b.mu.Unlock()
+ if ok {
+ close(sub.Updates)
+ }
+}
+
+// SubscriberCount returns the number of currently-connected
+// subscribers. Useful for /metrics and tests.
+func (b *Broadcaster) SubscriberCount() int {
+ b.mu.RLock()
+ defer b.mu.RUnlock()
+ return len(b.subscribers)
+}
+
+// DroppedDeliveries returns the cumulative count of envelopes dropped
+// because a subscriber buffer was full. Reset on process restart.
+func (b *Broadcaster) DroppedDeliveries() uint64 {
+ return b.dropped.Load()
+}
+
+func (b *Broadcaster) consumeLoop(ctx context.Context) {
+ defer close(b.doneCh)
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-b.stopCh:
+ return
+ default:
+ }
+ env, err := b.src.Next(ctx)
+ if err != nil {
+ if ctx.Err() != nil {
+ return
+ }
+ select {
+ case <-b.stopCh:
+ return
+ case <-time.After(50 * time.Millisecond):
+ }
+ continue
+ }
+ b.dispatch(env)
+ }
+}
+
+func (b *Broadcaster) dispatch(env graph.GraphUpdate) {
+ b.mu.RLock()
+ targets := make([]*Subscriber, 0, len(b.subscribers))
+ for _, sub := range b.subscribers {
+ if sub.TenantID != "" && env.TenantID != "" && sub.TenantID != env.TenantID {
+ continue
+ }
+ targets = append(targets, sub)
+ }
+ b.mu.RUnlock()
+ for _, sub := range targets {
+ select {
+ case sub.Updates <- env:
+ default:
+ b.dropped.Add(1)
+ }
+ }
+}
+
+// MarshalEnvelope is a small helper exported for the server: the
+// upgrade handler writes envelopes as JSON to the wire, and using a
+// single marshal path keeps the on-wire contract stable.
+func MarshalEnvelope(env graph.GraphUpdate) ([]byte, error) {
+ return json.Marshal(env)
+}
diff --git a/services/ingest/internal/graph_ws/broadcaster_test.go b/services/ingest/internal/graph_ws/broadcaster_test.go
new file mode 100644
index 000000000..b964bfcc2
--- /dev/null
+++ b/services/ingest/internal/graph_ws/broadcaster_test.go
@@ -0,0 +1,216 @@
+// Tests for the graph_ws Broadcaster (T1.4 — v8.0).
+package graph_ws
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/beenuar/aisoc/services/ingest/internal/graph"
+)
+
+// fakeSource is a deterministic EnvelopeSource backed by a buffered
+// channel. The constructor pre-loads N envelopes; Next drains them
+// in order and then blocks until ctx is cancelled.
+type fakeSource struct {
+ ch chan graph.GraphUpdate
+ closed chan struct{}
+ once sync.Once
+}
+
+func newFakeSource(envs []graph.GraphUpdate) *fakeSource {
+ ch := make(chan graph.GraphUpdate, len(envs))
+ for _, e := range envs {
+ ch <- e
+ }
+ return &fakeSource{ch: ch, closed: make(chan struct{})}
+}
+
+func (f *fakeSource) Next(ctx context.Context) (graph.GraphUpdate, error) {
+ select {
+ case e, ok := <-f.ch:
+ if !ok {
+ return graph.GraphUpdate{}, fmt.Errorf("source drained")
+ }
+ return e, nil
+ case <-ctx.Done():
+ return graph.GraphUpdate{}, ctx.Err()
+ case <-f.closed:
+ return graph.GraphUpdate{}, fmt.Errorf("source closed")
+ }
+}
+
+func (f *fakeSource) Close() error {
+ f.once.Do(func() { close(f.closed) })
+ return nil
+}
+
+// TestBroadcasterDelivers100EventsWithinOneSecond is the gate the
+// T1.4 spec calls out: 100 envelopes pushed into a fake Kafka
+// consumer must all reach a connected subscriber within 1s.
+func TestBroadcasterDelivers100EventsWithinOneSecond(t *testing.T) {
+ const eventCount = 100
+ envs := make([]graph.GraphUpdate, 0, eventCount)
+ for i := 0; i < eventCount; i++ {
+ envs = append(envs, graph.GraphUpdate{
+ EntityID: fmt.Sprintf("entity-%d", i),
+ ChangeType: graph.ChangeUpsertNode,
+ TS: time.Now(),
+ Label: graph.NodeAlert,
+ TenantID: "tenant-A",
+ SchemaVersion: graph.SchemaVersion,
+ })
+ }
+ src := newFakeSource(envs)
+ b := New(src, Options{BufferSize: eventCount * 2})
+
+ sub := b.Subscribe("tenant-A")
+ defer b.Unsubscribe(sub)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ b.Start(ctx)
+ defer b.Stop()
+
+ deadline := time.Now().Add(1 * time.Second)
+ received := 0
+ seen := make(map[string]struct{}, eventCount)
+ for received < eventCount {
+ remaining := time.Until(deadline)
+ if remaining <= 0 {
+ t.Fatalf("only received %d/%d envelopes before 1s deadline", received, eventCount)
+ }
+ select {
+ case env := <-sub.Updates:
+ if _, dup := seen[env.EntityID]; dup {
+ t.Fatalf("duplicate envelope for entity %s", env.EntityID)
+ }
+ seen[env.EntityID] = struct{}{}
+ received++
+ case <-time.After(remaining):
+ t.Fatalf("only received %d/%d envelopes before 1s deadline", received, eventCount)
+ }
+ }
+
+ if received != eventCount {
+ t.Fatalf("expected %d envelopes, got %d", eventCount, received)
+ }
+ if dropped := b.DroppedDeliveries(); dropped != 0 {
+ t.Fatalf("expected zero drops with a healthy subscriber, got %d", dropped)
+ }
+}
+
+// TestBroadcasterTenantScope confirms a subscriber pinned to a
+// tenant does not see other tenants' envelopes.
+func TestBroadcasterTenantScope(t *testing.T) {
+ envs := []graph.GraphUpdate{
+ {EntityID: "e-A1", TenantID: "tenant-A", ChangeType: graph.ChangeUpsertNode, SchemaVersion: graph.SchemaVersion},
+ {EntityID: "e-B1", TenantID: "tenant-B", ChangeType: graph.ChangeUpsertNode, SchemaVersion: graph.SchemaVersion},
+ {EntityID: "e-A2", TenantID: "tenant-A", ChangeType: graph.ChangeUpsertNode, SchemaVersion: graph.SchemaVersion},
+ {EntityID: "e-B2", TenantID: "tenant-B", ChangeType: graph.ChangeUpsertNode, SchemaVersion: graph.SchemaVersion},
+ }
+ src := newFakeSource(envs)
+ b := New(src, Options{})
+ subA := b.Subscribe("tenant-A")
+ defer b.Unsubscribe(subA)
+ subB := b.Subscribe("tenant-B")
+ defer b.Unsubscribe(subB)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ b.Start(ctx)
+ defer b.Stop()
+
+ collect := func(ch <-chan graph.GraphUpdate, want int) []graph.GraphUpdate {
+ t.Helper()
+ out := make([]graph.GraphUpdate, 0, want)
+ deadline := time.After(500 * time.Millisecond)
+ for len(out) < want {
+ select {
+ case env := <-ch:
+ out = append(out, env)
+ case <-deadline:
+ t.Fatalf("only got %d/%d envelopes", len(out), want)
+ }
+ }
+ return out
+ }
+
+ gotA := collect(subA.Updates, 2)
+ gotB := collect(subB.Updates, 2)
+ for _, e := range gotA {
+ if e.TenantID != "tenant-A" {
+ t.Fatalf("subA leaked envelope from %s", e.TenantID)
+ }
+ }
+ for _, e := range gotB {
+ if e.TenantID != "tenant-B" {
+ t.Fatalf("subB leaked envelope from %s", e.TenantID)
+ }
+ }
+}
+
+// TestBroadcasterBackpressureDropsForSlowClient confirms a slow
+// subscriber records drops but never blocks the consumer loop or
+// other (healthy) subscribers.
+func TestBroadcasterBackpressureDropsForSlowClient(t *testing.T) {
+ const eventCount = 50
+ envs := make([]graph.GraphUpdate, 0, eventCount)
+ for i := 0; i < eventCount; i++ {
+ envs = append(envs, graph.GraphUpdate{
+ EntityID: fmt.Sprintf("entity-%d", i),
+ TenantID: "tenant-A",
+ ChangeType: graph.ChangeUpsertNode,
+ SchemaVersion: graph.SchemaVersion,
+ })
+ }
+ src := newFakeSource(envs)
+ b := New(src, Options{})
+
+ slow := b.SubscribeWithBuffer("tenant-A", 4)
+ healthy := b.SubscribeWithBuffer("tenant-A", eventCount*2)
+ defer b.Unsubscribe(slow)
+ defer b.Unsubscribe(healthy)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ b.Start(ctx)
+ defer b.Stop()
+
+ deadline := time.After(1 * time.Second)
+ received := 0
+ for received < eventCount {
+ select {
+ case <-healthy.Updates:
+ received++
+ case <-deadline:
+ t.Fatalf("healthy subscriber received only %d/%d envelopes", received, eventCount)
+ }
+ }
+ if dropped := b.DroppedDeliveries(); dropped == 0 {
+ t.Fatalf("expected drops from slow subscriber with buffer=4 and 50 envelopes, got 0")
+ }
+}
+
+// TestBroadcasterStopReleases ensures Stop returns promptly and is
+// idempotent.
+func TestBroadcasterStopReleases(t *testing.T) {
+ src := newFakeSource(nil)
+ b := New(src, Options{})
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ b.Start(ctx)
+ done := make(chan struct{})
+ go func() {
+ b.Stop()
+ b.Stop()
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-time.After(500 * time.Millisecond):
+ t.Fatal("Stop did not return within 500ms")
+ }
+}
diff --git a/services/ingest/internal/graph_ws/kafka_source.go b/services/ingest/internal/graph_ws/kafka_source.go
new file mode 100644
index 000000000..9ca479bcc
--- /dev/null
+++ b/services/ingest/internal/graph_ws/kafka_source.go
@@ -0,0 +1,122 @@
+// Kafka adapter for the graph_ws broadcaster (T1.4 — v8.0).
+//
+// A KafkaSource wraps segmentio/kafka-go's Reader so the broadcaster
+// doesn't have to know about Kafka semantics. The Reader is configured
+// for "live tail": it joins a uniquely-named consumer group so each
+// pod sees every envelope, and starts from latest so we never replay
+// stale graph history when a websocket pod recycles.
+package graph_ws
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+
+ "github.com/beenuar/aisoc/services/ingest/internal/graph"
+ kafka "github.com/segmentio/kafka-go"
+)
+
+// KafkaSourceConfig describes how to attach to the graph-updates topic.
+type KafkaSourceConfig struct {
+ // Brokers is a comma-separated bootstrap server list.
+ Brokers string
+ // Topic is the graph-updates topic. Production: "security.graph_updates".
+ Topic string
+ // GroupID is the consumer group. Empty => derived from hostname so
+ // every pod consumes every message (live-tail semantics).
+ GroupID string
+ // StartOffset chooses where a new group reads from. Accepts
+ // kafka.FirstOffset or kafka.LastOffset; defaults to LastOffset
+ // because the WS contract is "live tail, no replay".
+ StartOffset int64
+}
+
+// KafkaSource is the production EnvelopeSource. It owns a kafka.Reader
+// and decodes each message into a graph.GraphUpdate.
+type KafkaSource struct {
+ reader *kafka.Reader
+}
+
+// NewKafkaSource builds a KafkaSource. The caller is responsible for
+// calling Close to release the underlying connection.
+func NewKafkaSource(cfg KafkaSourceConfig) (*KafkaSource, error) {
+ if cfg.Brokers == "" {
+ return nil, fmt.Errorf("graph_ws: kafka brokers required")
+ }
+ if cfg.Topic == "" {
+ return nil, fmt.Errorf("graph_ws: kafka topic required")
+ }
+ group := cfg.GroupID
+ if group == "" {
+ host, _ := os.Hostname()
+ if host == "" {
+ host = "graph-ws"
+ }
+ group = "graph-ws-" + host
+ }
+ start := cfg.StartOffset
+ if start == 0 {
+ start = kafka.LastOffset
+ }
+ rd := kafka.NewReader(kafka.ReaderConfig{
+ Brokers: splitCSV(cfg.Brokers),
+ Topic: cfg.Topic,
+ GroupID: group,
+ StartOffset: start,
+ MinBytes: 1,
+ MaxBytes: 10 * 1024 * 1024,
+ })
+ return &KafkaSource{reader: rd}, nil
+}
+
+// Next implements EnvelopeSource.
+func (k *KafkaSource) Next(ctx context.Context) (graph.GraphUpdate, error) {
+ msg, err := k.reader.ReadMessage(ctx)
+ if err != nil {
+ return graph.GraphUpdate{}, err
+ }
+ var env graph.GraphUpdate
+ if err := json.Unmarshal(msg.Value, &env); err != nil {
+ return graph.GraphUpdate{}, fmt.Errorf("graph_ws: decode envelope: %w", err)
+ }
+ if env.TenantID == "" {
+ for _, h := range msg.Headers {
+ if h.Key == "tenant_id" {
+ env.TenantID = string(h.Value)
+ break
+ }
+ }
+ }
+ return env, nil
+}
+
+// Close implements EnvelopeSource.
+func (k *KafkaSource) Close() error {
+ if k.reader == nil {
+ return nil
+ }
+ return k.reader.Close()
+}
+
+func splitCSV(s string) []string {
+ out := []string{}
+ cur := ""
+ for _, r := range s {
+ if r == ',' {
+ if cur != "" {
+ out = append(out, cur)
+ cur = ""
+ }
+ continue
+ }
+ if r == ' ' {
+ continue
+ }
+ cur += string(r)
+ }
+ if cur != "" {
+ out = append(out, cur)
+ }
+ return out
+}
diff --git a/services/ingest/internal/graph_ws/server.go b/services/ingest/internal/graph_ws/server.go
new file mode 100644
index 000000000..43b09c12c
--- /dev/null
+++ b/services/ingest/internal/graph_ws/server.go
@@ -0,0 +1,292 @@
+// HTTP upgrade handler for the graph_ws broadcaster (T1.4 — v8.0).
+//
+// The handler is intentionally minimal: tenant-scoped channels keyed
+// off the ``?tenant_id=<id>`` query param, no auth (auth is enforced
+// by the Python API proxy at services/api/app/api/v1/endpoints/
+// graph_ws.py — this server is expected to listen on the internal
+// service network only). Each connection registers a Subscriber with
+// the Broadcaster and pumps envelopes from the bounded buffer to the
+// websocket until the client disconnects.
+//
+// We deliberately avoid pulling in github.com/gorilla/websocket or
+// github.com/coder/websocket here — every new transitive dep on the
+// ingest binary widens the security surface and slows the build. The
+// graph-updates payload is JSON and clients are friendly browsers, so
+// a tiny stdlib-only RFC6455 upgrade implementation is enough. If we
+// ever need binary frames, compression, or ping/pong tuning, swap to
+// a library; the surface this server exports is small.
+package graph_ws
+
+import (
+ "crypto/sha1"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+)
+
+// wsHandshakeMagic is the fixed GUID from RFC 6455 §1.3 used to
+// derive the Sec-WebSocket-Accept response header.
+const wsHandshakeMagic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+
+// writeTimeout caps a single frame write so a wedged TCP socket
+// can't pin the dispatcher goroutine.
+const writeTimeout = 5 * time.Second
+
+// Server is the HTTP upgrade entry point. It is created once,
+// registered on the ingest router, and serves every websocket
+// upgrade against the same Broadcaster.
+type Server struct {
+ broker *Broadcaster
+}
+
+// NewServer pairs a Broadcaster with an HTTP handler.
+func NewServer(broker *Broadcaster) *Server {
+ return &Server{broker: broker}
+}
+
+// Handler returns an http.Handler that upgrades GET requests to a
+// websocket and pumps tenant-scoped graph updates to the client.
+//
+// Path-level routing is left to the host router; this handler does
+// not care which URL it lives at as long as the request method is
+// GET and the WebSocket handshake headers are present.
+func (s *Server) Handler() http.Handler {
+ return http.HandlerFunc(s.handle)
+}
+
+func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ tenantID := strings.TrimSpace(r.URL.Query().Get("tenant_id"))
+ if tenantID == "" {
+ tenantID = strings.TrimSpace(r.Header.Get("X-Tenant-ID"))
+ }
+ if tenantID == "" {
+ http.Error(w, "tenant_id required", http.StatusBadRequest)
+ return
+ }
+
+ if !isWebSocketHandshake(r) {
+ http.Error(w, "websocket upgrade required", http.StatusBadRequest)
+ return
+ }
+
+ hj, ok := w.(http.Hijacker)
+ if !ok {
+ http.Error(w, "websocket not supported", http.StatusInternalServerError)
+ return
+ }
+
+ key := r.Header.Get("Sec-WebSocket-Key")
+ if key == "" {
+ http.Error(w, "missing Sec-WebSocket-Key", http.StatusBadRequest)
+ return
+ }
+
+ conn, brw, err := hj.Hijack()
+ if err != nil {
+ http.Error(w, "hijack failed", http.StatusInternalServerError)
+ return
+ }
+ defer conn.Close()
+
+ accept := computeAcceptKey(key)
+ resp := "HTTP/1.1 101 Switching Protocols\r\n" +
+ "Upgrade: websocket\r\n" +
+ "Connection: Upgrade\r\n" +
+ "Sec-WebSocket-Accept: " + accept + "\r\n" +
+ "\r\n"
+ if _, err := brw.WriteString(resp); err != nil {
+ return
+ }
+ if err := brw.Flush(); err != nil {
+ return
+ }
+
+ sub := s.broker.Subscribe(tenantID)
+ defer s.broker.Unsubscribe(sub)
+
+ // Reader goroutine: we don't expect inbound application messages,
+ // but we must drain any frames the client sends (pings, close)
+ // to detect disconnects and to keep the TCP read side draining.
+ clientGone := make(chan struct{})
+ go func() {
+ defer close(clientGone)
+ for {
+ opcode, _, err := readFrame(brw.Reader)
+ if err != nil {
+ return
+ }
+ if opcode == 0x8 { // close
+ return
+ }
+ // ignore text/binary/ping for now; pong is handled by
+ // browsers automatically when we send pings, which we do
+ // not currently do.
+ }
+ }()
+
+ for {
+ select {
+ case <-r.Context().Done():
+ return
+ case <-clientGone:
+ return
+ case env, ok := <-sub.Updates:
+ if !ok {
+ return
+ }
+ payload, err := MarshalEnvelope(env)
+ if err != nil {
+ continue
+ }
+ if err := writeTextFrame(conn, brw, payload); err != nil {
+ return
+ }
+ }
+ }
+}
+
+func isWebSocketHandshake(r *http.Request) bool {
+ if !headerContains(r.Header, "Connection", "upgrade") {
+ return false
+ }
+ if !headerContains(r.Header, "Upgrade", "websocket") {
+ return false
+ }
+ if r.Header.Get("Sec-WebSocket-Version") != "13" {
+ return false
+ }
+ return true
+}
+
+func headerContains(h http.Header, key, value string) bool {
+ values := h.Values(key)
+ lv := strings.ToLower(value)
+ for _, v := range values {
+ for _, tok := range strings.Split(v, ",") {
+ if strings.EqualFold(strings.TrimSpace(tok), lv) {
+ return true
+ }
+ if strings.Contains(strings.ToLower(tok), lv) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func computeAcceptKey(key string) string {
+ h := sha1.New()
+ h.Write([]byte(key + wsHandshakeMagic))
+ return base64.StdEncoding.EncodeToString(h.Sum(nil))
+}
+
+// writeTextFrame encodes payload as a single unmasked text frame and
+// flushes it through the buffered writer.
+func writeTextFrame(deadlineConn deadlineSetter, brw bufferedWriterFlusher, payload []byte) error {
+ if err := deadlineConn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
+ return err
+ }
+ header := []byte{0x81} // FIN + opcode=text
+ plen := len(payload)
+ switch {
+ case plen <= 125:
+ header = append(header, byte(plen))
+ case plen <= 65535:
+ header = append(header, 126)
+ header = append(header, byte(plen>>8), byte(plen))
+ default:
+ header = append(header, 127)
+ for i := 7; i >= 0; i-- {
+ header = append(header, byte(plen>>(uint(i)*8)))
+ }
+ }
+ if _, err := brw.Write(header); err != nil {
+ return err
+ }
+ if _, err := brw.Write(payload); err != nil {
+ return err
+ }
+ return brw.Flush()
+}
+
+// readFrame parses a single RFC6455 frame from r. We only need the
+// opcode and the payload length on the client→server direction, but
+// we still consume the payload so the buffered reader advances.
+func readFrame(r io.Reader) (opcode byte, payload []byte, err error) {
+ hdr := make([]byte, 2)
+ if _, err = io.ReadFull(r, hdr); err != nil {
+ return 0, nil, err
+ }
+ opcode = hdr[0] & 0x0F
+ masked := hdr[1]&0x80 != 0
+ plen := int64(hdr[1] & 0x7F)
+ switch plen {
+ case 126:
+ ext := make([]byte, 2)
+ if _, err = io.ReadFull(r, ext); err != nil {
+ return 0, nil, err
+ }
+ plen = int64(ext[0])<<8 | int64(ext[1])
+ case 127:
+ ext := make([]byte, 8)
+ if _, err = io.ReadFull(r, ext); err != nil {
+ return 0, nil, err
+ }
+ plen = 0
+ for i := 0; i < 8; i++ {
+ plen = plen<<8 | int64(ext[i])
+ }
+ }
+ var mask [4]byte
+ if masked {
+ if _, err = io.ReadFull(r, mask[:]); err != nil {
+ return 0, nil, err
+ }
+ }
+ if plen > 0 {
+ payload = make([]byte, plen)
+ if _, err = io.ReadFull(r, payload); err != nil {
+ return 0, nil, err
+ }
+ if masked {
+ for i := range payload {
+ payload[i] ^= mask[i%4]
+ }
+ }
+ }
+ return opcode, payload, nil
+}
+
+// deadlineSetter is the subset of net.Conn we need for write
+// timeouts. Extracted so tests can stub the underlying connection.
+type deadlineSetter interface {
+ SetWriteDeadline(t time.Time) error
+}
+
+// bufferedWriterFlusher is the subset of *bufio.ReadWriter we need.
+type bufferedWriterFlusher interface {
+ io.Writer
+ Flush() error
+}
+
+// Errors exported for callers that want to distinguish failure modes.
+var (
+ ErrNoSubscribers = errors.New("graph_ws: no subscribers")
+)
+
+// String returns a one-line summary of broadcaster state. Used by
+// the `/internal/graph_ws/stats` debug endpoint.
+func (s *Server) String() string {
+ return fmt.Sprintf("graph_ws: subscribers=%d dropped=%d",
+ s.broker.SubscriberCount(),
+ s.broker.DroppedDeliveries(),
+ )
+}
diff --git a/services/ingest/internal/server/server.go b/services/ingest/internal/server/server.go
index 7f209efd0..09deaca1d 100644
--- a/services/ingest/internal/server/server.go
+++ b/services/ingest/internal/server/server.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/beenuar/aisoc/services/ingest/internal/config"
+ "github.com/beenuar/aisoc/services/ingest/internal/graph_ws"
"github.com/beenuar/aisoc/services/ingest/internal/handler"
"github.com/beenuar/aisoc/services/ingest/internal/inbox"
"github.com/go-chi/chi/v5"
@@ -62,7 +63,12 @@ type Server struct {
// inbox handler and just doesn't mount the universal-capture routes.
// In production both handlers are wired; in dev without DATABASE_DSN
// only the connector path is up.
-func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler) *Server {
+//
+// graphWSServer is the optional T1.4 WebSocket broadcaster (graph
+// update fan-out). Nil disables the /v1/graph_ws/stream route, which
+// is the expected default until an operator opts in via
+// AISOC_GRAPH_WS_ENABLED=true.
+func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler, graphWSServer *graph_ws.Server) *Server {
r := chi.NewRouter()
// Middleware
@@ -116,6 +122,17 @@ func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler) *S
} else {
log.Warn().Msg("inbox routes disabled (no Postgres pool wired)")
}
+
+ // T1.4 — graph-update WebSocket fan-out. The Python API
+ // proxy at services/api/app/api/v1/endpoints/graph_ws.py is
+ // the public-facing entry point (auth + tenant binding); the
+ // ingest route is internal and trusts that the proxy has
+ // validated the connecting tenant. We still require
+ // ?tenant_id=<id> as a defence-in-depth filter so a misrouted
+ // internal client can't subscribe to every tenant by accident.
+ if graphWSServer != nil {
+ r.Handle("/graph_ws/stream", graphWSServer.Handler())
+ }
})
return &Server{
diff --git a/services/ingest/main.go b/services/ingest/main.go
index e05485ee2..9b8cdfe0a 100644
--- a/services/ingest/main.go
+++ b/services/ingest/main.go
@@ -14,8 +14,8 @@ import (
"github.com/beenuar/aisoc/services/ingest/internal/config"
configsnap "github.com/beenuar/aisoc/services/ingest/internal/config_snapshot"
- "github.com/beenuar/aisoc/services/ingest/internal/envmode"
"github.com/beenuar/aisoc/services/ingest/internal/graph"
+ "github.com/beenuar/aisoc/services/ingest/internal/graph_ws"
"github.com/beenuar/aisoc/services/ingest/internal/handler"
"github.com/beenuar/aisoc/services/ingest/internal/inbox"
"github.com/beenuar/aisoc/services/ingest/internal/normalizer"
@@ -170,12 +170,45 @@ func main() {
log.Info().Msg("inbox: skipped (no DATABASE_DSN)")
}
- srv := server.New(cfg, h, inboxHandler)
+ // T1.4 (v8.0) — graph-update WebSocket fan-out. Opt-in via
+ // AISOC_GRAPH_WS_ENABLED=true. The broadcaster owns a single
+ // Kafka consumer against GraphUpdatesTopic and fans envelopes
+ // out to subscribed WebSocket clients with per-tenant filtering.
+ // Failures NEVER block the ingest path — the Kafka publish side
+ // (T1.1) is independent and the broadcaster is consumer-only.
+ var graphWSServer *graph_ws.Server
+ var graphWSBroker *graph_ws.Broadcaster
+ if cfg.GraphWSEnabled {
+ src, err := graph_ws.NewKafkaSource(graph_ws.KafkaSourceConfig{
+ Brokers: cfg.KafkaBrokers,
+ Topic: cfg.GraphUpdatesTopic,
+ GroupID: cfg.GraphWSGroupID,
+ })
+ if err != nil {
+ log.Warn().Err(err).Msg("graph_ws: disabled (Kafka source init failed)")
+ } else {
+ graphWSBroker = graph_ws.New(src, graph_ws.Options{BufferSize: cfg.GraphWSSubscriberBuffer})
+ graphWSServer = graph_ws.NewServer(graphWSBroker)
+ log.Info().
+ Str("topic", cfg.GraphUpdatesTopic).
+ Int("buffer", cfg.GraphWSSubscriberBuffer).
+ Msg("graph_ws: T1.4 WebSocket broadcaster enabled")
+ }
+ } else {
+ log.Info().Msg("graph_ws: disabled (AISOC_GRAPH_WS_ENABLED!=true)")
+ }
+
+ srv := server.New(cfg, h, inboxHandler, graphWSServer)
// Graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
+ if graphWSBroker != nil {
+ graphWSBroker.Start(ctx)
+ defer graphWSBroker.Stop()
+ }
+
// Drain VulnMatches → Kafka in a background goroutine
if norm.VulnMatches != nil {
go func() {
diff --git a/services/slack-bot/app/services/approval_audit.py b/services/slack-bot/app/services/approval_audit.py
index b77db67d4..6b48a20bc 100644
--- a/services/slack-bot/app/services/approval_audit.py
+++ b/services/slack-bot/app/services/approval_audit.py
@@ -58,7 +58,7 @@ class ApprovalAuditEvent:
actor_ip: str | None = None
source: str = "slack" # "slack" | "teams" | "email" | "scheduler"
error: str | None = None
- timestamp: float = field(default_factory=time.time)
+ timestamp: float = field(default_factory=lambda: time.time())
metadata: dict[str, Any] | None = None
def as_dict(self) -> dict[str, Any]:
@@ -84,7 +84,7 @@ class ApprovalAuditSink(Protocol):
"""Anything that can swallow an :class:`ApprovalAuditEvent`."""
async def record(self, event: ApprovalAuditEvent) -> None: # pragma: no cover - protocol
- """Persist an approval-audit event."""
+ ...
class NullAuditSink:
diff --git a/services/slack-bot/app/services/approval_timeout.py b/services/slack-bot/app/services/approval_timeout.py
index d3fa07a36..8e26c03b8 100644
--- a/services/slack-bot/app/services/approval_timeout.py
+++ b/services/slack-bot/app/services/approval_timeout.py
@@ -180,5 +180,5 @@ class ApprovalTimeoutScheduler:
# here — that's the whole point of the shutdown path — so
# suppress it explicitly alongside any tear-down errors.
with contextlib.suppress(asyncio.CancelledError, Exception):
- _ = await task
+ await task
self._timers.clear()
diff --git a/services/slack-bot/tests/test_approval_audit.py b/services/slack-bot/tests/test_approval_audit.py
index f9ee2d913..016363435 100644
--- a/services/slack-bot/tests/test_approval_audit.py
+++ b/services/slack-bot/tests/test_approval_audit.py
@@ -29,7 +29,9 @@ def test_event_as_dict_includes_required_fields():
def test_event_as_dict_omits_optional_fields_when_unset():
- event = ApprovalAuditEvent(case_id="c", action_id="a", approver_id="u", decision="approved")
+ event = ApprovalAuditEvent(
+ case_id="c", action_id="a", approver_id="u", decision="approved"
+ )
d = event.as_dict()
assert "error" not in d
assert "metadata" not in d
@@ -47,7 +49,9 @@ async def test_in_memory_sink_records_events():
@pytest.mark.asyncio
async def test_null_sink_no_op():
- await NullAuditSink().record(ApprovalAuditEvent(case_id="c", action_id="a", approver_id="u", decision="approved"))
+ await NullAuditSink().record(
+ ApprovalAuditEvent(case_id="c", action_id="a", approver_id="u", decision="approved")
+ )
@pytest.mark.asyncio
@@ -94,4 +98,6 @@ async def test_structlog_sink_swallows_logger_failure():
sink = StructlogAuditSink(logger=_BrokenLogger())
# Should not raise.
- await sink.record(ApprovalAuditEvent(case_id="c", action_id="a", approver_id="u", decision="approved"))
+ await sink.record(
+ ApprovalAuditEvent(case_id="c", action_id="a", approver_id="u", decision="approved")
+ )
diff --git a/services/slack-bot/tests/test_approval_timeout.py b/services/slack-bot/tests/test_approval_timeout.py
index 701812feb..3854c81d4 100644
--- a/services/slack-bot/tests/test_approval_timeout.py
+++ b/services/slack-bot/tests/test_approval_timeout.py
@@ -46,7 +46,9 @@ class _RecordingClient:
async def test_timer_fires_safe_default_reject_and_writes_audit():
client = _RecordingClient()
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
+ scheduler = ApprovalTimeoutScheduler(
+ approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
+ )
task = scheduler.schedule(
"action-1",
@@ -55,7 +57,7 @@ async def test_timer_fires_safe_default_reject_and_writes_audit():
case_id="case-1",
channel="C7",
)
- _ = await task
+ await task
assert client.reject_calls == ["action-1"]
assert client.approve_calls == []
@@ -74,10 +76,14 @@ async def test_timer_fires_safe_default_reject_and_writes_audit():
async def test_timer_safe_default_approve_invokes_approve():
client = _RecordingClient()
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
+ scheduler = ApprovalTimeoutScheduler(
+ approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
+ )
- task = scheduler.schedule("action-2", timeout_seconds=0.01, safe_default="approved", case_id="case-2")
- _ = await task
+ task = scheduler.schedule(
+ "action-2", timeout_seconds=0.01, safe_default="approved", case_id="case-2"
+ )
+ await task
assert client.approve_calls == ["action-2"]
assert audit.events[0].metadata == {"safe_default": "approved"}
@@ -87,16 +93,20 @@ async def test_timer_safe_default_approve_invokes_approve():
async def test_cancel_before_fire_suppresses_fallback():
client = _RecordingClient()
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
+ scheduler = ApprovalTimeoutScheduler(
+ approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
+ )
- task = scheduler.schedule("action-3", timeout_seconds=5.0, safe_default="rejected", case_id="case-3")
+ task = scheduler.schedule(
+ "action-3", timeout_seconds=5.0, safe_default="rejected", case_id="case-3"
+ )
assert scheduler.cancel("action-3") is True
# Subsequent cancel is a no-op.
assert scheduler.cancel("action-3") is False
# Let the cancellation propagate.
await asyncio.sleep(0)
with pytest.raises(asyncio.CancelledError):
- _ = await task
+ await task
assert client.reject_calls == []
assert audit.events == []
@@ -106,13 +116,19 @@ async def test_cancel_before_fire_suppresses_fallback():
async def test_reschedule_replaces_existing_timer():
client = _RecordingClient()
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
+ scheduler = ApprovalTimeoutScheduler(
+ approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
+ )
- first = scheduler.schedule("action-4", timeout_seconds=5.0, safe_default="rejected", case_id="case-4")
- second = scheduler.schedule("action-4", timeout_seconds=0.01, safe_default="rejected", case_id="case-4")
+ first = scheduler.schedule(
+ "action-4", timeout_seconds=5.0, safe_default="rejected", case_id="case-4"
+ )
+ second = scheduler.schedule(
+ "action-4", timeout_seconds=0.01, safe_default="rejected", case_id="case-4"
+ )
assert first.cancelled() or first is not second
- _ = await second
+ await second
# Only the second timer's firing should produce a fallback call.
assert client.reject_calls == ["action-4"]
assert len(audit.events) == 1
@@ -122,10 +138,14 @@ async def test_reschedule_replaces_existing_timer():
async def test_fallback_call_failure_still_audits_with_error():
client = _RecordingClient(fail=True)
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
+ scheduler = ApprovalTimeoutScheduler(
+ approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
+ )
- task = scheduler.schedule("action-5", timeout_seconds=0.01, safe_default="rejected", case_id="case-5")
- _ = await task
+ task = scheduler.schedule(
+ "action-5", timeout_seconds=0.01, safe_default="rejected", case_id="case-5"
+ )
+ await task
assert client.reject_calls == []
assert len(audit.events) == 1
@@ -138,7 +158,9 @@ async def test_fallback_call_failure_still_audits_with_error():
async def test_aclose_cancels_all_pending_timers():
client = _RecordingClient()
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
+ scheduler = ApprovalTimeoutScheduler(
+ approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
+ )
scheduler.schedule("a-1", timeout_seconds=5.0, safe_default="rejected")
scheduler.schedule("a-2", timeout_seconds=5.0, safe_default="rejected")
diff --git a/services/slack-bot/tests/test_hmac_verify.py b/services/slack-bot/tests/test_hmac_verify.py
index ad52a59f6..da9b63bcd 100644
--- a/services/slack-bot/tests/test_hmac_verify.py
+++ b/services/slack-bot/tests/test_hmac_verify.py
@@ -18,6 +18,7 @@ import time
import pytest
from app.services.hmac_verify import HmacVerificationError, sign, verify
+
SECRET = "test-secret-not-real"
diff --git a/services/teams-bot/app/callbacks.py b/services/teams-bot/app/callbacks.py
index dc95d5eeb..dc432c413 100644
--- a/services/teams-bot/app/callbacks.py
+++ b/services/teams-bot/app/callbacks.py
@@ -35,13 +35,8 @@ log = structlog.get_logger(__name__)
class _ActionsClient(Protocol):
- # Protocol bodies are documentation-only. Using docstrings instead of
- # ``...`` avoids CodeQL ``py/ineffectual-statement`` warnings on stub bodies.
- async def approve_action(self, action_id: str) -> dict[str, Any]:
- """Approve the action identified by ``action_id``."""
-
- async def reject_action(self, action_id: str) -> dict[str, Any]:
- """Reject the action identified by ``action_id``."""
+ async def approve_action(self, action_id: str) -> dict[str, Any]: ...
+ async def reject_action(self, action_id: str) -> dict[str, Any]: ...
@dataclass(slots=True, frozen=True)
@@ -57,8 +52,7 @@ class _AuditEvent:
class _AuditSink(Protocol):
- async def record(self, event: _AuditEvent) -> None:
- """Persist an approval-audit event."""
+ async def record(self, event: _AuditEvent) -> None: ...
class CallbackResult(dict):
@@ -111,7 +105,9 @@ async def handle_card_action(
return CallbackResult(
decision="rejected_unknown_verb",
ok=False,
- card=decision_card(decision="rejected", action_id=action_id, decided_by=approver_id),
+ card=decision_card(
+ decision="rejected", action_id=action_id, decided_by=approver_id
+ ),
error=f"unknown verb {verb!r}",
)
@@ -161,7 +157,9 @@ async def handle_card_action(
decision=decision_label,
ok=False,
error=str(exc),
- card=decision_card(decision=decision_label, action_id=action_id, decided_by=approver_id),
+ card=decision_card(
+ decision=decision_label, action_id=action_id, decided_by=approver_id
+ ),
)
if audit_sink is not None:
@@ -178,7 +176,9 @@ async def handle_card_action(
return CallbackResult(
decision=decision_label,
ok=True,
- card=decision_card(decision=decision_label, action_id=action_id, decided_by=approver_id),
+ card=decision_card(
+ decision=decision_label, action_id=action_id, decided_by=approver_id
+ ),
)
diff --git a/services/teams-bot/app/main.py b/services/teams-bot/app/main.py
index 2c9a54267..130cdf79b 100644
--- a/services/teams-bot/app/main.py
+++ b/services/teams-bot/app/main.py
@@ -31,7 +31,10 @@ from app.callbacks import callback_max_age_seconds, handle_card_action
app = FastAPI(
title="AiSOC Teams Bot",
- description=("ChatOps adapter for Microsoft Teams. Renders Adaptive Card approval prompts and verifies the signed callback payload."),
+ description=(
+ "ChatOps adapter for Microsoft Teams. Renders Adaptive Card "
+ "approval prompts and verifies the signed callback payload."
+ ),
version="0.1.0",
)
@@ -50,7 +53,11 @@ def _resolve_approver(activity: dict[str, Any]) -> str:
identifier (guest users, anon links).
"""
sender = activity.get("from") or {}
- return str(sender.get("aadObjectId") or "").strip() or str(sender.get("id") or "").strip() or "unknown"
+ return (
+ str(sender.get("aadObjectId") or "").strip()
+ or str(sender.get("id") or "").strip()
+ or "unknown"
+ )
@app.post("/teams/messages")
diff --git a/services/teams-bot/app/services/aisoc_clients.py b/services/teams-bot/app/services/aisoc_clients.py
index abce21aee..79a7a65db 100644
--- a/services/teams-bot/app/services/aisoc_clients.py
+++ b/services/teams-bot/app/services/aisoc_clients.py
@@ -25,22 +25,13 @@ log = structlog.get_logger(__name__)
class _ActionsClient(Protocol):
- # Protocol method bodies are documentation-only. We use docstrings (rather
- # than ``...``) so static analysers don't flag the bodies as ineffectual
- # statements (CodeQL ``py/ineffectual-statement``).
- async def approve_action(self, action_id: str) -> dict[str, Any]:
- """Approve the action identified by ``action_id``."""
-
- async def reject_action(self, action_id: str) -> dict[str, Any]:
- """Reject the action identified by ``action_id``."""
-
- async def aclose(self) -> None:
- """Release underlying network resources."""
+ async def approve_action(self, action_id: str) -> dict[str, Any]: ...
+ async def reject_action(self, action_id: str) -> dict[str, Any]: ...
+ async def aclose(self) -> None: ...
class _AuditSink(Protocol):
- async def record(self, event: Any) -> None:
- """Persist an approval-audit event."""
+ async def record(self, event: Any) -> None: ...
class _FallbackActionsClient:
@@ -75,7 +66,13 @@ class _FallbackActionsClient:
def _try_import_slack_bot_client():
"""Best-effort import of the Slack bot's actions client."""
- candidate = Path(__file__).resolve().parents[3] / "slack-bot" / "app" / "services" / "aisoc_clients.py"
+ candidate = (
+ Path(__file__).resolve().parents[3]
+ / "slack-bot"
+ / "app"
+ / "services"
+ / "aisoc_clients.py"
+ )
if not candidate.exists():
return None
spec = importlib.util.spec_from_file_location("_aisoc_slack_bot_clients", candidate)
@@ -108,7 +105,13 @@ class _NullAuditSink:
def build_audit_sink() -> _AuditSink:
"""Construct the shared audit sink if available; null sink otherwise."""
- candidate = Path(__file__).resolve().parents[3] / "slack-bot" / "app" / "services" / "approval_audit.py"
+ candidate = (
+ Path(__file__).resolve().parents[3]
+ / "slack-bot"
+ / "app"
+ / "services"
+ / "approval_audit.py"
+ )
if not candidate.exists():
return _NullAuditSink()
spec = importlib.util.spec_from_file_location("_aisoc_audit", candidate)
diff --git a/services/teams-bot/app/services/hmac_signer.py b/services/teams-bot/app/services/hmac_signer.py
index c79f35bd0..225510746 100644
--- a/services/teams-bot/app/services/hmac_signer.py
+++ b/services/teams-bot/app/services/hmac_signer.py
@@ -32,7 +32,9 @@ from typing import Any
# We resolve the module by absolute path so the Teams bot can be unit-
# tested in isolation (it doesn't share a pyproject with the Slack bot
# but the two repos co-evolve — see the README).
-_SLACK_BOT_HMAC_PATH = Path(__file__).resolve().parents[3] / "slack-bot" / "app" / "services" / "hmac_verify.py"
+_SLACK_BOT_HMAC_PATH = (
+ Path(__file__).resolve().parents[3] / "slack-bot" / "app" / "services" / "hmac_verify.py"
+)
_module_name = "_aisoc_hmac_verify"
_spec = importlib.util.spec_from_file_location(_module_name, _SLACK_BOT_HMAC_PATH)
@@ -72,7 +74,9 @@ def sign_card_data(
Mint the ``data`` payload attached to an Adaptive Card
``Action.Submit`` button.
"""
- payload = canonical_payload(verb=verb, action_id=action_id, case_id=case_id, issued_at=issued_at)
+ payload = canonical_payload(
+ verb=verb, action_id=action_id, case_id=case_id, issued_at=issued_at
+ )
return {
"verb": verb,
"action_id": action_id,
@@ -96,7 +100,9 @@ def verify_card_data(payload: dict[str, Any], *, secret: str, max_age_seconds: i
signature = str(payload.get("signature") or "")
if not verb or not action_id or issued_at is None:
raise HmacVerificationError("Missing required fields on signed payload")
- canonical = canonical_payload(verb=verb, action_id=action_id, case_id=case_id, issued_at=int(issued_at))
+ canonical = canonical_payload(
+ verb=verb, action_id=action_id, case_id=case_id, issued_at=int(issued_at)
+ )
verify(
canonical,
signature,
diff --git a/services/teams-bot/tests/test_cards.py b/services/teams-bot/tests/test_cards.py
index 5f3eb6dd7..53a309548 100644
--- a/services/teams-bot/tests/test_cards.py
+++ b/services/teams-bot/tests/test_cards.py
@@ -33,9 +33,7 @@ def test_case_context_card_has_required_envelope():
{"id": "case-1", "case_number": "CASE-0001", "title": "EDR detection"},
web_base="https://app.aisoc.test",
)
- # Pinned to the exact canonical schema URL — avoids CodeQL ``py/incomplete-url-substring-sanitization``
- # by checking the full string rather than a substring prefix.
- assert card["$schema"] == "http://adaptivecards.io/schemas/adaptive-card.json"
+ assert card["$schema"].startswith("http://adaptivecards.io")
assert card["type"] == "AdaptiveCard"
assert card["version"] == "1.5"
assert isinstance(card["body"], list) and len(card["body"]) >= 2