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.

feat(v8): Azure/GCP resource snapshots, ContextBundle, LLM contract

Beenu Arora674b47d6d11e
diff --git a/AISOC_V8_PROGRESS.md b/AISOC_V8_PROGRESS.md
index 884a15978..b991ed936 100644
--- a/AISOC_V8_PROGRESS.md
+++ b/AISOC_V8_PROGRESS.md
@@ -59,14 +59,14 @@ Wave-2 commits (most recent first, all SSH-signed, attributed Prince Sinha):
### 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 + GCP overrides pending)
+- [~] 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
-- [ ] T1.4 Real-time graph-update WebSocket (P1, 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; integration into LangGraph pending T2.2)
+- [~] 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` (fail-closed Pydantic validator on tool input/output; wiring into all agents pending)
+- [~] 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)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a53760fff..450dc7d46 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### LLM input contract — CI tests (T2.3, v8.0)
+
+`services/agents/tests/test_llm_contract.py` exercises `classify_message` /
+`LLMInputContract.validate` / `validate_messages`: raw OCSF-shaped JSON in a
+user message fails closed when `AISOC_AGENTS_LLM_CONTRACT_ENFORCED=1`
+(default), and prose plus `summarize_structure_for_llm` output passes. Tests
+use `{"role", "content"}` dict messages so they run without importing
+`langchain_core` (the contract already coerces LangChain `BaseMessage` and
+dicts the same way).
+
+### Real-time graph-update WebSocket (T1.4, v8.0)
+
+Closes the v8.0 loop between the ingest-side graph writer (T1.1) and the
+operator console. `services/realtime` now exposes a `graph` WebSocket
+channel reachable at `/ws/graph` (or piggy-backed on `/ws/all`) and runs a
+dedicated `aisoc-realtime-graph` Kafka consumer group against the
+`security.graph_updates` topic that the Go ingest writer publishes to
+(`services/ingest/internal/graph/writer.go`). Each `GraphUpdate` envelope
+(`entity_id`, `change_type`, `ts`, `label`, `rel_type`, `from`, `to`,
+`properties`, `schema_version`) is fanned out to clients scoped by
+`tenant_id`, with `default` as the single-tenant fallback so self-hosted
+deploys without explicit tenant tagging still light up live. The new
+consumer is wired alongside the existing fused-alerts consumer in
+non-blocking mode: a missing or unreachable graph topic logs at `warn` and
+never blocks the higher-priority alerts/cases/agents/insights fan-out. The
+topic name honours both `AISOC_GRAPH_UPDATES_TOPIC` and
+`KAFKA_TOPIC_GRAPH_UPDATES` envs (defaults to `security.graph_updates` so
+it matches the Go writer's default in
+`services/ingest/internal/config/config.go` without manual plumbing), and
+setting it to the empty string disables the consumer entirely for tests
+that don't spin up Kafka graph traffic. The Investigation Rail and Attack
+Chain views (T3.3 UI, in flight) can subscribe today and pick up node /
+edge mutations within ~1s of the upstream event reaching ingest.
+
### Public weekly benchmark scoreboard at /docs/benchmark-scoreboard
Public, append-only weekly scoreboard now lives at
diff --git a/plans/aisoc_v8.0_north_star_plan_1dee8c63.plan.md b/plans/aisoc_v8.0_north_star_plan_1dee8c63.plan.md
new file mode 100644
index 000000000..64a2d121a
--- /dev/null
+++ b/plans/aisoc_v8.0_north_star_plan_1dee8c63.plan.md
@@ -0,0 +1,476 @@
+# AiSOC v8.0 — North-star Plan
+
+> **Status**: Locked plan — implement as specified, do not edit.
+> **Captured**: 2026-05-15
+> **Hash**: `1dee8c63`
+> **Tracking**: `AISOC_V8_PROGRESS.md` mirrors progress; this file is the source of truth.
+> **Convention**: Mirrors workspace plan-file rules — `[ ]` → `[~]` (in flight) → `[x]` (shipped) lives in the progress mirror, never in this file.
+
+---
+
+## North-star outcomes (what v8.0 must ship)
+
+1. **Sub-minute investigation, with the numbers in public.** p50 < 60s, p95 < 120s on the 200-incident eval set, with token + USD per investigation published in `apps/docs/docs/benchmark.md`.
+2. **Knowledge graph built at ingest, not at query.** Every event materializes graph nodes + edges before fusion sees it; config-at-event-time captured as a versioned snapshot edge.
+3. **A clean three-model story** — Semantic (Neo4j) / Behavioral (UEBA + LightGBM + Isolation Forest) / Knowledge (Qdrant RAG + LLM). LLM only ever sees structured summaries, never raw logs.
+4. **Effective Permissions** across AWS / Azure / GCP / Okta / Google Workspace, with a Cytoscape graph view.
+5. **Attack Chains** — one alert pulls every related alert across the stack into a single ranked timeline.
+6. **NL hunting** as a hero surface — `/hunt`, saved hunts, scheduled hunts, example-query pills.
+7. **40+ live connectors**, up from 26.
+8. **Branded agent narrative** — 4 named agents that map to a customer's mental model (Detect / Triage / Hunt / Respond), with the existing sub-agents (phishing / identity / cloud / insider) framed as Triage capabilities.
+9. **Hosted multi-tenant SaaS at app.aisoc.dev** (early-access waitlist) running the same code as self-hosted. Self-hosted stays first-class.
+
+---
+
+## Tracks
+
+- **Track 1** — Graph-at-ingest architecture upgrade
+- **Track 2** — Agent / reasoning latency + cost
+- **Track 3** — UI: Effective Permissions, Attack Chains, NL Hunt, SOC Insights, Business Context
+- **Track 4** — Connector wave (15 new)
+- **Track 5** — Public benchmark + eval extensions
+- **Track 6** — Hosted SaaS + GTM enablement surface
+- **Track 7** — Narrative sharpening (OSS / sovereign / IDE-driven / public-eval / osquery)
+
+Each task: `Priority` (P0 must / P1 important / P2 nice) · `Effort` (S < 1 wk / M 2-4 wk / L 1-2 mo) · `Depends on` (other T-IDs).
+
+---
+
+## Track 1 — Architecture: graph at ingest
+
+**Goal:** end the "Neo4j is built after the fact" pattern. The security knowledge graph is written synchronously inside the ingest path, captures config-at-event-time, and has a published schema.
+
+### T1.1 — Ingest-side graph writer (P0, L, depends on: —)
+
+Insert a graph-write step into the Kafka ingest path so every normalized event materializes / updates graph nodes + edges *before* it lands in fusion.
+
+**New module:** `services/ingest/internal/graph/` (Go)
+- `writer.go` — Neo4j Bolt driver, batched UNWIND upserts, pooled connection
+- `schema.go` — entity + edge type enums, version stamping
+- `extractor.go` — pulls entity references out of OCSF events (actor, target, resource, network endpoint, code repo, container image)
+
+**Wiring:**
+- Kafka consumer group `aisoc-graph-writer` reading `security.events`
+- Idempotency: `(entity_type, natural_key, hash(properties))` UPSERT
+- Publish `security.graph_updates` topic with `{entity_id, change_type, ts}` for downstream consumers
+
+**Schema (versioned):**
+- Node labels: `Identity, Permission, Role, Policy, Resource, Configuration, Endpoint, User, ServiceAccount, Repo, Container, Image, NetworkPath, SaaSApp, Alert, Case, Detection`
+- Relationships: `:ASSUMED_BY, :HAS_PERMISSION, :GRANTS, :OWNS, :CONFIGURED_AS, :DEPLOYED_FROM, :ACCESSES, :PEER_OF, :TRIGGERED, :OCCURRED_ON, :MEMBER_OF, :DEPLOYS, :READS_FROM, :WRITES_TO`
+- Every event-edge carries `{ts, source_event_id, snapshot_id}`
+
+**Acceptance:**
+- `services/ingest/internal/graph/writer_test.go` — given the 360-event synthetic corpus, all 14 source types yield ≥ 1 graph entity, deterministic counts, CI-gated
+- `services/agents/tests/test_graph_freshness.py` — p95 < 2s from Kafka publish to graph readability via Cypher `MATCH`
+- `eval_report.json` adds `graph_freshness_ms` field
+
+### T1.2 — Config snapshots (config-at-event-time) (P0, M, depends on: T1.1)
+
+When an event lands referencing a resource, capture the resource's configuration *at that moment* as a versioned `Configuration` node connected via `:CONFIGURED_AS {ts}`.
+
+**New module:** `services/ingest/internal/config_snapshot/`
+- `snapshotter.go` — pulls config from connectors that expose `get_resource_config(resource_id, ts)`
+- `cache.go` — Redis-backed TTL cache to avoid round-trips for hot resources
+
+**Connector extension:** add optional method `get_resource_config(id, ts) -> dict` to `BaseConnector` (Python) and the Go connector interface. Default `NotImplemented`. Implement first for:
+- AWS (CloudTrail trail config, IAM policy version)
+- Azure (Resource Manager)
+- GCP (Asset Inventory)
+- Okta (group/policy versions)
+- GitHub (repo settings + branch protection)
+
+**Acceptance:** For an alert on AWS resource `i-12345`, the Cypher path `(:Alert)-[:OCCURRED_ON]->(:Resource)-[:CONFIGURED_AS {ts}]->(:Configuration)` returns the correct config at alert timestamp. Validated against fixtures in `services/ingest/test_data/aws_config_history.json`.
+
+### T1.3 — Publish the graph schema (P0, S, depends on: T1.1)
+
+- `apps/docs/docs/architecture/graph-schema.md` — narrative + Mermaid ER diagram + every label / relationship explained
+- `scripts/export_graph_schema.py` — connects to Neo4j, dumps current schema to YAML
+- `schemas/graph-schema.yaml` — checked in, regenerated on schema migration
+
+**Acceptance:** Doc renders on docs.aisoc.dev/architecture/graph-schema with full ER diagram. `scripts/export_graph_schema.py --check` fails CI if schema drifts without doc update.
+
+### T1.4 — Real-time graph-update WebSocket channel (P1, S, depends on: T1.1)
+
+`services/realtime/` exists. Add a `/graph/updates` channel that fans out the `security.graph_updates` Kafka topic to subscribed clients with tenant filtering.
+
+**Acceptance:** Console graph view subscribes; nodes light up < 1s after Kafka event publishes.
+
+---
+
+## Track 2 — Agent reasoning: latency + cost
+
+**Goal:** investigation p50 < 60s, p95 < 120s on the eval set, with measured token + USD per investigation published. LLM contract enforced — agents only consume structured summaries.
+
+### T2.1 — Pre-fetched context bundle (P0, M, depends on: T1.1)
+
+Before any sub-agent runs, build a `ContextBundle` Pydantic model:
+- entity neighborhood (configurable depth, default 2)
+- historical similar-case verdicts (last N from `aisoc_institutional_memory`)
+- peer-entity behavior baselines (UEBA)
+- threat-intel matches
+
+**New:** `services/agents/app/context/bundle.py` (~150 LOC). Replaces the per-tool round-trip discovery pattern.
+
+**Refactor:** sub-agents in `services/agents/app/agents/*.py` accept `ContextBundle` as a parameter; tools they call become enrichment of the bundle, not primary discovery.
+
+**Acceptance:**
+- `services/agents/tests/test_context_bundle.py` — for each of 200 eval incidents, bundle is fully populated in < 5s p95
+- Token-per-investigation drops ≥ 30% vs baseline (measured in eval)
+
+### T2.2 — LangGraph topology refactor: parallel sub-agents (P0, M, depends on: T2.1)
+
+Today's router is likely sequential. Move to parallel fan-out: `auto_triage_agent` classifies, then *concurrent* fan-out to relevant sub-agents (phishing AND identity if both signals present), join, then ResponderAgent.
+
+**File:** `services/agents/app/investigator/graph.py` — change router edges to parallel; introduce a Join node. Keep sequential path under a feature flag until eval is green.
+
+**Acceptance:**
+- `services/agents/tests/test_latency.py` — investigation wall-clock p50 < 60s, p95 < 120s on the 200-incident set, warm Fly.io
+- No regression in MITRE accuracy, completeness, or response-quality scores
+
+### T2.3 — Structured-summaries-only LLM contract (P0, M, depends on: T2.1)
+
+Some agent prompts may today concatenate raw logs. Enforce: every LLM call receives only ContextBundle summary fields + numerical scores + RAG snippets. No raw OCSF JSON, ever.
+
+**New:** `services/agents/app/llm/contract.py` — wraps every LLM call, validates message contents against `LLMInputContract` Pydantic model, fails closed on raw-log shape.
+
+**Acceptance:** `services/agents/tests/test_llm_contract.py` — all 200 eval-incident runs pass the contract.
+
+### T2.4 — Token + USD telemetry in eval (P0, S, depends on: —)
+
+Extend `scripts/run_evals.py` to emit `tokens_per_investigation` + `usd_per_investigation` aggregated from `aisoc_run_costs`. Add `scripts/render_eval_charts.py` → `docs/benchmark-charts/*.svg`.
+
+**Acceptance:** `apps/docs/docs/benchmark.md` includes p50/p95/p99 latency, mean/median tokens, mean/median USD — per-template and aggregate.
+
+### T2.5 — Brand the four agents (P0, S, depends on: —)
+
+Consolidate the public narrative around 4 named agents. Sub-agents (phishing / identity / cloud / insider) become *capabilities* of the Triage agent, not first-class names.
+
+- `Detect` — fusion + entity-risk + native detections
+- `Triage` — `auto_triage_agent` + the 4 sub-agents
+- `Hunt` — Hunt-as-Code engine + NL hunt surface
+- `Respond` — ResponderAgent + SOAR + ChatOps
+
+**Where:** rename agent classes in `services/agents/app/agents/__init__.py` (alias old names for back-compat); update `apps/docs/docs/architecture/agents.md`; update landing-page hero copy.
+
+**Acceptance:** Public docs reference exactly four agents. Internal sub-agent code paths unchanged.
+
+---
+
+## Track 3 — UI
+
+**Reframe:** AiSOC already ships ~25 console pages, Cytoscape graphs, Monaco editor, React Flow playbooks, the 684-LOC Investigation Timeline, Responder PWA, ⌘J Copilot dock, ⌘K palette. The real UI work in v8.0 is five named features + polish.
+
+### T3.1 — SOC Insights dashboard (P1, M, depends on: T2.4)
+
+New page: `apps/web/src/app/(console)/dashboards/soc-insights/page.tsx`.
+
+Tiles: MTTA, MTTR, FP rate, alerts/day, cases/day, agent-cost-per-investigation, analyst hours saved (heuristic: auto-closed cases × avg manual investigation time).
+
+**API:** `services/api/app/api/v1/endpoints/insights.py` — aggregates from cases + Investigation Ledger + `aisoc_run_costs`.
+
+**Acceptance:** Renders < 1s on tryaisoc.com with seeded data; tiles refresh via WebSocket every 30s.
+
+### T3.2 — Effective Permissions (P0, L, depends on: T1.1)
+
+**Backend:** `services/api/app/services/effective_permissions/` with provider modules:
+- `aws.py` — IAM policy resolution (identity-based + resource-based + SCP)
+- `azure.py` — RBAC role assignments + scope inheritance
+- `gcp.py` — IAM policy resolution + organizational policies
+- `okta.py` — group → role mapping
+- `gws.py` — Google Workspace admin role mapping
+
+Each takes a principal ID and returns the set of effective actions across resources with policy-chain provenance.
+
+**Caching:** materialize into Neo4j as `(:Identity)-[:EFFECTIVE_PERMISSION {actions, last_resolved}]->(:Resource)`.
+
+**UI:** `apps/web/src/app/(console)/identity/permissions/page.tsx` — Cytoscape "Identity → Role → Policy → Action → Resource"; collapsible by provider; "show only changes since last week" filter.
+
+**Acceptance:**
+- For fixture AWS account in `services/api/tests/fixtures/aws_iam_complex.json`, output matches AWS IAM Policy Simulator on 50 sample principal/resource pairs
+- UI loads for a 1k-principal tenant in < 3s
+
+### T3.3 — Attack Chains (P0, L, depends on: T1.1)
+
+**Backend:** `services/fusion/app/services/attack_chain.py` — given an alert, walks the graph within a configurable window (default 24h), pulls all alerts sharing ≥ 1 entity, ranks by graph distance + temporal proximity + risk overlap, returns a single ranked timeline.
+
+**Storage:** new table `attack_chains` via migration `services/api/migrations/0NN_attack_chains.sql`.
+
+**UI:** `apps/web/src/app/(console)/cases/[id]/attack-chain/page.tsx` — single timeline + side-by-side entity graph; "pivot to source" buttons that route back to the original detection / connector event.
+
+**Acceptance:** For seeded `INC-RT-001` (LockBit 3.0) on tryaisoc.com, Attack Chain stitches: initial phishing → credential harvest → cloud auth anomaly → S3 enumeration → exfil. All 5 alerts in correct temporal order.
+
+### T3.4 — `/hunt` — natural language hunt surface (P0, S-M, depends on: —)
+
+Rebrand `/investigate` to `/hunt`. Add saved-hunt persistence + scheduled-hunt cron from the same UI. Example-query pill row on first load:
+- "Did we get any new attacks from Iran?"
+- "Show me everyone who touched our prod IAM role in the last 7 days"
+- "Any GitHub auth from a new device this week?"
+
+**Files:**
+- Rename `apps/web/src/app/(console)/investigate/page.tsx` → `apps/web/src/app/(console)/hunt/page.tsx`. Add redirect.
+- New `services/api/app/api/v1/endpoints/hunts.py` for saved + scheduled hunts.
+- Reuse existing NL → Sigma/KQL/SPL/ES|QL translator chain.
+
+**Landing:** dedicated hero block ("Hunt at the speed of thought"), 90-second demo video, blog post.
+
+**Acceptance:** Each of the 3 example queries returns results in < 5s on seeded tryaisoc.com. Saved hunts persist across reload. Scheduled hunts fire on cron and create cases on hit.
+
+### T3.5 — Business Context Rules (P1, M, depends on: —)
+
+A layer between detection and the triage agent where customers encode their own context: "if alert.target.tag == 'prod' and alert.time.is_business_hours: severity = critical; route_to = tier2".
+
+**Engine:** `services/api/app/services/business_context/` — YAML or visual rule definitions; evaluated post-fusion, pre-triage-agent.
+
+**UI:** `apps/web/src/app/(console)/settings/business-context/page.tsx` — Monaco YAML editor with rule-builder side-panel; live preview against last 100 alerts.
+
+**Acceptance:** A test rule mutating severity is reflected within 1s of save; dry-run preview shows 50 sample alerts with before/after.
+
+### T3.6 — Slack / Teams approval Block-Kit cards (P1, M, depends on: —)
+
+Upgrade `services/slack-bot/` from slash-command-only to interactive Block Kit cards. Add Teams Adaptive Cards. Email fallback via Mailgun.
+
+**Behaviour:** approver sees full case context, Approve / Deny / Need-Info buttons, configurable timeout, safe-default fallback action, full audit trail.
+
+**Acceptance:** Approve/Deny buttons trigger HMAC-verified callback; timeout → safe-default action; full audit trail captured.
+
+### T3.7 — NL → playbook generator (P1, M, depends on: T3.4)
+
+Add NL-authored playbook drafting on top of the existing React Flow editor.
+
+**Files:**
+- `apps/web/src/app/(console)/playbooks/new/page.tsx?nl=true` — prompt input → LLM emits DAG draft → opens in React Flow editor
+- `services/agents/app/playbook/nl_drafter.py` — prompt template + LLM call + JSON Schema validation against `playbook.schema.json`
+
+**Acceptance:** Prompt "When a high-severity exfil alert fires on a prod S3 bucket, isolate the IAM role, snapshot the bucket policy, and page on-call" emits a valid DAG with isolate-role + snapshot-policy + page nodes wired in correct order.
+
+### T3.8 — Design system v2 + Storybook (P1, M, depends on: —)
+
+- Add shadcn/ui formally if not already wired
+- Tighten dark theme tokens
+- Build `apps/web/.storybook/` with 30+ component stories so screenshots can be programmatically generated for marketing
+- WCAG AA is already shipped per ROADMAP v7.0 — keep it green
+
+**Acceptance:** Storybook builds; 30+ stories; visual-regression snapshots committed.
+
+---
+
+## Track 4 — Connector wave (15 new)
+
+**Goal:** cross 40 live connectors; ship the 15 below in 8 weeks. All in `services/connectors/app/connectors/<id>/` with companion `plugins/<id>/plugin.yaml`.
+
+| # | Connector | Effort | Why this slot |
+|---|---|---|---|
+| 1 | Cloudflare WAF + Zero Trust | M | CDN + ZTNA increasingly the perimeter |
+| 2 | Tines | S | SOAR fallback target |
+| 3 | Torq | S | SOAR coverage parity |
+| 4 | Sublime Security | M | Email-security AI narrative |
+| 5 | Abnormal Security | M | Same |
+| 6 | Lacework (extend) | S | Add policy-violations stream |
+| 7 | Sysdig | M | K8s runtime |
+| 8 | Falco | S | OSS K8s runtime |
+| 9 | HashiCorp Vault audit | M | Identity-graph extension to secrets |
+| 10 | PagerDuty / Opsgenie | S | On-call loop closure |
+| 11 | Atlassian Confluence audit | S | SaaS breadth |
+| 12 | Box / Dropbox audit | M | DLP narrative |
+| 13 | Datadog logs + APM | M | Observability spine |
+| 14 | Snowflake audit | M | Warehouse parity |
+| 15 | OCI (Oracle Cloud) | M | Sovereign cloud play |
+
+**Cross-cutting:**
+- `scripts/generate_connector_docs.py` — auto-generate `apps/docs/docs/connectors/<id>.md` from each connector's `schema()`
+- Test scaffold per connector: `services/connectors/tests/connectors/test_<id>.py` covering schema valid, normalize round-trip, fixture-driven `fetch_alerts`
+- Marketplace card includes a "schema-drift alerts in last 30 days" badge from the existing sentinel
+
+**Acceptance:** 15 connectors land + green CI + auto-generated docs + visible in `/marketplace`.
+
+---
+
+## Track 5 — Public benchmark + eval extensions
+
+**Goal:** make AiSOC's eval the published reference. Everything reproducible from `make eval-public`.
+
+### T5.1 — Speed + token + cost publication (P0, S, depends on: T2.4)
+
+Publish `apps/docs/docs/benchmark.md`: p50/p95/p99 latency per template, tokens per investigation (mean/median + by-category), USD per investigation at current rate card.
+
+### T5.2 — Methodology page (P0, S, depends on: T5.1)
+
+Open-source methodology + rate card in `apps/docs/docs/benchmark-methodology.md`. Invite reproductions in the README footer.
+
+### T5.3 — Public-dataset fidelity benchmark (P1, M, depends on: —)
+
+Run AiSOC against:
+- AIT-LDS (Austrian Institute of Technology log dataset)
+- CICIDS2018
+- MITRE Engenuity ATT&CK Evaluations rounds where data is public
+
+**Files:**
+- `services/agents/tests/test_public_datasets.py`
+- `services/agents/tests/datasets/{ait_lds,cicids2018,mitre_engenuity}.py`
+
+**Acceptance:** Benchmark page shows AiSOC scores on each dataset with date stamp + commit SHA.
+
+### T5.4 — Public scoreboard page (P1, M, depends on: T5.1)
+
+Page at `tryaisoc.com/benchmark` that pulls latest CI's `eval_report.json` and renders score vs previous release. Open a GitHub issue template for anyone to PR a comparable published metric.
+
+### T5.5 — "Wet eval" weekly CI job (P1, S, depends on: T2.4)
+
+Today the eval runs against deterministic substrate (README discloses this). Add a separate weekly CI job that actually calls the LLM tier on the 200-incident set and posts the run's tokens + USD + latency to the benchmark page.
+
+**File:** `.github/workflows/wet-eval-weekly.yml`. Budget-gated; failure non-blocking on PRs.
+
+---
+
+## Track 6 — Hosted SaaS + GTM enablement surface
+
+### T6.1 — `app.aisoc.dev` multi-tenant managed instance (P0, L, depends on: T1.1, T2.2, T3.2, T3.3)
+
+Same code as self-hosted, deployed on Fly.io with regional read replicas. Sign-up gated by an early-access waitlist.
+
+**Files:**
+- `apps/web/src/app/(marketing)/early-access/page.tsx` — waitlist form
+- `services/api/app/api/v1/endpoints/waitlist.py` — captures applications, sends Slack alert to GTM channel
+- `infra/fly/managed/` — Helm-compose hybrid deploy config for the managed environment
+
+**Acceptance:** Waitlist captures applications; managed instance boots from `main` on every release tag.
+
+### T6.2 — Reference-customer page templates (P0, S, depends on: —)
+
+Template page so GTM can publish case studies without engineering involvement.
+
+**File:** `apps/web/src/app/(marketing)/customers/[slug]/page.tsx` — MDX-driven, with structured frontmatter: `{logo, industry, challenge, result_numbers[], quote, quote_role, quote_company}`.
+
+**Acceptance:** Template renders for a placeholder case study; new case study = new MDX file in `apps/web/content/customers/`.
+
+### T6.3 — Sovereign + air-gap one-pager (P1, S, depends on: —)
+
+A landing page surfacing AiSOC's deployment flexibility: air-gap mode, Ollama sidecar, on-prem, Helm, Terraform, any cloud, any country.
+
+**File:** `apps/web/src/app/(marketing)/sovereign/page.tsx` with a country / cloud / deployment-mode matrix.
+
+### T6.4 — `pnpm aisoc:demo` polishing (P1, S, depends on: —)
+
+The one-command demo seeder exists. Polish it: deterministic 4 cases (phishing / cloud takeover / insider exfil / ransomware), 90-second screencast in `apps/web/public/demo.mp4`, README badge linking to a Fly.io-hosted demo with read-only credentials.
+
+**Acceptance:** New user runs `pnpm aisoc:demo`, gets to a populated dashboard with 4 cases in < 4 min on a warm laptop.
+
+---
+
+## Track 7 — Narrative + IDE-driven SOC
+
+### T7.1 — Cursor extension (P0, M, depends on: —)
+
+Ship a Cursor extension wrapping `@aisoc/mcp` so analysts can run triage, replay decisions, and explain steps from inside Cursor.
+
+**New repo (or path):** `aisoc-cursor-extension/` or `services/mcp/cursor-extension/`.
+
+**Capabilities exposed via the extension:**
+- "Run triage on case X" → calls `aisoc_run_investigation`
+- "Replay step 3 of investigation Y" → calls `aisoc_replay_decision`
+- "Explain why the agent did this" → calls `aisoc_explain_step`
+- "Find detections covering this technique" → calls `aisoc_query_detections`
+
+**Acceptance:** Published to Cursor extension marketplace; demo video on tryaisoc.com showing a full triage flow without leaving Cursor.
+
+### T7.2 — L0–L4 automation maturity white paper (P1, S, depends on: —)
+
+The maturity model is shipped in v6.0. Write it up as a white paper under the AiSOC brand, host as a PDF at `apps/web/public/papers/l0-l4-automation-maturity.pdf`. Submit to MITRE D3FEND community channels.
+
+### T7.3 — Three blog posts to anchor the narrative (P1, S, depends on: T5.1, T7.1)
+
+- "How AiSOC investigates incidents in under a minute, with the numbers" — references T2 + T5 outputs
+- "The SOC has an IDE now" — references T7.1 Cursor extension
+- "AiSOC owns the endpoint truth layer" — osctrl + FleetDM + `aisoc-direct` + custom virtual tables + 16 osquery rules
+
+Authored as MDX in `apps/web/content/blog/`.
+
+---
+
+## Sequencing — 12 weeks
+
+### Week 0 — pre-kick-off
+- Eng lead walks team through this plan
+- PM opens GitHub issues for every T-ID with this doc linked
+- GTM kicks off reference-customer recruitment (long lead) and academic / lab reproductions (long lead)
+
+### Weeks 1–3 — parallel kickoff
+| Track | Tasks |
+|---|---|
+| T1 | T1.1 graph writer (start). T1.3 schema publication (finish wk 2). |
+| T2 | T2.4 token + USD telemetry (wk 1). T2.5 four-agent rebrand (wk 1). T2.1 ContextBundle (start wk 2). |
+| T3 | T3.4 `/hunt` rebrand (finish wk 2). T3.1 SOC Insights (start). |
+| T4 | First 5 connectors: Tines, Torq, Falco, PagerDuty, Confluence. |
+| T5 | T5.1 + T5.2 published (wk 3). |
+| T7 | T7.1 Cursor extension kickoff. |
+
+**Wk 3 milestone:** Ingest-side graph writer in beta on a dev tenant. Public benchmark page live. `/hunt` rebrand shipped. 5 new connectors landed. Four-agent naming live in docs.
+
+### Weeks 4–6 — heavy build
+| Track | Tasks |
+|---|---|
+| T1 | T1.1 finishes. T1.2 config snapshots. T1.4 graph-update WebSocket. |
+| T2 | T2.1 ships. T2.2 parallel topology refactor. T2.3 LLM contract. |
+| T3 | T3.5 Business Context Rules. T3.6 Slack Block Kit. |
+| T4 | 5 more connectors: Sublime, Abnormal, Sysdig, Vault, Box. |
+| T5 | T5.3 public-dataset benchmark. |
+| T7 | T7.3 blog 1 published. |
+
+**Wk 6 milestone:** Investigation p50 < 60s on the eval. Effective-permissions resolver in dev. Attack Chains backend in dev. 10 new connectors total. First reference customer logo committed.
+
+### Weeks 7–9 — UI completion + customer evidence
+| Track | Tasks |
+|---|---|
+| T3 | T3.2 Effective Permissions UI ships. T3.3 Attack Chains UI ships. T3.7 NL → playbook. T3.8 design system v2 + Storybook. |
+| T4 | Connectors 11–15: Datadog, Snowflake, OCI, Dropbox, Cloudflare. |
+| T5 | T5.4 public scoreboard + T5.5 wet eval CI. |
+| T6 | T6.1 `app.aisoc.dev` waitlist live. T6.2 customer page template + first 2 case studies. |
+| T7 | T7.2 maturity model white paper. T7.3 blogs 2 + 3. |
+
+**Wk 9 milestone:** Effective Permissions + Attack Chains live on tryaisoc.com. 15+ new connectors total (≥ 40 live). 2 customer reference pages public. Cursor extension shipped.
+
+### Weeks 10–12 — polish + v8.0 launch
+- v8.0 release bundling everything in T1–T3
+- T6.4 demo seeder + 90s screencast cut
+- Launch sequence: HN post, Twitter thread, blog promotion, customer-quoted case studies
+- Final reference-customer logos go live
+- Cursor-extension demo video featured on landing
+
+**Wk 12 milestone:** v8.0 shipped. Effective Permissions + Attack Chains + NL Hunt + SOC Insights + 15 new connectors + 5 customer reference pages + Cursor extension + public sub-minute benchmark — all live.
+
+---
+
+## Appendix — task index
+
+```
+[ ] T1.1 Ingest-side graph writer (P0, L)
+[ ] T1.2 Config snapshots (P0, M) → T1.1
+[ ] T1.3 Publish graph schema (P0, S) → T1.1
+[ ] T1.4 Real-time graph-update WebSocket (P1, S) → T1.1
+[ ] T2.1 Pre-fetched context bundle (P0, M) → T1.1
+[ ] T2.2 LangGraph parallel topology (P0, M) → T2.1
+[ ] T2.3 LLM-input contract (P0, M) → T2.1
+[ ] T2.4 Token + USD eval telemetry (P0, S)
+[ ] T2.5 Four-agent brand consolidation (P0, S)
+[ ] T3.1 SOC Insights dashboard (P1, M) → T2.4
+[ ] T3.2 Effective Permissions (P0, L) → T1.1
+[ ] T3.3 Attack Chains (P0, L) → T1.1
+[ ] T3.4 /hunt NL surface (P0, S-M)
+[ ] T3.5 Business Context Rules (P1, M)
+[ ] T3.6 Slack/Teams Block Kit approvals (P1, M)
+[ ] T3.7 NL → playbook generator (P1, M) → T3.4
+[ ] T3.8 Design system v2 + Storybook (P1, M)
+[ ] T4.x 15-connector wave (P1, L total)
+[ ] T5.1 Speed + token + USD published (P0, S) → T2.4
+[ ] T5.2 Methodology page (P0, S) → T5.1
+[ ] T5.3 Public-dataset fidelity benchmark (P1, M)
+[ ] T5.4 Public scoreboard page (P1, M) → T5.1
+[ ] T5.5 Wet-eval weekly CI job (P1, S) → T2.4
+[ ] T6.1 app.aisoc.dev managed waitlist (P0, L) → T1.1, T2.2, T3.2, T3.3
+[ ] T6.2 Reference-customer page template (P0, S)
+[ ] T6.3 Sovereign + air-gap landing page (P1, S)
+[ ] T6.4 Demo seeder + screencast polish (P1, S)
+[ ] T7.1 Cursor extension (P0, M)
+[ ] T7.2 L0–L4 white paper (P1, S)
+[ ] T7.3 Three anchor blog posts (P1, S) → T5.1, T7.1
+```
diff --git a/services/agents/app/agents/auto_triage_agent.py b/services/agents/app/agents/auto_triage_agent.py
index 47c0b7eb1..b4df546e5 100644
--- a/services/agents/app/agents/auto_triage_agent.py
+++ b/services/agents/app/agents/auto_triage_agent.py
@@ -21,7 +21,9 @@ import structlog
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
+from app.llm import safe_ainvoke
from app.models.state import AgentStatus, InvestigationState
+from app.prompt_serialization import format_extra_fields_for_llm
logger = structlog.get_logger()
@@ -122,7 +124,7 @@ def _build_alert_context(state: InvestigationState) -> str:
extra_keys = {k for k in raw if k not in {"severity", "risk_score", "mitre_techniques", *ioc_fields}}
if extra_keys:
extras = {k: raw[k] for k in sorted(extra_keys)[:10]}
- parts.append(f"Additional fields: {json.dumps(extras, default=str)}")
+ parts.append("Additional fields (summary, not raw JSON):\n" + format_extra_fields_for_llm(extras))
return "\n".join(parts)
@@ -178,11 +180,12 @@ async def run_auto_triage(state: InvestigationState) -> InvestigationState:
t0 = time.monotonic()
try:
- response = await llm.ainvoke(
+ response = await safe_ainvoke(
+ llm,
[
SystemMessage(content=_SYSTEM_PROMPT),
HumanMessage(content=alert_context),
- ]
+ ],
)
raw_text = response.content
result = _parse_llm_response(raw_text)
diff --git a/services/agents/app/agents/cloud_agent.py b/services/agents/app/agents/cloud_agent.py
index 8e7edfb68..444cf231e 100644
--- a/services/agents/app/agents/cloud_agent.py
+++ b/services/agents/app/agents/cloud_agent.py
@@ -19,7 +19,9 @@ from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from app.context import ContextBundle
+from app.llm import safe_ainvoke
from app.models.state import AgentStatus, InvestigationState
+from app.prompt_serialization import format_extra_fields_for_llm, summarize_structure_for_llm
logger = structlog.get_logger()
@@ -87,17 +89,35 @@ def _build_cloud_context(state: InvestigationState) -> str:
if raw.get("bucket_acl") or raw.get("bucket_policy"):
parts.append(f"Bucket ACL: {raw.get('bucket_acl', 'N/A')}")
if raw.get("bucket_policy"):
- parts.append(f"Bucket Policy: {json.dumps(raw['bucket_policy'], default=str)[:500]}")
+ parts.append(
+ "Bucket Policy:\n"
+ + summarize_structure_for_llm(
+ raw["bucket_policy"], label="bucket_policy", max_lines=28, max_depth=3
+ )
+ )
if raw.get("security_group_rules"):
- parts.append(f"SG Rules: {json.dumps(raw['security_group_rules'], default=str)[:500]}")
+ parts.append(
+ "SG Rules:\n"
+ + summarize_structure_for_llm(
+ raw["security_group_rules"], label="security_group_rules", max_lines=28, max_depth=3
+ )
+ )
if raw.get("iam_policy") or raw.get("permissions"):
val = raw.get("iam_policy") or raw.get("permissions")
- parts.append(f"IAM/Permissions: {json.dumps(val, default=str)[:500]}")
+ parts.append(
+ "IAM/Permissions:\n"
+ + summarize_structure_for_llm(val, label="iam_permissions", max_lines=28, max_depth=3)
+ )
if raw.get("api_calls"):
- parts.append(f"API calls: {json.dumps(raw['api_calls'], default=str)[:500]}")
+ parts.append(
+ "API calls:\n"
+ + summarize_structure_for_llm(
+ raw["api_calls"], label="api_calls", max_lines=28, max_depth=2
+ )
+ )
if raw.get("is_public") is not None:
parts.append(f"Public access: {raw['is_public']}")
@@ -125,7 +145,7 @@ def _build_cloud_context(state: InvestigationState) -> str:
}
if extra_keys:
extras = {k: raw[k] for k in sorted(extra_keys)[:8]}
- parts.append(f"Additional fields: {json.dumps(extras, default=str)}")
+ parts.append("Additional fields:\n" + format_extra_fields_for_llm(extras, max_keys=8))
return "\n".join(parts)
@@ -197,11 +217,12 @@ async def run_cloud(
t0 = time.monotonic()
try:
- response = await llm.ainvoke(
+ response = await safe_ainvoke(
+ llm,
[
SystemMessage(content=_SYSTEM_PROMPT),
HumanMessage(content=prompt_context),
- ]
+ ],
)
result = _parse_response(response.content)
except Exception as exc:
diff --git a/services/agents/app/agents/identity_agent.py b/services/agents/app/agents/identity_agent.py
index 80a93ed10..65e406231 100644
--- a/services/agents/app/agents/identity_agent.py
+++ b/services/agents/app/agents/identity_agent.py
@@ -18,6 +18,8 @@ from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from app.context import ContextBundle
+from app.llm import safe_ainvoke
+from app.prompt_serialization import format_extra_fields_for_llm, summarize_structure_for_llm
from app.models.state import AgentStatus, InvestigationState
logger = structlog.get_logger()
@@ -82,14 +84,22 @@ def _build_identity_context(state: InvestigationState) -> str:
parts.append(f"{label}: {raw[key]}")
if raw.get("login_attempts"):
- parts.append(f"Login attempts: {json.dumps(raw['login_attempts'], default=str)}")
+ parts.append(
+ "Login attempts:\n"
+ + summarize_structure_for_llm(
+ raw["login_attempts"], label="login_attempts", max_lines=24, max_depth=2
+ )
+ )
if raw.get("failed_count"):
parts.append(f"Failed attempt count: {raw['failed_count']}")
geo_fields = ["login_locations", "geo_locations"]
for gf in geo_fields:
if raw.get(gf):
- parts.append(f"Geo locations: {json.dumps(raw[gf], default=str)}")
+ parts.append(
+ f"Geo locations ({gf}):\n"
+ + summarize_structure_for_llm(raw[gf], label=gf, max_lines=20, max_depth=2)
+ )
priv_fields = ["role_change", "group_added", "permissions_changed", "privilege_level"]
priv_parts = []
@@ -102,7 +112,12 @@ def _build_identity_context(state: InvestigationState) -> str:
if raw.get("timestamp"):
parts.append(f"Event time: {raw['timestamp']}")
if raw.get("previous_login"):
- parts.append(f"Previous login: {json.dumps(raw['previous_login'], default=str)}")
+ parts.append(
+ "Previous login:\n"
+ + summarize_structure_for_llm(
+ raw["previous_login"], label="previous_login", max_lines=16, max_depth=2
+ )
+ )
extra_keys = {
k
@@ -122,7 +137,7 @@ def _build_identity_context(state: InvestigationState) -> str:
}
if extra_keys:
extras = {k: raw[k] for k in sorted(extra_keys)[:8]}
- parts.append(f"Additional fields: {json.dumps(extras, default=str)}")
+ parts.append("Additional fields:\n" + format_extra_fields_for_llm(extras, max_keys=8))
return "\n".join(parts)
@@ -193,11 +208,12 @@ async def run_identity(
t0 = time.monotonic()
try:
- response = await llm.ainvoke(
+ response = await safe_ainvoke(
+ llm,
[
SystemMessage(content=_SYSTEM_PROMPT),
HumanMessage(content=prompt_context),
- ]
+ ],
)
result = _parse_response(response.content)
except Exception as exc:
diff --git a/services/agents/app/agents/insider_threat_agent.py b/services/agents/app/agents/insider_threat_agent.py
index 9bf5537e9..0722e55e2 100644
--- a/services/agents/app/agents/insider_threat_agent.py
+++ b/services/agents/app/agents/insider_threat_agent.py
@@ -19,7 +19,9 @@ from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from app.context import ContextBundle
+from app.llm import safe_ainvoke
from app.models.state import AgentStatus, InvestigationState
+from app.prompt_serialization import format_extra_fields_for_llm, summarize_structure_for_llm
logger = structlog.get_logger()
@@ -113,10 +115,20 @@ def _build_insider_context(state: InvestigationState) -> str:
parts.append(f"Destination domain: {raw['destination_domain']}")
if raw.get("usb_events"):
- parts.append(f"USB events: {json.dumps(raw['usb_events'], default=str)[:400]}")
+ parts.append(
+ "USB events:\n"
+ + summarize_structure_for_llm(
+ raw["usb_events"], label="usb_events", max_lines=24, max_depth=2
+ )
+ )
if raw.get("recent_activity"):
- parts.append(f"Recent activity: {json.dumps(raw['recent_activity'], default=str)[:400]}")
+ parts.append(
+ "Recent activity:\n"
+ + summarize_structure_for_llm(
+ raw["recent_activity"], label="recent_activity", max_lines=24, max_depth=2
+ )
+ )
if raw.get("baseline_deviation"):
parts.append(f"Baseline deviation: {raw['baseline_deviation']}")
@@ -144,7 +156,7 @@ def _build_insider_context(state: InvestigationState) -> str:
}
if extra_keys:
extras = {k: raw[k] for k in sorted(extra_keys)[:8]}
- parts.append(f"Additional fields: {json.dumps(extras, default=str)}")
+ parts.append("Additional fields:\n" + format_extra_fields_for_llm(extras, max_keys=8))
return "\n".join(parts)
@@ -218,11 +230,12 @@ async def run_insider_threat(
t0 = time.monotonic()
try:
- response = await llm.ainvoke(
+ response = await safe_ainvoke(
+ llm,
[
SystemMessage(content=_SYSTEM_PROMPT),
HumanMessage(content=prompt_context),
- ]
+ ],
)
result = _parse_response(response.content)
except Exception as exc:
diff --git a/services/agents/app/agents/phishing_agent.py b/services/agents/app/agents/phishing_agent.py
index 3ae267568..21d9ccc69 100644
--- a/services/agents/app/agents/phishing_agent.py
+++ b/services/agents/app/agents/phishing_agent.py
@@ -19,6 +19,8 @@ from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from app.context import ContextBundle
+from app.llm import safe_ainvoke
+from app.prompt_serialization import format_extra_fields_for_llm, summarize_structure_for_llm
from app.models.state import AgentStatus, InvestigationState
logger = structlog.get_logger()
@@ -70,14 +72,22 @@ def _build_phishing_context(state: InvestigationState) -> str:
parts.append(f"{label}: {raw[key]}")
if raw.get("urls"):
- parts.append(f"URLs found: {json.dumps(raw['urls'], default=str)}")
+ parts.append(
+ "URLs found:\n"
+ + summarize_structure_for_llm(raw["urls"], label="urls", max_lines=24, max_depth=2)
+ )
if raw.get("url"):
parts.append(f"Primary URL: {raw['url']}")
if raw.get("domain"):
parts.append(f"Domain: {raw['domain']}")
if raw.get("attachment_hashes"):
- parts.append(f"Attachment hashes: {json.dumps(raw['attachment_hashes'])}")
+ parts.append(
+ "Attachment hashes:\n"
+ + summarize_structure_for_llm(
+ raw["attachment_hashes"], label="attachment_hashes", max_lines=16, max_depth=1
+ )
+ )
if raw.get("file_hash"):
parts.append(f"File hash: {raw['file_hash']}")
@@ -117,7 +127,7 @@ def _build_phishing_context(state: InvestigationState) -> str:
}
if extra_keys:
extras = {k: raw[k] for k in sorted(extra_keys)[:8]}
- parts.append(f"Additional fields: {json.dumps(extras, default=str)}")
+ parts.append("Additional fields:\n" + format_extra_fields_for_llm(extras, max_keys=8))
return "\n".join(parts)
@@ -186,11 +196,12 @@ async def run_phishing(
t0 = time.monotonic()
try:
- response = await llm.ainvoke(
+ response = await safe_ainvoke(
+ llm,
[
SystemMessage(content=_SYSTEM_PROMPT),
HumanMessage(content=prompt_context),
- ]
+ ],
)
result = _parse_response(response.content)
except Exception as exc:
diff --git a/services/agents/app/api/contextual.py b/services/agents/app/api/contextual.py
index 61ed2db61..2d3a271aa 100644
--- a/services/agents/app/api/contextual.py
+++ b/services/agents/app/api/contextual.py
@@ -45,6 +45,9 @@ from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
+from app.llm import safe_ainvoke, safe_astream
+from app.prompt_serialization import summarize_structure_for_llm
+
logger = structlog.get_logger()
router = APIRouter(prefix="/api/v1/contextual", tags=["contextual"])
@@ -313,10 +316,12 @@ _SYSTEM_PROMPTS: dict[tuple[str, str], str] = {
def _serialize_entity(entity: dict[str, Any] | None, entity_id: str) -> str:
if not entity:
return f"(no entity payload supplied; entity_id={entity_id})"
- try:
- return json.dumps(entity, indent=2, default=str)[:8000]
- except (TypeError, ValueError):
- return repr(entity)[:8000]
+ return summarize_structure_for_llm(
+ entity,
+ label="entity_snapshot",
+ max_lines=80,
+ max_depth=3,
+ )
def _build_messages(req: ContextualActionRequest) -> tuple[str, str]:
@@ -337,7 +342,7 @@ def _build_messages(req: ContextualActionRequest) -> tuple[str, str]:
f"Entity ID: {req.entity_id}",
"",
"Entity snapshot:",
- "```json",
+ "```text",
entity_blob,
"```",
]
@@ -369,7 +374,7 @@ async def _call_llm(system: str, user: str, model: str) -> tuple[str, int]:
return _fallback_response(system, user), 0
llm = ChatOpenAI(model=model, temperature=0.2)
- response = await llm.ainvoke([SystemMessage(content=system), HumanMessage(content=user)])
+ response = await safe_ainvoke(llm, [SystemMessage(content=system), HumanMessage(content=user)])
text = response.content if isinstance(response.content, str) else str(response.content)
tokens = 0
if hasattr(response, "response_metadata"):
@@ -397,7 +402,7 @@ async def _stream_llm(system: str, user: str, model: str) -> AsyncIterator[str]:
return
llm = ChatOpenAI(model=model, temperature=0.2, streaming=True)
- async for chunk in llm.astream([SystemMessage(content=system), HumanMessage(content=user)]):
+ async for chunk in safe_astream(llm, [SystemMessage(content=system), HumanMessage(content=user)]):
if hasattr(chunk, "content") and chunk.content:
yield chunk.content if isinstance(chunk.content, str) else str(chunk.content)
diff --git a/services/agents/app/investigator/bundle_prompt.py b/services/agents/app/investigator/bundle_prompt.py
new file mode 100644
index 000000000..baa0b7f9c
--- /dev/null
+++ b/services/agents/app/investigator/bundle_prompt.py
@@ -0,0 +1,89 @@
+"""Format ContextBundle dicts for LLM prompts with sanitization (T2.1 / T2.3)."""
+
+from __future__ import annotations
+
+import uuid
+from types import SimpleNamespace
+from typing import Any
+
+import structlog
+
+from app.context.bundle import ContextBundle, ContextBundleBuilder
+from app.investigator.prompt_sanitizer import sanitize_text
+
+logger = structlog.get_logger()
+
+_BUNDLE_APPEND_MAX_LEN = 8000
+
+
+def stable_incident_uuid(case_id: str, tenant_id: str) -> uuid.UUID:
+ """Deterministic UUID for bundle builder when ``case_id`` is not a UUID."""
+ try:
+ return uuid.UUID(str(case_id))
+ except (ValueError, TypeError, AttributeError):
+ return uuid.uuid5(uuid.NAMESPACE_DNS, f"{tenant_id}:{case_id}")
+
+
+def _bundle_state_for_investigator(
+ *,
+ case_id: str,
+ tenant_id: str,
+ alert_summary: str,
+ raw_alert: dict[str, Any],
+) -> SimpleNamespace:
+ return SimpleNamespace(
+ incident_id=stable_incident_uuid(case_id, tenant_id),
+ tenant_id=tenant_id,
+ alert_summary=alert_summary,
+ raw_alert=raw_alert,
+ )
+
+
+async def prefetch_context_bundle_dict(
+ *,
+ case_id: str,
+ tenant_id: str,
+ alert_summary: str,
+ raw_alert: dict[str, Any],
+) -> dict[str, Any]:
+ """Build a JSON-serialisable ContextBundle dict; never raises."""
+ try:
+ builder = ContextBundleBuilder()
+ bundle = await builder.build(
+ _bundle_state_for_investigator(
+ case_id=case_id,
+ tenant_id=tenant_id,
+ alert_summary=alert_summary,
+ raw_alert=raw_alert,
+ )
+ )
+ return bundle.model_dump(mode="json")
+ except Exception as exc: # noqa: BLE001
+ safe_case = str(case_id).replace("\r", " ").replace("\n", " ")[:200]
+ safe_tenant = str(tenant_id).replace("\r", " ").replace("\n", " ")[:120]
+ logger.warning(
+ "context_bundle.prefetch_failed",
+ error=str(exc).replace("\r", " ").replace("\n", " ")[:500],
+ case_id=safe_case,
+ tenant_id=safe_tenant,
+ )
+ return {}
+
+
+def format_bundle_prompt_append(bundle_dict: dict[str, Any] | None) -> str:
+ """Return sanitized text to append to an LLM prompt, or empty string."""
+ if not bundle_dict:
+ return ""
+ try:
+ bundle = ContextBundle.model_validate(bundle_dict)
+ lines = bundle.prompt_context_lines()
+ if not lines:
+ return ""
+ text = "\n".join(lines)
+ return sanitize_text(text, max_len=_BUNDLE_APPEND_MAX_LEN)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "context_bundle.format_failed",
+ error=str(exc).replace("\r", " ").replace("\n", " ")[:500],
+ )
+ return ""
diff --git a/services/agents/app/investigator/forensic_agent.py b/services/agents/app/investigator/forensic_agent.py
index 6ee617465..fc2f8d548 100644
--- a/services/agents/app/investigator/forensic_agent.py
+++ b/services/agents/app/investigator/forensic_agent.py
@@ -20,9 +20,11 @@ from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from app.core.cost_telemetry import record_llm_call
+from app.llm import safe_ainvoke
+from app.prompt_serialization import summarize_structure_for_llm
+from .bundle_prompt import format_bundle_prompt_append
from .prompt_sanitizer import (
- sanitize_for_prompt,
sanitize_iterable_of_strings,
sanitize_text,
)
@@ -64,10 +66,11 @@ async def _llm_forensic(state: InvestigatorState) -> dict[str, Any]:
safe_summary = sanitize_text(state.alert_summary, max_len=2_000)
safe_recon = sanitize_text(state.recon.summary, max_len=2_000)
safe_mitre = sanitize_iterable_of_strings(state.recon.mitre_techniques, max_item_len=64, max_items=25)
- enrichment_blob = sanitize_for_prompt(
+ enrichment_blob = summarize_structure_for_llm(
dict(list(state.enrichment_cache.items())[:10]),
label="enrichment_cache",
- max_blob_len=3_000,
+ max_lines=40,
+ max_depth=2,
)
prompt = (
@@ -76,6 +79,9 @@ async def _llm_forensic(state: InvestigatorState) -> dict[str, Any]:
f"MITRE techniques: {safe_mitre}\n\n"
f"Enrichment data (sample):\n{enrichment_blob}"
)
+ bundle_append = format_bundle_prompt_append(state.context_bundle)
+ if bundle_append:
+ prompt = f"{prompt}\n\n{bundle_append}"
messages = [
SystemMessage(content=_SYSTEM_PROMPT),
@@ -94,7 +100,7 @@ async def _llm_forensic(state: InvestigatorState) -> dict[str, Any]:
t0 = time.monotonic()
try:
- response = await llm.ainvoke(messages)
+ response = await safe_ainvoke(llm, messages)
content = response.content
latency_ms = int((time.monotonic() - t0) * 1000)
tokens = 0
diff --git a/services/agents/app/investigator/orchestrator.py b/services/agents/app/investigator/orchestrator.py
index e9ce2009a..ff7ce9046 100644
--- a/services/agents/app/investigator/orchestrator.py
+++ b/services/agents/app/investigator/orchestrator.py
@@ -23,6 +23,7 @@ from opentelemetry import trace
from app.core.cost_telemetry import CostTracker
from . import ledger
+from .bundle_prompt import prefetch_context_bundle_dict
from .forensic_agent import run_forensic
from .recon_agent import run_recon
from .report_writer_agent import run_report_writer
@@ -150,11 +151,18 @@ class InvestigatorOrchestrator:
with _tracer.start_as_current_span("investigator.run") as span:
span.set_attribute("case.id", case_id)
span.set_attribute("tenant.id", tenant_id)
+ bundle = await prefetch_context_bundle_dict(
+ case_id=case_id,
+ tenant_id=tenant_id,
+ alert_summary=alert_summary,
+ raw_alert=raw_alert or {},
+ )
initial = InvestigatorState(
case_id=case_id,
alert_summary=alert_summary,
raw_alert=raw_alert or {},
tenant_id=tenant_id,
+ context_bundle=bundle,
)
run_uuid = run_id or uuid.uuid4()
@@ -249,11 +257,18 @@ class InvestigatorOrchestrator:
and only forward new entries. This same monotonic seq becomes the
primary sort key in the persisted ledger.
"""
+ bundle = await prefetch_context_bundle_dict(
+ case_id=case_id,
+ tenant_id=tenant_id,
+ alert_summary=alert_summary,
+ raw_alert=raw_alert or {},
+ )
initial = InvestigatorState(
case_id=case_id,
alert_summary=alert_summary,
raw_alert=raw_alert or {},
tenant_id=tenant_id,
+ context_bundle=bundle,
)
run_uuid = run_id or uuid.uuid4()
diff --git a/services/agents/app/investigator/recon_agent.py b/services/agents/app/investigator/recon_agent.py
index a4f89a83f..309fb2740 100644
--- a/services/agents/app/investigator/recon_agent.py
+++ b/services/agents/app/investigator/recon_agent.py
@@ -19,8 +19,11 @@ from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from app.core.cost_telemetry import record_llm_call
+from app.llm import safe_ainvoke
+from app.prompt_serialization import summarize_structure_for_llm
-from .prompt_sanitizer import sanitize_for_prompt, sanitize_text
+from .bundle_prompt import format_bundle_prompt_append
+from .prompt_sanitizer import sanitize_text
from .state import InvestigatorState, ReconFindings, StepKind
from .tools import enrich_ioc, extract_iocs, map_to_mitre, sha256_of
@@ -63,12 +66,19 @@ async def _llm_recon(state: InvestigatorState) -> dict[str, Any]:
# authoritative even if an attacker plants a "ignore previous instructions"
# payload inside a banner or log message.
safe_summary = sanitize_text(state.alert_summary, max_len=2_000)
- raw_alert_blob = sanitize_for_prompt(
- state.raw_alert,
- label="raw_alert",
- max_blob_len=3_000,
- )
- prompt = f"Alert summary:\n{safe_summary}\n\nRaw alert data:\n{raw_alert_blob}"
+ if isinstance(state.raw_alert, str):
+ raw_alert_blob = sanitize_text(state.raw_alert, max_len=2_500)
+ else:
+ raw_alert_blob = summarize_structure_for_llm(
+ state.raw_alert,
+ label="alert_structure",
+ max_lines=45,
+ max_depth=3,
+ )
+ prompt = f"Alert summary:\n{safe_summary}\n\nStructured alert summary:\n{raw_alert_blob}"
+ bundle_append = format_bundle_prompt_append(state.context_bundle)
+ if bundle_append:
+ prompt = f"{prompt}\n\n{bundle_append}"
messages = [
SystemMessage(content=_SYSTEM_PROMPT),
@@ -87,7 +97,7 @@ async def _llm_recon(state: InvestigatorState) -> dict[str, Any]:
t0 = time.monotonic()
try:
- response = await llm.ainvoke(messages)
+ response = await safe_ainvoke(llm, messages)
content = response.content
latency_ms = int((time.monotonic() - t0) * 1000)
tokens = 0
diff --git a/services/agents/app/investigator/report_writer_agent.py b/services/agents/app/investigator/report_writer_agent.py
index d29c2df90..a60dc50d6 100644
--- a/services/agents/app/investigator/report_writer_agent.py
+++ b/services/agents/app/investigator/report_writer_agent.py
@@ -18,9 +18,11 @@ from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from app.core.cost_telemetry import record_llm_call
+from app.llm import safe_ainvoke
+from app.prompt_serialization import summarize_structure_for_llm
+from .bundle_prompt import format_bundle_prompt_append
from .prompt_sanitizer import (
- sanitize_for_prompt,
sanitize_iterable_of_strings,
sanitize_text,
)
@@ -75,11 +77,17 @@ def _build_context(state: InvestigatorState) -> str:
safe_eradication = sanitize_iterable_of_strings(state.responder.eradication_steps[:5], max_item_len=400, max_items=5)
safe_recovery = sanitize_iterable_of_strings(state.responder.recovery_steps[:5], max_item_len=400, max_items=5)
- iocs_blob = sanitize_for_prompt(state.recon.iocs, label="iocs", max_blob_len=2_500)
- enrichment_blob = sanitize_for_prompt(
+ iocs_blob = summarize_structure_for_llm(
+ state.recon.iocs,
+ label="iocs",
+ max_lines=30,
+ max_depth=2,
+ )
+ enrichment_blob = summarize_structure_for_llm(
dict(list(state.enrichment_cache.items())[:5]),
label="enrichment_sample",
- max_blob_len=1_500,
+ max_lines=25,
+ max_depth=2,
)
sections = [
@@ -161,6 +169,9 @@ async def run_report_writer(state_dict: dict[str, Any]) -> dict[str, Any]:
llm = ChatOpenAI(model=model, temperature=0)
context = _build_context(state)
+ bundle_append = format_bundle_prompt_append(state.context_bundle)
+ if bundle_append:
+ context = f"{context}\n\n{bundle_append}"
system_prompt = _SYSTEM_PROMPT.format(case_id=state.case_id)
messages = [
SystemMessage(content=system_prompt),
@@ -179,7 +190,7 @@ async def run_report_writer(state_dict: dict[str, Any]) -> dict[str, Any]:
t_llm = time.monotonic()
try:
- response = await llm.ainvoke(messages)
+ response = await safe_ainvoke(llm, messages)
state.report_md = response.content
latency_ms = int((time.monotonic() - t_llm) * 1000)
tokens = 0
diff --git a/services/agents/app/investigator/responder_agent.py b/services/agents/app/investigator/responder_agent.py
index 160860ec2..015862522 100644
--- a/services/agents/app/investigator/responder_agent.py
+++ b/services/agents/app/investigator/responder_agent.py
@@ -19,9 +19,11 @@ from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from app.core.cost_telemetry import record_llm_call
+from app.llm import safe_ainvoke
+from app.prompt_serialization import summarize_structure_for_llm
+from .bundle_prompt import format_bundle_prompt_append
from .prompt_sanitizer import (
- sanitize_for_prompt,
sanitize_iterable_of_strings,
sanitize_text,
)
@@ -65,10 +67,11 @@ async def _llm_responder(state: InvestigatorState) -> dict[str, Any]:
safe_blast = sanitize_text(state.forensic.blast_radius, max_len=1_000)
safe_mitre = sanitize_iterable_of_strings(state.recon.mitre_techniques, max_item_len=64, max_items=25)
safe_actors = sanitize_iterable_of_strings(state.recon.threat_actors, max_item_len=128, max_items=25)
- timeline_blob = sanitize_for_prompt(
- state.forensic.timeline[-5:],
+ timeline_blob = summarize_structure_for_llm(
+ list(state.forensic.timeline[-5:]),
label="timeline_tail",
- max_blob_len=2_500,
+ max_lines=35,
+ max_depth=2,
)
prompt = (
@@ -80,6 +83,9 @@ async def _llm_responder(state: InvestigatorState) -> dict[str, Any]:
f"Threat actors: {safe_actors}\n\n"
f"Timeline (last 5):\n{timeline_blob}"
)
+ bundle_append = format_bundle_prompt_append(state.context_bundle)
+ if bundle_append:
+ prompt = f"{prompt}\n\n{bundle_append}"
messages = [
SystemMessage(content=_SYSTEM_PROMPT),
@@ -98,7 +104,7 @@ async def _llm_responder(state: InvestigatorState) -> dict[str, Any]:
t0 = time.monotonic()
try:
- response = await llm.ainvoke(messages)
+ response = await safe_ainvoke(llm, messages)
content = response.content
latency_ms = int((time.monotonic() - t0) * 1000)
tokens = 0
diff --git a/services/agents/app/investigator/state.py b/services/agents/app/investigator/state.py
index 383526ee7..42cfa8c2a 100644
--- a/services/agents/app/investigator/state.py
+++ b/services/agents/app/investigator/state.py
@@ -118,6 +118,9 @@ class InvestigatorState(BaseModel):
# Shared enrichment cache (IOC → enrichment result)
enrichment_cache: dict[str, Any] = Field(default_factory=dict)
+ # Pre-fetched ContextBundle (T2.1 / T2.3) — JSON-serialisable dict appended to LLM prompts.
+ context_bundle: dict[str, Any] = Field(default_factory=dict)
+
# LLM message history (accumulated for context)
messages: list[dict[str, Any]] = Field(default_factory=list)
diff --git a/services/agents/app/llm/__init__.py b/services/agents/app/llm/__init__.py
index c1b2b00c0..700e177cd 100644
--- a/services/agents/app/llm/__init__.py
+++ b/services/agents/app/llm/__init__.py
@@ -11,22 +11,28 @@ leaking raw payloads to a third-party model.
from .contract import (
AGENTS_LLM_CONTRACT_ENFORCED_ENV,
+ CONTRACT_DICT_KEY_BLOCKLIST,
LLMContractViolation,
LLMInputContract,
classify_message,
is_contract_enforced,
+ make_safe_chat_model,
safe_ainvoke,
+ safe_astream,
set_contract_enforcement,
validate_messages,
)
__all__ = [
"AGENTS_LLM_CONTRACT_ENFORCED_ENV",
+ "CONTRACT_DICT_KEY_BLOCKLIST",
"LLMContractViolation",
"LLMInputContract",
"classify_message",
"is_contract_enforced",
+ "make_safe_chat_model",
"safe_ainvoke",
+ "safe_astream",
"set_contract_enforcement",
"validate_messages",
]
diff --git a/services/agents/app/llm/contract.py b/services/agents/app/llm/contract.py
index cb66a6338..84c45ef96 100644
--- a/services/agents/app/llm/contract.py
+++ b/services/agents/app/llm/contract.py
@@ -67,6 +67,10 @@ _LOG_KEYS = frozenset(
}
)
+# Union of dict keys that must never appear in LLM-bound JSON strings
+# (prompt serialization uses this to redact / shallow-summarize nested data).
+CONTRACT_DICT_KEY_BLOCKLIST: frozenset[str] = frozenset(_OCSF_KEYS | _LOG_KEYS)
+
# Compact regex for the most common raw-log signatures we want to catch
# even when the payload is rendered as a string instead of a dict.
_LOG_SHAPE_PATTERNS = (
diff --git a/services/agents/app/prompt_serialization.py b/services/agents/app/prompt_serialization.py
new file mode 100644
index 000000000..3a0b94740
--- /dev/null
+++ b/services/agents/app/prompt_serialization.py
@@ -0,0 +1,119 @@
+"""Line-oriented serialization for LLM prompts (T2.1 / T2.3).
+
+Avoid ``json.dumps`` of alert-shaped dicts in user-visible prompt text:
+``classify_message`` treats the final string and can false-positive on
+OCSF-like patterns. Prefer shallow key–value lines and blocked-key redaction.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from app.llm.contract import CONTRACT_DICT_KEY_BLOCKLIST
+
+
+def _format_primitive(v: Any) -> str:
+ if v is None:
+ return "(null)"
+ if isinstance(v, bool):
+ return "true" if v else "false"
+ if isinstance(v, (int, float)):
+ return str(v)
+ s = str(v).replace("\r", " ").replace("\n", " ")
+ if len(s) > 400:
+ return s[:400] + "…"
+ return s
+
+
+def format_extra_fields_for_llm(
+ extra: dict[str, Any],
+ *,
+ max_keys: int = 12,
+ max_depth: int = 2,
+) -> str:
+ """Format a flat-ish dict as newline-separated ``key: value`` lines."""
+ if not extra:
+ return "(none)"
+ lines: list[str] = []
+ keys = sorted(extra.keys(), key=str)
+ omitted = 0
+ for k in keys:
+ if len(lines) >= max_keys:
+ omitted = len(keys) - len(lines)
+ break
+ if str(k) in CONTRACT_DICT_KEY_BLOCKLIST:
+ lines.append(f"{k}: <redacted: contract key>")
+ continue
+ v = extra[k]
+ if isinstance(v, dict):
+ lines.append(
+ f"{k}:\n{summarize_structure_for_llm(v, label=str(k), max_lines=10, max_depth=max_depth)}"
+ )
+ elif isinstance(v, (list, tuple)):
+ lines.append(
+ f"{k}:\n{summarize_structure_for_llm(list(v), label=str(k), max_lines=10, max_depth=max_depth)}"
+ )
+ else:
+ lines.append(f"{k}: {_format_primitive(v)}")
+ if omitted > 0:
+ lines.append(f"… and {omitted} more keys omitted")
+ return "\n".join(lines)
+
+
+def summarize_structure_for_llm(
+ obj: Any,
+ *,
+ label: str = "data",
+ max_lines: int = 40,
+ max_depth: int = 2,
+) -> str:
+ """Summarize nested dict/list structures without emitting raw OCSF JSON."""
+ out: list[str] = []
+
+ def add(line: str) -> None:
+ if len(out) < max_lines:
+ out.append(line)
+
+ def visit(node: Any, path: str, depth: int) -> None:
+ if len(out) >= max_lines:
+ return
+ if depth > max_depth:
+ add(f"{path}: <nested, depth cap>")
+ return
+ if isinstance(node, dict):
+ keys = [k for k in node if str(k) not in CONTRACT_DICT_KEY_BLOCKLIST]
+ if not keys:
+ add(f"{path}: <dict (keys redacted)>")
+ return
+ for k in sorted(keys, key=str)[:30]:
+ if len(out) >= max_lines:
+ break
+ v = node[k]
+ sub = f"{path}.{k}" if path else str(k)
+ if isinstance(v, dict):
+ nk = len([x for x in v if str(x) not in CONTRACT_DICT_KEY_BLOCKLIST])
+ add(f"{sub}: dict({nk} keys)")
+ if depth < max_depth and nk <= 12:
+ visit(v, sub, depth + 1)
+ elif isinstance(v, (list, tuple)):
+ add(f"{sub}: list[{len(v)} items]")
+ if depth < max_depth:
+ cap = min(5, len(v))
+ for i in range(cap):
+ visit(v[i], f"{sub}[{i}]", depth + 1)
+ if len(v) > cap:
+ add(f"{sub}: … {len(v) - cap} more items omitted")
+ else:
+ add(f"{sub}: {_format_primitive(v)}")
+ elif isinstance(node, (list, tuple)):
+ add(f"{path}: list[{len(node)}]")
+ if depth < max_depth:
+ for i, it in enumerate(node[:6]):
+ visit(it, f"{path}[{i}]", depth + 1)
+ if len(node) > 6:
+ add(f"{path}: … {len(node) - 6} more items omitted")
+ else:
+ add(f"{path}: {_format_primitive(node)}")
+
+ visit(obj, label, 0)
+ return "\n".join(out) if out else "(empty)"
diff --git a/services/agents/tests/test_llm_contract.py b/services/agents/tests/test_llm_contract.py
new file mode 100644
index 000000000..0e2c31d05
--- /dev/null
+++ b/services/agents/tests/test_llm_contract.py
@@ -0,0 +1,68 @@
+"""Tests for T2.3 LLM input contract: no raw OCSF / vendor log JSON in model messages.
+
+Uses ``summarize_structure_for_llm`` for safe payloads and asserts
+``validate_messages`` / ``LLMInputContract`` reject raw JSON blobs that match
+log-shape heuristics (e.g. ``class_uid``).
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from app.llm.contract import (
+ LLMContractViolation,
+ LLMInputContract,
+ classify_message,
+ set_contract_enforcement,
+ validate_messages,
+)
+from app.prompt_serialization import summarize_structure_for_llm
+
+
+def contract_enforced():
+ prev = set_contract_enforcement(True)
+ try:
+ yield
+ finally:
+ set_contract_enforcement(prev)
+
+
+def test_classify_message_flags_minimal_ocsf_json() -> None:
+ """Raw OCSF-shaped JSON must be classified as log-like."""
+ blob = json.dumps({"class_uid": 7003, "category_uid": 2, "activity_id": 1})
+ assert classify_message(blob) is not None
+
+
+def test_llm_input_contract_rejects_raw_ocsf_json(contract_enforced) -> None:
+ raw = json.dumps({"class_uid": 1, "activity_id": 2, "metadata": {"product": "AWS"}})
+ with pytest.raises(LLMContractViolation):
+ LLMInputContract.validate([{"role": "user", "content": raw}])
+
+
+def test_validate_messages_accepts_summarized_structure(contract_enforced) -> None:
+ entity = {
+ "user_id": "u-1",
+ "display_name": "Alice",
+ "risk": {"score": 42},
+ }
+ body = summarize_structure_for_llm(
+ entity, label="entity_snapshot", max_lines=80, max_depth=3
+ )
+ msgs = [
+ {"role": "system", "content": "You are a security analyst."},
+ {"role": "user", "content": body},
+ ]
+ validate_messages(msgs)
+ LLMInputContract.validate(msgs)
+
+
+def test_validate_messages_rejects_nested_json_string_with_class_uid(
+ contract_enforced,
+) -> None:
+ """Even inside prose, a substring matching OCSF field names must fail."""
+ bad = "Context: " + json.dumps({"class_uid": 99})
+ with pytest.raises(LLMContractViolation):
+ validate_messages([{"role": "user", "content": bad}])
diff --git a/services/connectors/app/connectors/azure_defender.py b/services/connectors/app/connectors/azure_defender.py
index 9d21f9295..9e52258e5 100644
--- a/services/connectors/app/connectors/azure_defender.py
+++ b/services/connectors/app/connectors/azure_defender.py
@@ -19,6 +19,7 @@ from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
+from urllib.parse import quote
import httpx
import structlog
@@ -169,6 +170,46 @@ class AzureDefenderConnector(BaseConnector):
return [self.normalize(a) for a in alerts]
+ async def get_resource_config(
+ self,
+ resource_id: str,
+ at_ts: str | None = None,
+ ) -> dict[str, Any]:
+ """Fetch a single ``alerts_v2`` record by Graph alert id (``external_id``)."""
+ if not (resource_id or "").strip():
+ return {}
+ alert_id = resource_id.strip()
+ url = f"{_GRAPH_BASE}/security/alerts_v2/{quote(alert_id, safe='')}"
+
+ if not self._access_token:
+ await self._authenticate()
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(url, headers=self._headers())
+ if resp.status_code == 401:
+ logger.warning(
+ "azure_defender.get_resource_config_unauthorized",
+ alert_id=str(alert_id).replace("\r", "").replace("\n", " ")[:256],
+ )
+ await self._authenticate()
+ resp = await client.get(url, headers=self._headers())
+ if resp.status_code != 200:
+ logger.warning(
+ "azure_defender.get_resource_config_failed",
+ status=resp.status_code,
+ alert_id=str(alert_id).replace("\r", "").replace("\n", " ")[:256],
+ body=str(resp.text).replace("\r", "").replace("\n", " ")[:300],
+ )
+ return {}
+ try:
+ body = resp.json()
+ except Exception: # noqa: BLE001
+ return {}
+ out: dict[str, Any] = {"raw": body, "snapshot_freshness": "live"}
+ if at_ts:
+ out["snapshot_requested_at"] = at_ts
+ return out
+
# ----------------------- normalize --------------------------
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
diff --git a/services/connectors/app/connectors/gcp_scc.py b/services/connectors/app/connectors/gcp_scc.py
index 095885d2c..efc988c2c 100644
--- a/services/connectors/app/connectors/gcp_scc.py
+++ b/services/connectors/app/connectors/gcp_scc.py
@@ -228,6 +228,46 @@ class GCPSCCConnector(BaseConnector):
return [self.normalize(item) for item in entries]
+ async def get_resource_config(
+ self,
+ resource_id: str,
+ at_ts: str | None = None,
+ ) -> dict[str, Any]:
+ """Fetch one SCC finding by full resource name (``external_id`` from normalize)."""
+ if not (resource_id or "").strip():
+ return {}
+ rid = resource_id.strip()
+ url = f"{_SCC_BASE}/{rid}"
+
+ await self._authenticate()
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(url, headers=self._headers())
+ if resp.status_code == 401:
+ logger.warning(
+ "gcp_scc.get_resource_config_unauthorized",
+ finding=str(rid).replace("\r", "").replace("\n", " ")[:512],
+ )
+ self._access_token = None
+ await self._authenticate()
+ resp = await client.get(url, headers=self._headers())
+ if resp.status_code != 200:
+ logger.warning(
+ "gcp_scc.get_resource_config_failed",
+ status=resp.status_code,
+ finding=str(rid).replace("\r", "").replace("\n", " ")[:512],
+ body=str(resp.text).replace("\r", "").replace("\n", " ")[:300],
+ )
+ return {}
+ try:
+ body = resp.json()
+ except Exception: # noqa: BLE001
+ return {}
+ out: dict[str, Any] = {"raw": body, "snapshot_freshness": "live"}
+ if at_ts:
+ out["snapshot_requested_at"] = at_ts
+ return out
+
# ----------------------- normalize --------------------------
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
diff --git a/services/connectors/tests/test_azure_connectors.py b/services/connectors/tests/test_azure_connectors.py
index 34d6899bd..73ea04fca 100644
--- a/services/connectors/tests/test_azure_connectors.py
+++ b/services/connectors/tests/test_azure_connectors.py
@@ -333,3 +333,69 @@ async def test_azure_defender_fetch_alerts_returns_normalized_events():
assert len(events) == 1
assert events[0]["severity"] == "high"
assert events[0]["source"] == "azure_defender"
+
+
+async def test_azure_defender_get_resource_config_empty_id():
+ connector = AzureDefenderConnector(_TENANT, _CLIENT, _SECRET)
+ assert await connector.get_resource_config("") == {}
+ assert await connector.get_resource_config(" ") == {}
+
+
+async def test_azure_defender_get_resource_config_success():
+ respx.post(f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token").mock(
+ return_value=httpx.Response(200, json={"access_token": "abc", "expires_in": 3600})
+ )
+ detail_url = "https://graph.microsoft.com/v1.0/security/alerts_v2/alert-detail-1"
+ respx.get(detail_url).mock(
+ return_value=httpx.Response(
+ 200,
+ json={"id": "alert-detail-1", "title": "Detail", "severity": "high"},
+ )
+ )
+
+ connector = AzureDefenderConnector(_TENANT, _CLIENT, _SECRET)
+ cfg = await connector.get_resource_config("alert-detail-1", at_ts="2026-01-15T12:00:00Z")
+ assert cfg["snapshot_freshness"] == "live"
+ assert cfg["snapshot_requested_at"] == "2026-01-15T12:00:00Z"
+ assert cfg["raw"]["id"] == "alert-detail-1"
+ assert cfg["raw"]["title"] == "Detail"
+
+
+async def test_azure_defender_get_resource_config_401_then_retry():
+ respx.post(f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token").mock(
+ side_effect=[
+ httpx.Response(200, json={"access_token": "tok-1", "expires_in": 3600}),
+ httpx.Response(200, json={"access_token": "tok-2", "expires_in": 3600}),
+ ]
+ )
+ detail_url = "https://graph.microsoft.com/v1.0/security/alerts_v2/alert-retry"
+ respx.get(detail_url).mock(
+ side_effect=[
+ httpx.Response(401, text="expired"),
+ httpx.Response(200, json={"id": "alert-retry", "title": "After refresh"}),
+ ]
+ )
+
+ connector = AzureDefenderConnector(_TENANT, _CLIENT, _SECRET)
+ cfg = await connector.get_resource_config("alert-retry")
+ assert cfg["raw"]["title"] == "After refresh"
+
+
+async def test_azure_defender_get_resource_config_non_200_returns_empty():
+ respx.post(f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token").mock(
+ return_value=httpx.Response(200, json={"access_token": "abc", "expires_in": 3600})
+ )
+ respx.get("https://graph.microsoft.com/v1.0/security/alerts_v2/missing").mock(
+ return_value=httpx.Response(404, text="not found")
+ )
+
+ connector = AzureDefenderConnector(_TENANT, _CLIENT, _SECRET)
+ assert await connector.get_resource_config("missing") == {}
diff --git a/services/connectors/tests/test_gcp_connectors.py b/services/connectors/tests/test_gcp_connectors.py
index a5f604401..7779c5a45 100644
--- a/services/connectors/tests/test_gcp_connectors.py
+++ b/services/connectors/tests/test_gcp_connectors.py
@@ -379,3 +379,76 @@ async def test_scc_fetch_alerts_returns_normalized_findings(fake_sa_json):
assert events[0]["severity"] == "high"
assert events[0]["title"] == "PUBLIC_BUCKET_ACL"
assert events[0]["resource_type"] == "google.cloud.storage.Bucket"
+
+
+async def test_scc_get_resource_config_empty_id(fake_sa_json):
+ connector = GCPSCCConnector(_ORG, fake_sa_json)
+ assert await connector.get_resource_config("") == {}
+ assert await connector.get_resource_config(" ") == {}
+
+
+async def test_scc_get_resource_config_success(fake_sa_json):
+ respx.post("https://oauth2.googleapis.com/token").mock(
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
+ )
+ finding_name = f"organizations/{_ORG}/sources/888/findings/detail-1"
+ respx.get(f"https://securitycenter.googleapis.com/v1/{finding_name}").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "name": finding_name,
+ "category": "IAM_ANOMALY",
+ "severity": "MEDIUM",
+ "eventTime": "2026-01-01T00:00:00Z",
+ },
+ )
+ )
+
+ connector = GCPSCCConnector(_ORG, fake_sa_json)
+ cfg = await connector.get_resource_config(finding_name, at_ts="2026-01-10T00:00:00Z")
+ assert cfg["snapshot_freshness"] == "live"
+ assert cfg["snapshot_requested_at"] == "2026-01-10T00:00:00Z"
+ assert cfg["raw"]["category"] == "IAM_ANOMALY"
+ assert cfg["raw"]["name"] == finding_name
+
+
+async def test_scc_get_resource_config_401_then_retry(fake_sa_json):
+ respx.post("https://oauth2.googleapis.com/token").mock(
+ side_effect=[
+ httpx.Response(200, json={"access_token": "tok-1", "expires_in": 3600}),
+ httpx.Response(200, json={"access_token": "tok-2", "expires_in": 3600}),
+ ]
+ )
+ finding_name = f"organizations/{_ORG}/sources/888/findings/retry-f"
+ detail_url = f"https://securitycenter.googleapis.com/v1/{finding_name}"
+ respx.get(detail_url).mock(
+ side_effect=[
+ httpx.Response(401, text="invalid authentication credentials"),
+ httpx.Response(200, json={"name": finding_name, "category": "OPEN_FIREWALL", "severity": "LOW"}),
+ ]
+ )
+
+ connector = GCPSCCConnector(_ORG, fake_sa_json)
+ cfg = await connector.get_resource_config(finding_name)
+ assert cfg["raw"]["category"] == "OPEN_FIREWALL"
+
+
+async def test_scc_get_resource_config_non_200_returns_empty(fake_sa_json):
+ respx.post("https://oauth2.googleapis.com/token").mock(
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
+ )
+ finding_name = f"organizations/{_ORG}/sources/888/findings/gone"
+ respx.get(f"https://securitycenter.googleapis.com/v1/{finding_name}").mock(
+ return_value=httpx.Response(404, text="not found")
+ )
+
+ connector = GCPSCCConnector(_ORG, fake_sa_json)
+ assert await connector.get_resource_config(finding_name) == {}
diff --git a/services/realtime/src/index.ts b/services/realtime/src/index.ts
index a04d979c1..36aa7d0fa 100644
--- a/services/realtime/src/index.ts
+++ b/services/realtime/src/index.ts
@@ -15,6 +15,17 @@ const PORT = parseInt(process.env.PORT || '8086', 10);
const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379/4';
const KAFKA_BROKERS = (process.env.KAFKA_BOOTSTRAP_SERVERS || 'localhost:9092').split(',');
const KAFKA_TOPIC_FUSED = process.env.KAFKA_TOPIC_FUSED || 'aisoc.alerts.fused';
+// T1.4 (v8.0): graph-update channel. The ingest-side graph writer publishes
+// one envelope per node/edge upsert on `security.graph_updates`; we fan out
+// to WebSocket clients subscribed to `/ws/graph`. Topic name matches the
+// default in services/ingest/internal/config/config.go (env
+// `AISOC_GRAPH_UPDATES_TOPIC`) so the two services agree without manual
+// plumbing. Set to an empty string to disable the consumer entirely (useful
+// in tests that don't spin up Kafka for graph traffic).
+const KAFKA_TOPIC_GRAPH_UPDATES =
+ process.env.AISOC_GRAPH_UPDATES_TOPIC ||
+ process.env.KAFKA_TOPIC_GRAPH_UPDATES ||
+ 'security.graph_updates';
const VAPID_PUBLIC_KEY = process.env.VAPID_PUBLIC_KEY || '';
const VAPID_PRIVATE_KEY = process.env.VAPID_PRIVATE_KEY || '';
const VAPID_SUBJECT = process.env.VAPID_SUBJECT || 'mailto:[email protected]';
@@ -120,15 +131,22 @@ const server = http.createServer(app);
// --- WebSocket server ---
// Accept both `/ws` (legacy) and `/ws/:channel` (preferred). The channel lets
// callers say up-front what they care about (alerts, cases, agents, insights,
-// all) so we can avoid spamming a panel that only renders alerts with
+// graph, all) so we can avoid spamming a panel that only renders alerts with
// case/agent traffic.
//
// The `insights` channel (T3.1) is consumed by
// apps/web/src/app/(app)/dashboards/soc-insights/page.tsx to know when to
// re-fetch the aggregator endpoint. The payload itself stays small —
// it's a poke, not a data delivery.
-type Channel = 'alerts' | 'cases' | 'agents' | 'insights' | 'all';
-const VALID_CHANNELS: Channel[] = ['alerts', 'cases', 'agents', 'insights', 'all'];
+//
+// The `graph` channel (T1.4, v8.0) is consumed by the Investigation Rail and
+// Attack Chain views to light up new entity nodes / edges in near-real-time.
+// Unlike `insights`, the payload IS the delivery: each message carries the
+// full GraphUpdate envelope from `security.graph_updates` (entity_id,
+// change_type, label, rel_type, from, to, properties, schema_version), so
+// the client can apply the mutation locally without re-querying Neo4j.
+type Channel = 'alerts' | 'cases' | 'agents' | 'insights' | 'graph' | 'all';
+const VALID_CHANNELS: Channel[] = ['alerts', 'cases', 'agents', 'insights', 'graph', 'all'];
const wss = new WebSocketServer({ noServer: true });
@@ -212,6 +230,12 @@ const CHANNEL_FOR_TYPE: Record<string, Channel[]> = {
// T3.1: SOC Insights dashboard tick. Both the dedicated `insights`
// subscribers and any `all`-subscribed admin consoles get the poke.
'insights_updated': ['insights', 'all'],
+ // T1.4 (v8.0): graph-mutation fan-out from the ingest-side writer.
+ // `graph.update` carries the full GraphUpdate envelope; `graph` and
+ // `all` subscribers both receive it. We deliberately do NOT include
+ // `insights` here — the SOC Insights dashboard is a stats poke, not a
+ // graph-render surface.
+ 'graph.update': ['graph', 'all'],
};
function broadcastToTenant(tenantId: string, message: { type: string } & Record<string, unknown>) {
@@ -321,14 +345,16 @@ app.get('/sse', sseRateLimit, (req, res) => {
});
});
+// Single shared Kafka client so we don't spin up a second TCP fan-out for
+// each topic; kafkajs multiplexes consumers internally.
+const kafka = new Kafka({
+ clientId: 'aisoc-realtime',
+ brokers: KAFKA_BROKERS,
+ retry: { retries: 5 },
+});
+
// --- Kafka consumer: bridge fused alerts to WebSocket clients ---
async function startKafkaConsumer() {
- const kafka = new Kafka({
- clientId: 'aisoc-realtime',
- brokers: KAFKA_BROKERS,
- retry: { retries: 5 },
- });
-
const consumer = kafka.consumer({ groupId: 'aisoc-realtime-ws' });
await consumer.connect();
@@ -390,6 +416,87 @@ async function startKafkaConsumer() {
});
}
+// --- Kafka consumer: bridge graph mutations to WebSocket clients (T1.4) ---
+// The ingest-side graph writer (services/ingest/internal/graph/writer.go)
+// publishes one envelope per node/edge upsert on `security.graph_updates`.
+// We fan that stream out to clients subscribed to `/ws/graph` (or `/ws/all`),
+// scoped by tenant. We deliberately run this on its own consumer group so a
+// graph-side stall can't backpressure the fused-alert fan-out — and vice
+// versa. A failure to start (Kafka unreachable, topic missing, etc.) is
+// logged and surfaced via the outer retry wrapper; it does NOT crash the
+// process, because the alert fan-out path is the higher-priority surface.
+async function startGraphUpdateConsumer() {
+ if (!KAFKA_TOPIC_GRAPH_UPDATES) {
+ log.info('Graph update consumer disabled (empty KAFKA_TOPIC_GRAPH_UPDATES)');
+ return;
+ }
+
+ const consumer = kafka.consumer({ groupId: 'aisoc-realtime-graph' });
+
+ await consumer.connect();
+ await consumer.subscribe({
+ topic: KAFKA_TOPIC_GRAPH_UPDATES,
+ // We never want to replay the full graph history on a realtime restart —
+ // a panel that connects today should see deltas from now, not from the
+ // start of the topic.
+ fromBeginning: false,
+ });
+
+ log.info(
+ { topic: KAFKA_TOPIC_GRAPH_UPDATES, groupId: 'aisoc-realtime-graph' },
+ 'Graph update Kafka consumer connected',
+ );
+
+ await consumer.run({
+ eachMessage: async ({ message }) => {
+ if (!message.value) return;
+ try {
+ // The Go writer emits the camel-case-on-the-wire form documented in
+ // services/ingest/internal/graph/writer.go: `entity_id`,
+ // `change_type`, `ts`, `label`, `rel_type`, `from`, `to`,
+ // `properties`, `schema_version`, `tenant_id`. Anything else is
+ // treated as a malformed envelope and dropped.
+ const update = JSON.parse(message.value.toString()) as {
+ entity_id?: string;
+ change_type?: string;
+ ts?: string;
+ label?: string;
+ rel_type?: string;
+ from?: string;
+ to?: string;
+ properties?: Record<string, unknown>;
+ schema_version?: string;
+ tenant_id?: string;
+ };
+
+ if (!update.entity_id || !update.change_type) {
+ // Headerless or partial envelopes are almost always a producer
+ // bug — log once at warn so we notice in CI but don't tear the
+ // consumer down. (kafkajs auto-commits the offset either way.)
+ log.warn(
+ { entity_id: update.entity_id, change_type: update.change_type },
+ 'Dropping malformed graph update (missing entity_id or change_type)',
+ );
+ return;
+ }
+
+ // Per-tenant fan-out. Default to "default" so single-tenant
+ // self-hosted deploys keep working without explicit tenant tagging
+ // (matches the policy on the fused-alerts consumer above).
+ const tenantId = update.tenant_id || 'default';
+
+ broadcastToTenant(tenantId, {
+ type: 'graph.update',
+ payload: update,
+ timestamp: new Date().toISOString(),
+ });
+ } catch (err) {
+ log.warn({ err }, 'Failed to parse graph update Kafka message');
+ }
+ },
+ });
+}
+
// --- Web Push routes (Phase 4B mobile responder PWA) ---
// Public key is needed by the browser to subscribe; the rest are
// authenticated routes the API gateway forwards on behalf of a user.
@@ -534,9 +641,29 @@ app.get('/healthz', reportHealth);
// default or the container is launched with IPv6 disabled.
server.listen(PORT, '::', async () => {
log.info({ port: PORT, host: '::' }, 'AiSOC Real-time service started');
- try {
- await startKafkaConsumer();
- } catch (err) {
- log.warn({ err }, 'Kafka consumer failed to start (will retry)');
- }
+
+ // Start the two Kafka consumers concurrently. Each is wrapped in its own
+ // try/catch so a failure on the graph topic (e.g. it doesn't exist yet on
+ // a brand-new cluster) does NOT block the higher-priority fused-alerts
+ // fan-out. We deliberately fire them in parallel rather than awaiting
+ // sequentially so the HTTP/WS listener is fully up before either Kafka
+ // round-trip completes.
+ void (async () => {
+ try {
+ await startKafkaConsumer();
+ } catch (err) {
+ log.warn({ err }, 'Kafka consumer failed to start (will retry)');
+ }
+ })();
+
+ void (async () => {
+ try {
+ await startGraphUpdateConsumer();
+ } catch (err) {
+ // T1.4 fan-out is best-effort: if the graph topic isn't available the
+ // alerts/cases/agents/insights channels still work, the graph panel
+ // just won't light up in real time.
+ log.warn({ err }, 'Graph update consumer failed to start (will retry)');
+ }
+ })();
});