# dshapi/ai-spm architecture

> Architecture diagram of the GitHub repository dshapi/ai-spm, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-20). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/dshapi/ai-spm
- Repository: https://github.com/dshapi/ai-spm

## Overview

1. **Overall shape**
   - This repository is a multi-service AI security posture management platform.
   - It splits into a **user-facing chat/control path**, a **security telemetry and policy plane**, and a **compliance/analytics plane**.
   - Most backend services are Python 3.11 with FastAPI; the frontend is a React/Vite single-page app. Docker Compose is the deployment boundary.

2. **User-facing entrypoints**
   - There are two primary UIs: the **Orbyx Chat UI** for interacting with the LLM gateway, and the **admin portal** for posture, inventory, cases, policies, and simulation views.
   - The chat UI talks to the main API gateway. The admin UI talks mostly to the SPM APIs and consumes metrics/event-derived views.
   - An optional auth overlay adds **Traefik + Keycloak + forward-auth** in front of the admin portal for local SSO.

3. **Main request path for prompts**
   - User prompts enter the **`services/api` gateway**, which performs JWT auth, per-user rate limiting, prompt/security screening, OPA policy checks, and memory lookup.
   - The gateway then calls the external LLM provider, currently Anthropic-compatible models, and may also call Tavily for web search or fetch tools.
   - Responses go back through a second-pass output safety layer before being returned to the user.

4. **Prompt security boundary**
   - Prompt safety is enforced by multiple layers rather than a single filter.
   - `guard-model` handles content moderation, `memory-service` screens stored context for injection patterns, and OPA policies decide allow/escalate/block based on posture and auth context.
   - `output_guard` and output-scanning logic in the API protect the egress side, especially for secrets and PII.

5. **Event backbone**
   - Kafka is the central asynchronous bus. Tenant-scoped topics carry raw events, posture-enriched events, decisions, tool requests/results, memory events, approvals, freeze controls, and audit data.
   - This is the main decoupling boundary: the interactive API emits events, while analytics, enforcement, and audit consumers react independently.
   - Tenant isolation is structural: topic names, audit rows, and metrics are all tenant-scoped.

6. **Telemetry enrichment and enforcement**
   - The **processor** enriches raw events with posture scoring and intent analysis.
   - The **policy decider** evaluates OPA rules and emits enforcement actions such as allow, escalate, or block.
   - The **Flink CEP** service adds behavioral analytics like burst detection, sustained-volume detection, and signal correlation for suspicious sessions.

7. **Stateful services and persistence**
   - **Redis** stores rate-limit counters and conversation memory with TTL-based namespaces.
   - **PostgreSQL** stores the SPM domain data: model registry, compliance evidence, posture snapshots, findings, and exported audit records.
   - Alembic migrations exist under the SPM service and the agent-orchestrator service, showing the database schema is a first-class part of the architecture.

8. **SPM control plane**
   - `spm-api` exposes the model registry, compliance reporting, posture queries, and model approval/freeze-related functionality.
   - `spm-aggregator` consumes Kafka events and materializes them into Postgres plus Prometheus metrics.
   - This plane is what drives the compliance dashboards and provides the authoritative record of approved models, posture history, and audit exports.

9. **Tooling and agentic execution**
   - The platform supports agentic tool use through `tool_parser`, `executor`, and related agent orchestration code.
   - Tool calls are not executed directly from the model: they are parsed, policy-checked, and often require approval before side-effecting actions run.
   - Tool results feed back into Kafka and the agent flow, which keeps tool execution observable and auditable.

10. **Autonomous threat hunting path**
   - The `threat-hunting-agent` is a separate autonomous scanner that does not depend on a user prompt.
   - It consumes Kafka session/events and also runs scheduled scans across Redis, Postgres, and host/runtime signals.
   - When it finds suspicious patterns, it posts structured threat findings into the `agent-orchestrator-service`, which deduplicates, prioritizes, and can open cases.

11. **Policy and governance layer**
   - OPA is the policy engine for prompt, output, tool, memory, model, and jailbreak-related controls.
   - The `policy-simulator` service lets you dry-run policy changes against sample events without affecting live traffic.
   - The `freeze-controller` is a governance override: it can suspend users or models in real time via Kafka control events.

12. **Observability and compliance**
   - Prometheus scrapes metrics from the services, and Grafana is pre-provisioned with engineering, compliance, and posture dashboards.
   - Compliance is mapped to **NIST AI RMF** functions, and threat behavior can be tagged with **MITRE ATLAS** techniques.
   - The audit trail is designed to be tamper-evident by writing to Kafka and mirroring into Postgres with idempotent export semantics.

13. **Startup and bootstrap**
   - `startup-orchestrator` is the bootstrap boundary for the whole stack.
   - On first boot it generates RSA keys for JWTs, creates Kafka topics, seeds OPA policies, and registers default models.
   - That means the platform is intended to self-provision locally without depending on an external identity or provisioning system.

14. **Shared code and configuration**
   - `platform_shared` contains cross-cutting primitives like config, Kafka helpers, security, policy explanation, risk scoring, and model/event schemas.
   - The repo also contains shared policy bundles under `opa/`, dashboard provisioning under `grafana/`, and Prometheus config under `prometheus/`.
   - Those directories are important architectural boundaries because they define platform-wide behavior rather than a single service.

Main entry points: [`services/api`](https://github.com/dshapi/ai-spm/tree/main/services/api) (API gateway), [`platform_shared/topics.py`](https://github.com/dshapi/ai-spm/blob/main/platform_shared/topics.py) (Kafka bus), [`opa/policies`](https://github.com/dshapi/ai-spm/tree/main/opa/policies) (OPA policies), [`spm/db`](https://github.com/dshapi/ai-spm/tree/main/spm/db) (Postgres)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_g_frontend["User apps"]
  node_ui_chat["Chat UI<br/>React/Vite SPA"]
  node_ui_admin["Admin portal<br/>React dashboard"]
  node_auth_overlay["Auth overlay<br/>Traefik+Keycloak"]
end

subgraph group_g_gateway["Interactive path"]
  node_api_gateway["API gateway"]
  node_memory_service[("Memory service<br/>Redis-backed memory")]
  node_guard_model["Guard model<br/>Moderation service"]
  node_retrieval_gateway["Retrieval gateway<br/>Tool/search gateway"]
  node_llm_service["LLM provider<br/>Anthropic-compatible LLM"]
  node_output_guard["Output guard<br/>Egress scanner"]
end

subgraph group_g_security["Policy plane"]
  node_processor["Processor<br/>Event enricher"]
  node_policy_decider["Policy decider<br/>OPA enforcement"]
  node_policy_simulator["Policy simulator<br/>Dry-run service"]
  node_freeze_controller["Freeze controller<br/>Governance override"]
  node_threat_hunter["Threat hunter<br/>Autonomous agent"]
end

subgraph group_g_spm["SPM plane"]
  node_agent_orchestrator["Agent orchestrator<br/>Case pipeline"]
  node_spm_api["SPM API<br/>FastAPI control plane"]
  node_spm_aggregator["SPM aggregator<br/>Kafka consumer"]
end

subgraph group_g_platform["Platform layer"]
  node_startup_orchestrator["Startup orchestrator<br/>Bootstrap service"]
  node_kafka_bus[("Kafka bus<br/>Event backbone<br/>[topics.py]")]
  node_postgres_db[("Postgres<br/>System of record")]
  node_redis_cache[("Redis<br/>TTL state")]
  node_platform_shared["Shared core<br/>Common libraries"]
  node_opa_policies["OPA policies<br/>Policy bundle"]
  node_grafana_dashboards["Grafana dashboards<br/>Observability assets"]
end

node_ui_chat -->|"prompts"| node_api_gateway
node_ui_admin -->|"control views"| node_spm_api
node_auth_overlay -->|"protects"| node_ui_admin
node_api_gateway -->|"lookup"| node_memory_service
node_api_gateway -->|"moderates"| node_guard_model
node_api_gateway -->|"policy check"| node_policy_decider
node_api_gateway -->|"search/fetch"| node_retrieval_gateway
node_api_gateway -->|"generate"| node_llm_service
node_api_gateway -->|"egress scan"| node_output_guard
node_api_gateway -->|"emit events"| node_kafka_bus
node_processor -->|"consume/emit"| node_kafka_bus
node_policy_decider -->|"decisions"| node_kafka_bus
node_policy_simulator -->|"dry-run"| node_opa_policies
node_freeze_controller -->|"controls"| node_kafka_bus
node_threat_hunter -->|"consume"| node_kafka_bus
node_threat_hunter -->|"findings"| node_agent_orchestrator
node_agent_orchestrator -->|"persist"| node_postgres_db
node_agent_orchestrator -->|"publish"| node_kafka_bus
node_spm_api -->|"query/write"| node_postgres_db
node_spm_aggregator -->|"consume"| node_kafka_bus
node_spm_aggregator -->|"materialize"| node_postgres_db
node_startup_orchestrator -->|"seed topics"| node_kafka_bus
node_startup_orchestrator -->|"seed rules"| node_opa_policies
node_startup_orchestrator -->|"init data"| node_postgres_db
node_platform_shared -.->|"shared code"| node_api_gateway
node_platform_shared -.->|"shared code"| node_spm_api
node_platform_shared -.->|"shared code"| node_threat_hunter
node_opa_policies -->|"governs"| node_api_gateway
node_opa_policies -->|"governs"| node_policy_decider
node_grafana_dashboards -.->|"visualizes"| node_spm_aggregator

click node_ui_chat "https://github.com/dshapi/ai-spm/tree/main/ui/src"
click node_ui_admin "https://github.com/dshapi/ai-spm/tree/main/ui/src/admin"
click node_auth_overlay "https://github.com/dshapi/ai-spm/tree/main/auth"
click node_api_gateway "https://github.com/dshapi/ai-spm/tree/main/services/api"
click node_memory_service "https://github.com/dshapi/ai-spm/tree/main/services/memory_service"
click node_guard_model "https://github.com/dshapi/ai-spm/tree/main/services/guard_model"
click node_retrieval_gateway "https://github.com/dshapi/ai-spm/tree/main/services/retrieval_gateway"
click node_llm_service "https://github.com/dshapi/ai-spm/tree/main/services/llm"
click node_output_guard "https://github.com/dshapi/ai-spm/tree/main/services/output_guard"
click node_processor "https://github.com/dshapi/ai-spm/tree/main/services/processor"
click node_policy_decider "https://github.com/dshapi/ai-spm/tree/main/services/policy_decider"
click node_policy_simulator "https://github.com/dshapi/ai-spm/tree/main/services/policy_simulator"
click node_freeze_controller "https://github.com/dshapi/ai-spm/tree/main/services/freeze_controller"
click node_threat_hunter "https://github.com/dshapi/ai-spm/tree/main/services/threat-hunting-agent"
click node_agent_orchestrator "https://github.com/dshapi/ai-spm/tree/main/services/agent-orchestrator-service"
click node_spm_api "https://github.com/dshapi/ai-spm/tree/main/services/spm_api"
click node_spm_aggregator "https://github.com/dshapi/ai-spm/tree/main/services/spm_aggregator"
click node_startup_orchestrator "https://github.com/dshapi/ai-spm/tree/main/services/startup_orchestrator"
click node_kafka_bus "https://github.com/dshapi/ai-spm/blob/main/platform_shared/topics.py"
click node_postgres_db "https://github.com/dshapi/ai-spm/tree/main/spm/db"
click node_redis_cache "https://github.com/dshapi/ai-spm/tree/main/services/memory_service"
click node_platform_shared "https://github.com/dshapi/ai-spm/tree/main/platform_shared"
click node_opa_policies "https://github.com/dshapi/ai-spm/tree/main/opa/policies"
click node_grafana_dashboards "https://github.com/dshapi/ai-spm/tree/main/grafana/dashboards"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_ui_chat,node_ui_admin,node_auth_overlay toneBlue
class node_api_gateway,node_memory_service,node_guard_model,node_retrieval_gateway,node_llm_service,node_output_guard toneAmber
class node_processor,node_policy_decider,node_policy_simulator,node_freeze_controller,node_threat_hunter toneMint
class node_agent_orchestrator,node_spm_api,node_spm_aggregator toneRose
class node_startup_orchestrator,node_kafka_bus,node_postgres_db,node_redis_cache,node_platform_shared,node_opa_policies,node_grafana_dashboards toneIndigo
```

## Components

### User apps

Human-facing chat and admin interfaces.

- [Chat UI](https://github.com/dshapi/ai-spm/tree/main/ui/src): React/Vite SPA · Orbyx chat interface for user prompts and session views. · `ui/src`
- [Admin portal](https://github.com/dshapi/ai-spm/tree/main/ui/src/admin): React dashboard · Posture, inventory, cases, policies, simulation, and analytics views. · `ui/src/admin`
- [Auth overlay](https://github.com/dshapi/ai-spm/tree/main/auth): Traefik+Keycloak · Optional local SSO front door for the admin UI. · `auth`

### Interactive path

Prompt intake, safety checks, retrieval, and tool execution.

- [API gateway](https://github.com/dshapi/ai-spm/tree/main/services/api): FastAPI gateway · Main interactive entrypoint for prompts, auth, rate limiting, screening, memory, and response safety. · `services/api`
- [Memory service](https://github.com/dshapi/ai-spm/tree/main/services/memory_service): Redis-backed memory · Conversation memory and injection-aware context screening. · `services/memory_service`
- [Guard model](https://github.com/dshapi/ai-spm/tree/main/services/guard_model): Moderation service · Content moderation and safety classification for prompts and events. · `services/guard_model`
- [Retrieval gateway](https://github.com/dshapi/ai-spm/tree/main/services/retrieval_gateway): Tool/search gateway · Retrieval and web-search/fetch boundary used by the prompt path. · `services/retrieval_gateway`
- [LLM provider](https://github.com/dshapi/ai-spm/tree/main/services/llm): Anthropic-compatible LLM · External model endpoint used for generation. · `services/llm`
- [Output guard](https://github.com/dshapi/ai-spm/tree/main/services/output_guard): Egress scanner · Second-pass scanning for secrets, PII, and unsafe output. · `services/output_guard`

### Policy plane

Policy, enforcement, and autonomous threat hunting.

- [Processor](https://github.com/dshapi/ai-spm/tree/main/services/processor): Event enricher · Adds posture scoring and intent analysis to raw events. · `services/processor`
- [Policy decider](https://github.com/dshapi/ai-spm/tree/main/services/policy_decider): OPA enforcement · Evaluates rules and emits allow, escalate, or block decisions. · `services/policy_decider`
- [Policy simulator](https://github.com/dshapi/ai-spm/tree/main/services/policy_simulator): Dry-run service · Tests policy changes against sample events without impacting live traffic. · `services/policy_simulator`
- [Freeze controller](https://github.com/dshapi/ai-spm/tree/main/services/freeze_controller): Governance override · Real-time suspension of users or models via control events. · `services/freeze_controller`
- [Threat hunter](https://github.com/dshapi/ai-spm/tree/main/services/threat-hunting-agent): Autonomous agent · Scheduled and event-driven scanner for suspicious sessions and runtime signals. · `services/threat-hunting-agent`

### SPM plane

Compliance, posture, registry, and audit materialization.

- [Agent orchestrator](https://github.com/dshapi/ai-spm/tree/main/services/agent-orchestrator-service): Case pipeline · Deduplicates, prioritizes, and routes findings into cases and results. · `services/agent-orchestrator-service`
- [SPM API](https://github.com/dshapi/ai-spm/tree/main/services/spm_api): FastAPI control plane · Model registry, posture queries, compliance reports, approvals, and freezes. · `services/spm_api`
- [SPM aggregator](https://github.com/dshapi/ai-spm/tree/main/services/spm_aggregator): Kafka consumer · Materializes telemetry into Postgres and Prometheus metrics. · `services/spm_aggregator`

### Platform layer

Shared libraries, storage, messaging, and bootstrap.

- [Startup orchestrator](https://github.com/dshapi/ai-spm/tree/main/services/startup_orchestrator): Bootstrap service · Seeds keys, topics, policies, and default models on first boot. · `services/startup_orchestrator`
- [Kafka bus](https://github.com/dshapi/ai-spm/blob/main/platform_shared/topics.py): Event backbone · Tenant-scoped async bus for events, decisions, approvals, audit, and tool data. · `platform_shared/topics.py`
- [Postgres](https://github.com/dshapi/ai-spm/tree/main/spm/db): System of record · Stores SPM domain data, findings, posture snapshots, and audit exports. · `spm/db`
- [Redis](https://github.com/dshapi/ai-spm/tree/main/services/memory_service): TTL state · Holds rate-limit counters and conversation memory namespaces. · `services/memory_service`
- [Shared core](https://github.com/dshapi/ai-spm/tree/main/platform_shared): Common libraries · Config, Kafka helpers, security, policy explanation, risk scoring, and schemas. · `platform_shared`
- [OPA policies](https://github.com/dshapi/ai-spm/tree/main/opa/policies): Policy bundle · Shared policy rules for prompts, outputs, tools, memory, model, PII, and jailbreak control. · `opa/policies`
- [Grafana dashboards](https://github.com/dshapi/ai-spm/tree/main/grafana/dashboards): Observability assets · Engineering and compliance dashboards provisioned with shared datasources. · `grafana/dashboards`

## Connections

- Chat UI → API gateway: prompts · Chat sessions send user messages into the gateway.
- Admin portal → SPM API: control views · Admin portal reads posture, registry, and compliance views.
- Auth overlay → Admin portal: protects · Optional SSO overlay in front of the admin portal.
- API gateway → Memory service: lookup · Retrieves and screens conversation memory.
- API gateway → Guard model: moderates · Runs prompt safety classification.
- API gateway → Policy decider: policy check · Sends context for prompt and tool authorization decisions.
- API gateway → Retrieval gateway: search/fetch · Routes retrieval and web-search tool calls.
- API gateway → LLM provider: generate · Calls the external model provider for completion.
- API gateway → Output guard: egress scan · Applies output safety before returning a response.
- API gateway → Kafka bus: emit events · Publishes session, decision, and audit events to Kafka.
- Processor → Kafka bus: consume/emit · Consumes raw events and publishes enriched telemetry.
- Policy decider → Kafka bus: decisions · Writes allow, escalate, and block actions to the bus.
- Policy simulator → OPA policies: dry-run · Evaluates candidate rules against sample events.
- Freeze controller → Kafka bus: controls · Broadcasts suspension and freeze events.
- Threat hunter → Kafka bus: consume · Scans session and event streams for suspicious activity.
- Threat hunter → Agent orchestrator: findings · Submits structured threat findings for triage.
- Agent orchestrator → Postgres: persist · Stores findings, cases, sessions, policies, and audit-linked records.
- Agent orchestrator → Kafka bus: publish · Emits events for downstream consumers and auditability.
- SPM API → Postgres: query/write · Reads and updates authoritative SPM state.
- SPM aggregator → Kafka bus: consume · Materializes tenant-scoped telemetry from the event bus.
- SPM aggregator → Postgres: materialize · Writes compliance and posture aggregates to Postgres.
- Startup orchestrator → Kafka bus: seed topics · Creates the tenant-scoped topics used by the platform.
- Startup orchestrator → OPA policies: seed rules · Bootstraps default policy bundles.
- Startup orchestrator → Postgres: init data · Registers baseline models and platform records.
- Shared core → API gateway: shared code · Common security, config, and Kafka primitives.
- Shared core → SPM API: shared code · Shared schemas and helpers used across the control plane.
- Shared core → Threat hunter: shared code · Shared risk, trust, and policy utilities.
- OPA policies → API gateway: governs · Policy bundles inform prompt, output, tool, and memory checks.
- OPA policies → Policy decider: governs · OPA rules drive enforcement decisions.
- Grafana dashboards → SPM aggregator: visualizes · Dashboards consume the metrics materialized by the aggregator.
