Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(ai-estate): aisoc_ai_assets table, model, routes and the fusion recorder that writes it
Beenu Arora951de158757a
diff --git a/services/api/app/api/v1/endpoints/ai_assets.py b/services/api/app/api/v1/endpoints/ai_assets.pynew file mode 100644index 000000000..64a6878a9--- /dev/null+++ b/services/api/app/api/v1/endpoints/ai_assets.py@@ -0,0 +1,221 @@+"""Read the observed AI estate, and record an operator's judgement about it.++Depth plan 6.1.++Three routes: list, one asset, and a sanction decision. The list is what the+console page renders; the sanction route is the only write, and it writes one+tri-state field.++Why reads require a permission here when most reads in this service do not+--------------------------------------------------------------------------+This inventory names which coding agent on which laptop belongs to which+person and which provider key it holds. That is a target list, and a session+that can read alerts should not automatically get it. ``ai_estate:read`` is+held by the five working roles; ``ai_estate:write`` by the two that govern.++Why there is no create route+----------------------------+Rows arrive from observation — the fusion recorder writes them from AI+runtime, endpoint and provider-audit telemetry. A create route would let the+inventory be populated by hand, and an inventory a human can type into stops+answering the question it exists to answer, which is "what is running that+nobody told us about". The declaration surface already exists and is+``/api/v1/mcp-servers``.+"""++from __future__ import annotations++import uuid+from typing import Annotated, Any++import structlog+from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel, Field+from sqlalchemy import select, update++from app.api.v1.deps import CurrentUser, require_permission+from app.db.rls import TenantDBSession+from app.models.ai_asset import AI_ASSET_KINDS, AiAsset+from app.services.ai_inventory import score_risk++logger = structlog.get_logger()++router = APIRouter(prefix="/ai-assets", tags=["ai-estate"])++_MAX_PAGE = 200+++class AiAssetModel(BaseModel):+ """One asset as the console sees it."""++ id: str+ kind: str+ externalId: str+ displayName: str | None = None+ vendor: str | None = None+ discoverySource: str+ # Null means "not learned", and the console must render that differently+ # from a blank: an asset nobody is accountable for is the finding.+ principal: str | None = None+ device: str | None = None+ effectivePermissions: dict[str, Any] | None = None+ attributes: dict[str, Any] = Field(default_factory=dict)+ risk: int+ riskReasons: list[str] = Field(default_factory=list)+ sanctioned: bool | None = None+ firstSeen: str+ lastSeen: str+ observationCount: int+++class AiAssetListResponse(BaseModel):+ items: list[AiAssetModel]+ total: int+ # Stated rather than inferred from an empty list. A tenant with no AI+ # telemetry and a tenant whose AI estate is genuinely empty look+ # identical in the rows, and only one of them is a reason to go looking.+ observedSources: list[str] = Field(default_factory=list)+++class SanctionRequest(BaseModel):+ sanctioned: bool | None = Field(+ ...,+ description="true = approved, false = reviewed and refused, null = back to undecided. The three are distinct.",+ )+ note: str | None = Field(None, max_length=500)+++def _to_model(row: AiAsset) -> AiAssetModel:+ return AiAssetModel(+ id=str(row.id),+ kind=row.kind,+ externalId=row.external_id,+ displayName=row.display_name,+ vendor=row.vendor,+ discoverySource=row.discovery_source,+ principal=row.principal,+ device=row.device,+ effectivePermissions=row.effective_permissions,+ attributes=row.attributes or {},+ risk=row.risk_score,+ riskReasons=list(row.risk_reasons or []),+ sanctioned=row.sanctioned,+ firstSeen=row.first_seen_at.isoformat(),+ lastSeen=row.last_seen_at.isoformat(),+ observationCount=row.observation_count,+ )++[email protected]("", response_model=AiAssetListResponse)+async def list_ai_assets(+ db: TenantDBSession,+ current_user: Annotated[CurrentUser, Depends(require_permission("ai_estate:read"))],+ kind: Annotated[str | None, Query(description="Filter to one asset kind.")] = None,+ unlinked: Annotated[bool, Query(description="Only assets with no person linked.")] = False,+ limit: Annotated[int, Query(ge=1, le=_MAX_PAGE)] = 50,+ offset: Annotated[int, Query(ge=0)] = 0,+) -> AiAssetListResponse:+ """The estate, newest sighting first."""+ if kind is not None and kind not in AI_ASSET_KINDS:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"Unknown kind {kind!r}. Known kinds: {', '.join(AI_ASSET_KINDS)}.",+ )++ stmt = select(AiAsset).where(AiAsset.tenant_id == current_user.tenant_id)+ if kind is not None:+ stmt = stmt.where(AiAsset.kind == kind)+ if unlinked:+ stmt = stmt.where(AiAsset.principal.is_(None))++ rows = (await db.execute(stmt.order_by(AiAsset.last_seen_at.desc()).limit(limit).offset(offset))).scalars().all()++ # Counted independently of the page rather than from len(rows), which+ # would report the page size as the total on every page but the last.+ count_stmt = select(AiAsset.id).where(AiAsset.tenant_id == current_user.tenant_id)+ if kind is not None:+ count_stmt = count_stmt.where(AiAsset.kind == kind)+ if unlinked:+ count_stmt = count_stmt.where(AiAsset.principal.is_(None))+ total = len((await db.execute(count_stmt)).scalars().all())++ sources = sorted(+ {+ s+ for s in (+ await db.execute(select(AiAsset.discovery_source).where(AiAsset.tenant_id == current_user.tenant_id).distinct())+ )+ .scalars()+ .all()+ }+ )++ return AiAssetListResponse(items=[_to_model(r) for r in rows], total=total, observedSources=sources)++[email protected]("/{asset_id}", response_model=AiAssetModel)+async def get_ai_asset(+ asset_id: uuid.UUID,+ db: TenantDBSession,+ current_user: Annotated[CurrentUser, Depends(require_permission("ai_estate:read"))],+) -> AiAssetModel:+ row = (+ await db.execute(select(AiAsset).where(AiAsset.id == asset_id, AiAsset.tenant_id == current_user.tenant_id))+ ).scalar_one_or_none()+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="AI asset not found")+ return _to_model(row)++[email protected]("/{asset_id}/sanction", response_model=AiAssetModel)+async def sanction_ai_asset(+ asset_id: uuid.UUID,+ payload: SanctionRequest,+ db: TenantDBSession,+ current_user: Annotated[CurrentUser, Depends(require_permission("ai_estate:write"))],+) -> AiAssetModel:+ """Approve an asset, refuse it, or put it back to undecided.++ The risk score is recomputed here rather than left stale, through the+ same `score_risk` the recorder calls, because the sanction decision is+ one of its inputs: an asset that has just been refused and is still+ running is a different exposure from one nobody had looked at.+ """+ row = (+ await db.execute(select(AiAsset).where(AiAsset.id == asset_id, AiAsset.tenant_id == current_user.tenant_id))+ ).scalar_one_or_none()+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="AI asset not found")++ score, reasons = score_risk(+ kind=row.kind,+ principal=row.principal,+ device=row.device,+ sanctioned=payload.sanctioned,+ attributes=row.attributes or {},+ effective_permissions=row.effective_permissions,+ )+ attributes = dict(row.attributes or {})+ if payload.note:+ attributes["sanction_note"] = payload.note++ await db.execute(+ update(AiAsset)+ .where(AiAsset.id == asset_id, AiAsset.tenant_id == current_user.tenant_id)+ .values(sanctioned=payload.sanctioned, risk_score=score, risk_reasons=reasons, attributes=attributes)+ )+ await db.commit()++ logger.info(+ "ai_asset.sanctioned",+ asset_id=str(asset_id),+ kind=row.kind,+ sanctioned=payload.sanctioned,+ actor=str(current_user.user_id),+ )++ row.sanctioned = payload.sanctioned+ row.risk_score = score+ row.risk_reasons = reasons+ row.attributes = attributes+ return _to_model(row)diff --git a/services/api/app/api/v1/endpoints/api_keys.py b/services/api/app/api/v1/endpoints/api_keys.pyindex 758ed74b6..ae9edc08a 100644--- a/services/api/app/api/v1/endpoints/api_keys.py+++ b/services/api/app/api/v1/endpoints/api_keys.py@@ -87,6 +87,12 @@ VALID_SCOPES: frozenset[str] = frozenset("elevation:read","elevation:request","elevation:approve",+ # Depth 6.1. Mintable so a tenant can pull its own AI-estate+ # inventory into a CMDB or a governance report without a wildcard+ # key. Listed here widens nothing by itself: the grant check below+ # still refuses a scope the minter does not hold.+ "ai_estate:read",+ "ai_estate:write","access_conditions:read","access_conditions:write","workload_identities:read",diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex 5cadb3d76..a1b902b06 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -7,6 +7,7 @@ from app.api.v1.endpoints import (admin_users,agent_tools,agents,+ ai_assets,airgap,alert_explain,alert_writeback,@@ -162,6 +163,10 @@ api_router.include_router(plugins.router)api_router.include_router(community.router)api_router.include_router(marketplace.router)api_router.include_router(mcp_servers.router)+# Depth 6.1: the observed AI estate. `mcp_servers` above is what an operator+# declared; this is what AiSOC saw running, and the interesting row is the+# one present in the second and absent from the first.+api_router.include_router(ai_assets.router)# Gap-closure Phase 6.1 and 6.2: tenant-authored investigation skills:# authored in YAML, validated against the tools this tenant's agent can# actually call, backtested through the Phase 1 replay with and without thediff --git a/services/api/app/core/security.py b/services/api/app/core/security.pyindex b413fe8a1..3e94bd3e0 100644--- a/services/api/app/core/security.py+++ b/services/api/app/core/security.py@@ -102,6 +102,14 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {"elevation:read","elevation:request","elevation:approve",+ # Depth 6.1. The AI-estate inventory names which coding agent on+ # which laptop belongs to which person and which provider key it+ # holds. That is a target list, so it is a permission of its own+ # rather than riding on alerts:read.+ "ai_estate:read",+ # Approving or refusing an observed AI asset is a governance+ # decision, so it sits with the roles that govern.+ "ai_estate:write","access_conditions:read","access_conditions:write",],@@ -139,6 +147,14 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# the role the separation-of-duties rule assumes exists."elevation:read","elevation:request",+ # Depth 6.1. The AI-estate inventory names which coding agent on+ # which laptop belongs to which person and which provider key it+ # holds. That is a target list, so it is a permission of its own+ # rather than riding on alerts:read.+ "ai_estate:read",+ # Approving or refusing an observed AI asset is a governance+ # decision, so it sits with the roles that govern.+ "ai_estate:write","elevation:approve","access_conditions:read",],@@ -168,6 +184,11 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# tenant's own knowledge base, so every role that can read an# alert can read it."knowledge_base:read",+ # Depth 6.1. The AI-estate inventory names which coding agent on+ # which laptop belongs to which person and which provider key it+ # holds. That is a target list, so it is a permission of its own+ # rather than riding on alerts:read.+ "ai_estate:read",# Request, never approve. The analyst asking to isolate a host is# not the person who should decide they may."elevation:request",@@ -196,6 +217,11 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# tenant's own knowledge base, so every role that can read an# alert can read it."knowledge_base:read",+ # Depth 6.1. The AI-estate inventory names which coding agent on+ # which laptop belongs to which person and which provider key it+ # holds. That is a target list, so it is a permission of its own+ # rather than riding on alerts:read.+ "ai_estate:read","elevation:request",],"viewer": [diff --git a/services/api/app/models/__init__.py b/services/api/app/models/__init__.pyindex 888ca5323..dd2c575aa 100644--- a/services/api/app/models/__init__.py+++ b/services/api/app/models/__init__.py@@ -1,6 +1,7 @@"""ORM models package - imports all models for Alembic and SQLAlchemy."""from app.db.database import Base+from app.models.ai_asset import AiAssetfrom app.models.alert import Alertfrom app.models.asset import AlertAssetCorrelation, Asset, AssetVulnerabilityfrom app.models.branding import OrgBrandAsset, OrgBranding@@ -102,6 +103,7 @@ __all__ = ["TenantInboxToken","TenantLlmCredential","McpServer",+ "AiAsset","PasskeyCredential","PasskeyChallenge","OnCallStatus",diff --git a/services/api/app/models/ai_asset.py b/services/api/app/models/ai_asset.pynew file mode 100644index 000000000..0e04a9722--- /dev/null+++ b/services/api/app/models/ai_asset.py@@ -0,0 +1,89 @@+"""Observed AI estate: one row per AI asset a tenant actually runs.++Depth plan 6.1. Backs ``/api/v1/ai-assets`` and migration+``105_ai_assets.sql``; the migration header carries the reasoning for each+column and is the thing to read first.++The distinction worth repeating here, because it is what makes the table+useful: ``aisoc_mcp_servers`` is what an operator *declared*, this is what+AiSOC *observed*. The row that matters is the one present here and absent+there.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Integer, Text+from sqlalchemy.dialects.postgresql import JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base++#: The six kinds depth plan 6.1 names. Mirrored by the CHECK constraint in+#: the migration, so a seventh value fails at the write rather than appearing+#: as an unfilterable row in the console.+AI_ASSET_KINDS: tuple[str, ...] = (+ "ai_app",+ "coding_agent",+ "mcp_server",+ "ide_extension",+ "provider_key",+ "oauth_grant",+)++#: Which discovery path produced a row. Carried rather than inferred because+#: the three sources see genuinely different things, and an analyst reading an+#: unlinked asset needs to know whether the link is missing or unknowable:+#: runtime telemetry knows the model and never the device, endpoint discovery+#: knows the device and never the model.+AI_ASSET_SOURCES: tuple[str, ...] = (+ "ai_runtime",+ "endpoint",+ "provider_audit",+ "oauth_audit",+ "declared",+)+++class AiAsset(Base):+ """One observed AI asset, with the person and device behind it."""++ __tablename__ = "aisoc_ai_assets"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("tenants.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )++ kind: Mapped[str] = mapped_column(Text, nullable=False)+ external_id: Mapped[str] = mapped_column(Text, nullable=False)+ display_name: Mapped[str | None] = mapped_column(Text, nullable=True)+ vendor: Mapped[str | None] = mapped_column(Text, nullable=True)+ discovery_source: Mapped[str] = mapped_column(Text, nullable=False)++ # NULL means "not learned", never "none". The console renders the two+ # differently and the difference is the finding.+ principal: Mapped[str | None] = mapped_column(Text, nullable=True)+ device: Mapped[str | None] = mapped_column(Text, nullable=True)+ effective_permissions: Mapped[dict | None] = mapped_column(JSONB, nullable=True)++ attributes: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)++ risk_score: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ risk_reasons: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)++ # Tri-state on purpose: NULL is "nobody has decided", which is not the+ # same as reviewed and refused.+ sanctioned: Mapped[bool | None] = mapped_column(Boolean, nullable=True)++ first_seen_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))+ last_seen_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))+ observation_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=1)++ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))diff --git a/services/api/app/services/ai_inventory.py b/services/api/app/services/ai_inventory.pynew file mode 100644index 000000000..1d68aec9a--- /dev/null+++ b/services/api/app/services/ai_inventory.py@@ -0,0 +1,169 @@+"""Risk scoring and reads for the observed AI estate.++Depth plan 6.1.++One home for the number+-----------------------+``score_risk`` is the only place a risk score is computed. The fusion+recorder calls it on write and stores the result; the console reads the+stored value. Nothing recomputes it in a query. That is deliberate: this+repository has already shipped two surfaces disagreeing about the same rows+because each owned its own SQL expression for a figure, and the way they+disagreed — one averaging over a column nothing writes — was invisible until+somebody compared them by hand.++What the score is, and what it is not+-------------------------------------+It is an **exposure** score, not a verdict. It answers "how much could this+asset reach, and how little do we know about it", which is the question an+inventory can answer from what it has. It does not claim the asset is+malicious; that is what the detections in 6.5 are for, and they read the same+rows.++Every component below adds a *reason string* alongside its points, so the+console shows why rather than a bare number and a reviewer can disagree with+a sentence. A score with no reasons would be the kind of figure nobody can+act on and nobody can refute.+"""++from __future__ import annotations++from typing import Any++#: Points per signal. Capped at 100 by `score_risk`, which also means adding a+#: new signal cannot silently rescale the existing ones.+_POINTS = {+ "unlinked_principal": 15,+ "unlinked_device": 10,+ "undeclared": 20,+ "refused": 30,+ "privileged_permissions": 25,+ "prompts_disabled": 25,+ "unvetted_source": 20,+ "secret_in_prompt": 20,+ "high_risk_tool": 15,+ "broad_oauth_scope": 25,+}++#: OAuth scopes that let an AI application read or alter a mailbox, a drive or+#: a repository wholesale. Each is a real scope string from the provider's own+#: reference, not a category we invented: an AI note-taker with+#: ``https://mail.google.com/`` can read every message the grantee can.+BROAD_OAUTH_SCOPES: frozenset[str] = frozenset(+ {+ "https://mail.google.com/",+ "https://www.googleapis.com/auth/drive",+ "https://www.googleapis.com/auth/gmail.modify",+ "https://www.googleapis.com/auth/admin.directory.user",+ "Mail.ReadWrite",+ "Mail.Read",+ "Files.ReadWrite.All",+ "Sites.ReadWrite.All",+ "Directory.ReadWrite.All",+ "repo",+ "admin:org",+ }+)++#: Tool names whose effect is a change to an estate rather than a read. An+#: agent that has called one of these is a different asset from one that has+#: only ever searched.+HIGH_RISK_TOOLS: frozenset[str] = frozenset(+ {+ "execute_command",+ "run_shell",+ "write_file",+ "delete_file",+ "send_email",+ "create_user",+ "grant_permission",+ "deploy",+ "terraform_apply",+ "database_write",+ }+)+++def score_risk(+ *,+ kind: str,+ principal: str | None,+ device: str | None,+ sanctioned: bool | None,+ attributes: dict[str, Any] | None,+ effective_permissions: dict[str, Any] | None,+) -> tuple[int, list[str]]:+ """Return ``(score, reasons)`` for one asset.++ ``sanctioned`` is tri-state and each state scores differently, which is+ the part that is easy to get wrong: ``None`` means nobody has looked+ (a modest amount of risk, because an unreviewed asset is unmanaged),+ ``False`` means somebody looked and said no (a lot, because it is running+ anyway), and ``True`` means approved (nothing).+ """+ attributes = attributes or {}+ reasons: list[str] = []+ score = 0++ if not principal:+ score += _POINTS["unlinked_principal"]+ reasons.append("No person is linked: nobody is accountable for what it does.")+ if not device and kind in {"coding_agent", "ide_extension", "mcp_server"}:+ score += _POINTS["unlinked_device"]+ reasons.append("No device is linked, so containment has nowhere to act.")++ if sanctioned is False:+ score += _POINTS["refused"]+ reasons.append("Reviewed and refused, and still running.")+ elif sanctioned is None:+ score += _POINTS["undeclared"]+ reasons.append("Not declared in the inventory: nobody has reviewed it.")++ if attributes.get("permission_prompts_disabled"):+ score += _POINTS["prompts_disabled"]+ reasons.append("Started with its permission prompts disabled, so a human confirms nothing.")++ source = str(attributes.get("install_source") or "")+ if source and source not in {"official", "vendor", "internal"}:+ score += _POINTS["unvetted_source"]+ reasons.append(f"Installed from an unvetted source ({source}).")++ secret_kinds = attributes.get("prompt_secret_kinds") or []+ if secret_kinds:+ score += _POINTS["secret_in_prompt"]+ kinds = ", ".join(sorted(str(k) for k in secret_kinds)[:3])+ reasons.append(f"Credential material has appeared in its prompts ({kinds}).")++ tools = {str(t) for t in (attributes.get("tools") or [])}+ risky = sorted(tools & HIGH_RISK_TOOLS)+ if risky:+ score += _POINTS["high_risk_tool"]+ reasons.append(f"Calls tools that change an estate ({', '.join(risky[:3])}).")++ scopes = {str(s) for s in (attributes.get("scopes") or [])}+ broad = sorted(scopes & BROAD_OAUTH_SCOPES)+ if broad:+ score += _POINTS["broad_oauth_scope"]+ reasons.append(f"Holds an OAuth scope covering a whole mailbox, drive or org ({broad[0]}).")++ if _is_privileged(effective_permissions):+ score += _POINTS["privileged_permissions"]+ reasons.append("The linked principal holds administrative permissions.")++ return min(score, 100), reasons+++def _is_privileged(effective_permissions: dict[str, Any] | None) -> bool:+ """Whether the Phase 2.5 snapshot says the principal is administrative.++ Reads the resolver's own output shape rather than guessing at a provider+ format. Returns ``False`` for ``None``, which is the honest answer when+ no snapshot was collected — scoring an unknown as privileged would make+ every asset on a deployment without posture collection look severe.+ """+ if not effective_permissions:+ return False+ if effective_permissions.get("is_admin") is True:+ return True+ roles = effective_permissions.get("admin_roles") or []+ return bool(roles)diff --git a/services/api/migrations/105_ai_assets.sql b/services/api/migrations/105_ai_assets.sqlnew file mode 100644index 000000000..b784db118--- /dev/null+++ b/services/api/migrations/105_ai_assets.sql@@ -0,0 +1,168 @@+-- 105: the AI estate a tenant actually runs, as opposed to the one it registered.+--+-- Depth plan 6.1.+--+-- `aisoc_mcp_servers` (069) is a *declaration*: the MCP servers an operator+-- chose to trust. This table is an *observation*: every AI app, coding agent,+-- MCP server, IDE extension, provider key and OAuth grant AiSOC has seen,+-- whether or not anybody declared it. The two have to be separate, because+-- the interesting row is the one in this table and not in that one — the+-- coding agent nobody registered, running on a laptop, holding a key.+--+-- Why one table with a `kind` rather than six tables+-- --------------------------------------------------+-- Every question an analyst asks of this data is asked across the kinds, not+-- within one: what does this person run, what runs on this device, what has+-- appeared since Friday. Six tables would make each of those a six-way union+-- and would let the columns drift apart. The kinds differ in what identifies+-- them, which is `external_id`, and in what they carry, which is `attributes`.+--+-- Why `first_seen_at` and `last_seen_at` are columns and not derived+-- ------------------------------------------------------------------+-- Derived from the lake they would be a scan over every AI event ever+-- archived, per row, per page load. They are also the two fields the page is+-- sorted and filtered by. The recorder maintains them with `LEAST`/`GREATEST`+-- on conflict so a late-arriving event cannot move `first_seen_at` forward.+--+-- Why the person, the device and the permissions are nullable+-- -----------------------------------------------------------+-- Because the source often does not know. A gateway log names the agent and+-- the model and nothing about the laptop; an osquery row names the device and+-- the process and nothing about the provider account. Writing an empty string+-- or a placeholder would make "we did not learn this" indistinguishable from+-- "there is nobody", and the console renders the two differently: an unlinked+-- asset is a finding, not a blank cell.+--+-- `effective_permissions` holds what Phase 2.5's resolver returned for the+-- linked principal at the time of the last sighting, as a snapshot rather+-- than a join. A join would re-resolve on every read and would silently+-- change history; a snapshot answers "what could this agent reach when we+-- last saw it", which is the question an incident asks.+--+-- Why `risk_score` is stored rather than computed in the query+-- ------------------------------------------------------------+-- It is computed by one function (`app/services/ai_inventory.py::score_risk`)+-- on write, so the console, the API and any future detection all read the+-- same number. Two surfaces computing a risk two ways is how `mttr_hours` and+-- `cases_closed_7d` came to disagree about the same rows.++CREATE TABLE IF NOT EXISTS aisoc_ai_assets (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,++ -- The six kinds the plan names. Constrained in the database because a+ -- seventh value arriving from a new discovery source should fail loudly+ -- at the write rather than appear as an unfilterable row in the console.+ kind TEXT NOT NULL CHECK (kind IN (+ 'ai_app',+ 'coding_agent',+ 'mcp_server',+ 'ide_extension',+ 'provider_key',+ 'oauth_grant'+ )),++ -- Stable within (tenant, kind): the agent id from runtime telemetry, the+ -- process name plus device from endpoint discovery, the key id from a+ -- provider's audit log, the client id of an OAuth grant.+ external_id TEXT NOT NULL,+ display_name TEXT,+ vendor TEXT,++ -- Which discovery path produced this row. Carried because the three see+ -- different things and an analyst needs to know which one is talking:+ -- `ai_runtime` knows the model and the tools and not the device,+ -- `endpoint` knows the device and the binary and not the model,+ -- `provider_audit` knows the account and the key and neither.+ discovery_source TEXT NOT NULL CHECK (discovery_source IN (+ 'ai_runtime',+ 'endpoint',+ 'provider_audit',+ 'oauth_audit',+ 'declared'+ )),++ -- Links. NULL means "not learned", never "none" — see the header.+ principal TEXT,+ device TEXT,+ effective_permissions JSONB,++ -- Everything kind-specific: model, provider, tool names, extension+ -- version, scopes granted. Indexed as a whole rather than per key,+ -- because the shape differs per kind by design.+ attributes JSONB NOT NULL DEFAULT '{}'::jsonb,++ risk_score INTEGER NOT NULL DEFAULT 0 CHECK (risk_score BETWEEN 0 AND 100),+ -- Why the row scored what it scored, so the console can show it and a+ -- reviewer can disagree with a reason rather than with a number.+ risk_reasons JSONB NOT NULL DEFAULT '[]'::jsonb,++ -- An operator's judgement, independent of the score. `sanctioned` is the+ -- allowlist the shadow-AI detection reads; it defaults to NULL, meaning+ -- nobody has decided, which is different from "reviewed and refused".+ sanctioned BOOLEAN,++ first_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ observation_count BIGINT NOT NULL DEFAULT 1,++ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ -- The upsert key. A device is part of identity for the kinds where the+ -- same binary on two laptops is two assets (a coding agent, an IDE+ -- extension) and NULL for the kinds where it is one (a provider key).+ --+ -- NULLS NOT DISTINCT is load-bearing and is the whole reason this is a+ -- named constraint. Under the default, NULL never equals NULL, so every+ -- sighting of a provider key — which has no device — would insert a new+ -- row rather than update the one before it, and the inventory would grow+ -- one row per event while `first_seen_at` reset on each. The same+ -- mistake was made in 074 and is spelled the same way here. PostgreSQL+ -- 15 or later; the tree pins 16.+ CONSTRAINT aisoc_ai_assets_identity+ UNIQUE NULLS NOT DISTINCT (tenant_id, kind, external_id, device)+);++COMMENT ON TABLE aisoc_ai_assets IS+ 'Observed AI estate: apps, coding agents, MCP servers, IDE extensions, '+ 'provider keys and OAuth grants, with the person and device behind each. '+ 'Written by the fusion recorder from AI runtime, endpoint and provider '+ 'audit telemetry. Distinct from aisoc_mcp_servers, which is what an '+ 'operator declared rather than what is running.';+COMMENT ON COLUMN aisoc_ai_assets.principal IS+ 'The person the asset acted for, when a source said so. NULL means not '+ 'learned, never "nobody" — the console renders an unlinked asset as a '+ 'finding rather than a blank cell.';+COMMENT ON COLUMN aisoc_ai_assets.effective_permissions IS+ 'Snapshot of what the Phase 2.5 resolver returned for the linked '+ 'principal at the last sighting. A snapshot and not a join, so history '+ 'does not change under a later permission edit.';+COMMENT ON COLUMN aisoc_ai_assets.sanctioned IS+ 'Operator judgement. NULL means undecided, which is not the same as '+ 'reviewed-and-refused; the shadow-AI detection reads TRUE as an allowlist.';++CREATE INDEX IF NOT EXISTS idx_ai_assets_tenant_last_seen+ ON aisoc_ai_assets (tenant_id, last_seen_at DESC);+CREATE INDEX IF NOT EXISTS idx_ai_assets_tenant_kind+ ON aisoc_ai_assets (tenant_id, kind);+CREATE INDEX IF NOT EXISTS idx_ai_assets_tenant_principal+ ON aisoc_ai_assets (tenant_id, principal);++-- Row-level security. The `OR current_tenant_id() IS NULL` arm is what lets+-- the cross-tenant workers (retention purge, tenant deletion) reach this+-- table; dropping it makes those silently see nothing. FORCE so the table+-- owner, which is the role that runs migrations, does not walk past it.+ALTER TABLE aisoc_ai_assets ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_ai_assets FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_ai_assets_tenant ON aisoc_ai_assets;+CREATE POLICY aisoc_ai_assets_tenant ON aisoc_ai_assets+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_ai_assets TO aisoc_app;+ END IF;+END+$$;diff --git a/services/fusion/app/main.py b/services/fusion/app/main.pyindex 166586976..33a68cd64 100644--- a/services/fusion/app/main.py+++ b/services/fusion/app/main.py@@ -21,6 +21,7 @@ from app.services.deduplicator import Deduplicatorfrom app.services.detection_engine import DetectionEnginefrom app.services.dlq_sink import PostgresDLQfrom app.services.entity_risk import EntityRiskEngine+from app.services.ai_asset_recorder import AiAssetRecorderfrom app.services.first_seen import FirstSeenStorefrom app.services.fusion_engine import FusionEnginefrom app.services.ioc_match import TenantIocMatcher@@ -136,6 +137,14 @@ async def lifespan(app: FastAPI):# capture None and drop every dead letter.dlq = PostgresDLQ(lambda: sink._pool) if sink is not None else None+ # Depth 6.1 — the observed AI estate. Shares the alert sink's pool for+ # the same reason the dead-letter queue does: one Postgres connection+ # pool per service, opened by `sink.start()` during `worker.start()`.+ # Passed as a callable because that happens after this point, and+ # capturing `sink._pool` eagerly would capture None and silently drop+ # every sighting for the life of the process.+ ai_assets = AiAssetRecorder(lambda: sink._pool) if sink is not None else None+worker = FusionWorker(engine,sink=sink,@@ -150,6 +159,7 @@ async def lifespan(app: FastAPI):# in the console kept receiving its alerts.overlays=OverlayCache(_overlay_pool()),ueba_cache=ueba_cache,+ ai_assets=ai_assets,)set_worker(worker)diff --git a/services/fusion/app/services/ai_asset_recorder.py b/services/fusion/app/services/ai_asset_recorder.pynew file mode 100644index 000000000..29247d9c2--- /dev/null+++ b/services/fusion/app/services/ai_asset_recorder.py@@ -0,0 +1,566 @@+"""Build the observed AI estate out of the event stream.++Depth plan 6.1. This is the writer behind ``aisoc_ai_assets``, and it sits on+the fusion consumer's raw-events branch because that is the one path every+normalized event already travels on the default profile. A recorder behind a+flag, or in a service CORE does not start, is a table nothing writes and a+console page that renders "no AI estate" to a tenant that has one.++What it reads+-------------+Three shapes, each identified by what the ingest normalizer stamped on it+rather than by guessing from field presence:++* ``ai-runtime`` and ``ai-finding`` — the SDK and gateway telemetry. These+ name the agent, the model, the MCP server and the human it acted for.+* ``llm_usage`` provider audit events — these name a provider key and the+ account that minted it, and nothing about any device.+* OCSF Process Activity (class 1007) carrying a known coding-agent or MCP+ server binary — these name the device and the binary, and nothing about+ the model. Depth 6.2 widens this set; the hook is here so the two items do+ not have to touch the same file twice.++Each row records which of the three saw it, because an analyst reading an+asset with no device needs to know whether the link is missing or whether+that source could never have supplied it.++Why it buffers+--------------+A busy agent emits a span per tool call. Upserting per span would put a+write on the hot path of every AI event in the deployment to update a+``last_seen_at`` that nobody reads at that resolution. Sightings coalesce in+memory by identity and flush on size or age, the same shape the lake writer+uses, so one row is written per asset per flush interval however chatty the+agent is.++Fail-soft, in one direction+---------------------------+A Postgres outage drops the buffered sightings and logs it. It must never+wedge the consumer: an inventory is a governance surface, and losing an hour+of it is survivable in a way that stalling alert promotion is not. The drop+is counted and logged at ``warning`` so a quiet inventory is diagnosable+rather than mysterious.+"""++from __future__ import annotations++import json+import time+from collections.abc import Callable+from dataclasses import dataclass, field+from datetime import UTC, datetime+from typing import Any++import structlog++logger = structlog.get_logger()++#: Flush when either is reached. Sized so a tenant with one agent still sees+#: its first asset inside a minute of the first span.+_MAX_PENDING = 200+_MAX_AGE_SECONDS = 30.0++#: Process names that mean a coding agent is running on a device. Matched on+#: the executable's base name, lowercased. Deliberately a small, named list+#: rather than a substring heuristic: "agent" matches half the EDR estate,+#: and a false positive here puts somebody's antivirus on an AI inventory.+CODING_AGENT_PROCESSES: dict[str, str] = {+ "claude": "Anthropic",+ "codex": "OpenAI",+ "aider": "Aider",+ "goose": "Block",+ "continue": "Continue",+ "opencode": "OpenCode",+ "gemini": "Google",+ "copilot": "GitHub",+ "copilot-language-server": "GitHub",+ "amazonq": "Amazon",+ "cline": "Cline",+}++#: Process names that mean an MCP server is running locally.+MCP_SERVER_PROCESSES: tuple[str, ...] = (+ "mcp-server",+ "mcp_server",+ "mcp-proxy",+ "uvx",+)++#: The six kinds. Mirrors `app.models.ai_asset.AI_ASSET_KINDS` in the API+#: service; the two cannot import each other because both package their code+#: as a top-level ``app``, which is the same reason the capability vocabulary+#: is mirrored rather than shared.+KIND_AI_APP = "ai_app"+KIND_CODING_AGENT = "coding_agent"+KIND_MCP_SERVER = "mcp_server"+KIND_IDE_EXTENSION = "ide_extension"+KIND_PROVIDER_KEY = "provider_key"+KIND_OAUTH_GRANT = "oauth_grant"++ALL_KINDS = (+ KIND_AI_APP,+ KIND_CODING_AGENT,+ KIND_MCP_SERVER,+ KIND_IDE_EXTENSION,+ KIND_PROVIDER_KEY,+ KIND_OAUTH_GRANT,+)++_UPSERT_SQL = """+INSERT INTO aisoc_ai_assets (+ tenant_id, kind, external_id, display_name, vendor, discovery_source,+ principal, device, attributes, risk_score, risk_reasons,+ first_seen_at, last_seen_at, observation_count+)+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11::jsonb, $12, $13, $14)+ON CONFLICT ON CONSTRAINT aisoc_ai_assets_identity DO UPDATE SET+ -- LEAST/GREATEST rather than assignment: a replayed Kafka batch or a+ -- late-arriving span must not be able to move first_seen_at forward,+ -- which would erase the one fact an inventory exists to keep.+ first_seen_at = LEAST(aisoc_ai_assets.first_seen_at, EXCLUDED.first_seen_at),+ last_seen_at = GREATEST(aisoc_ai_assets.last_seen_at, EXCLUDED.last_seen_at),+ observation_count = aisoc_ai_assets.observation_count + EXCLUDED.observation_count,+ display_name = COALESCE(EXCLUDED.display_name, aisoc_ai_assets.display_name),+ vendor = COALESCE(EXCLUDED.vendor, aisoc_ai_assets.vendor),+ -- A later sighting that did not learn the person must not erase one an+ -- earlier sighting did. COALESCE in this order keeps the newer value+ -- when there is one and the older value when there is not.+ principal = COALESCE(EXCLUDED.principal, aisoc_ai_assets.principal),+ attributes = aisoc_ai_assets.attributes || EXCLUDED.attributes,+ risk_score = EXCLUDED.risk_score,+ risk_reasons = EXCLUDED.risk_reasons,+ updated_at = NOW()+"""+++@dataclass+class _Sighting:+ """One asset as last seen, with everything merged in."""++ tenant_id: str+ kind: str+ external_id: str+ device: str | None+ display_name: str | None = None+ vendor: str | None = None+ discovery_source: str = "ai_runtime"+ principal: str | None = None+ attributes: dict[str, Any] = field(default_factory=dict)+ count: int = 0+ first_seen: float = 0.0+ last_seen: float = 0.0++ @property+ def identity(self) -> tuple[str, str, str, str]:+ # The device participates in identity, and the empty string stands in+ # for "no device" so two unlinked sightings of one provider key+ # coalesce rather than accumulating. The database agrees through+ # NULLS NOT DISTINCT on the same tuple.+ return (self.tenant_id, self.kind, self.external_id, self.device or "")++ def merge(self, other: _Sighting) -> None:+ self.count += other.count+ self.first_seen = min(self.first_seen, other.first_seen) if self.first_seen else other.first_seen+ self.last_seen = max(self.last_seen, other.last_seen)+ self.display_name = other.display_name or self.display_name+ self.vendor = other.vendor or self.vendor+ self.principal = other.principal or self.principal+ for key, value in other.attributes.items():+ if key in ("tools", "models", "prompt_secret_kinds"):+ merged = set(self.attributes.get(key, [])) | set(value or [])+ self.attributes[key] = sorted(merged)+ else:+ self.attributes[key] = value+++def _nested(obj: Any, *path: str) -> Any:+ cur: Any = obj+ for key in path:+ if not isinstance(cur, dict):+ return None+ cur = cur.get(key)+ return cur+++def _text(value: Any) -> str | None:+ if isinstance(value, str) and value.strip():+ return value.strip()[:255]+ return None+++def _basename(path: str) -> str:+ stem = path.replace("\\", "/").rsplit("/", 1)[-1].lower()+ return stem[:-4] if stem.endswith(".exe") else stem+++def classify(message: dict[str, Any]) -> list[_Sighting]:+ """Turn one normalized event into zero or more AI-asset sightings.++ Pure, so the classification can be tested against vendor-shaped payloads+ without a database — and so the database half can be tested without+ reconstructing an event.+ """+ ocsf = message.get("ocsf_event")+ if not isinstance(ocsf, dict):+ return []+ tenant_id = _text(message.get("tenant_id") or ocsf.get("tenant_uid"))+ if not tenant_id:+ return []++ now = time.time()+ source_type = _text(ocsf.get("source_type")) or _text(_nested(ocsf, "metadata", "product", "name")) or ""+ out: list[_Sighting] = []++ if source_type in ("ai-runtime", "ai-finding", "AI Runtime", "AI Guardrail"):+ out.extend(_from_ai_telemetry(tenant_id, ocsf, now))+ elif ocsf.get("class_uid") == 1007:+ out.extend(_from_process_activity(tenant_id, ocsf, now))+ elif source_type in ("llm_usage", "AI / LLM Usage Audit"):+ out.extend(_from_provider_audit(tenant_id, ocsf, now))++ return out+++def _from_ai_telemetry(tenant_id: str, ocsf: dict[str, Any], now: float) -> list[_Sighting]:+ """SDK and gateway spans: the agent, its model, and any MCP server."""+ agent_id = _text(_nested(ocsf, "actor", "process", "name"))+ agent_name = _text(_nested(ocsf, "actor", "process", "path"))+ principal = _text(_nested(ocsf, "actor", "user", "name"))+ device = _text(_nested(ocsf, "src_endpoint", "hostname"))+ model = _text(_nested(ocsf, "metadata", "product", "feature", "name"))+ provider = _text(ocsf.get("cloud", {}).get("provider")) if isinstance(ocsf.get("cloud"), dict) else None+ tool = _text(ocsf.get("activity_name"))+ secret_kinds = _nested(ocsf, "finding", "evidence", "prompt_secret_kinds") or []+ server = _text(ocsf.get("resource", {}).get("name")) if isinstance(ocsf.get("resource"), dict) else None++ out: list[_Sighting] = []+ if agent_id:+ attributes: dict[str, Any] = {}+ if model:+ attributes["models"] = [model]+ if provider:+ attributes["provider"] = provider+ if tool:+ attributes["tools"] = [tool]+ if isinstance(secret_kinds, list) and secret_kinds:+ attributes["prompt_secret_kinds"] = sorted({str(k) for k in secret_kinds})+ # A coding agent is distinguished by its binary, not by the fact that+ # it is an agent. An agent we cannot place is an `ai_app`, which is+ # the honest answer rather than the flattering one.+ base = _basename(agent_name or agent_id)+ is_coding = base in CODING_AGENT_PROCESSES+ out.append(+ _Sighting(+ tenant_id=tenant_id,+ kind=KIND_CODING_AGENT if is_coding else KIND_AI_APP,+ external_id=agent_id,+ device=device,+ display_name=agent_name or agent_id,+ vendor=CODING_AGENT_PROCESSES.get(base) or provider,+ discovery_source="ai_runtime",+ principal=principal,+ attributes=attributes,+ count=1,+ first_seen=now,+ last_seen=now,+ )+ )+ if server:+ out.append(+ _Sighting(+ tenant_id=tenant_id,+ kind=KIND_MCP_SERVER,+ external_id=server,+ device=device,+ display_name=server,+ discovery_source="ai_runtime",+ principal=principal,+ attributes={"tools": [tool]} if tool else {},+ count=1,+ first_seen=now,+ last_seen=now,+ )+ )+ return out+++def _from_process_activity(tenant_id: str, ocsf: dict[str, Any], now: float) -> list[_Sighting]:+ """EDR and osquery process telemetry: the device and the binary.++ Depth 6.2 supplies the osquery half and widens the match tables; this+ reads whatever an EDR connector already normalizes to class 1007.+ """+ name = _text(_nested(ocsf, "process", "name")) or _text(_nested(ocsf, "actor", "process", "name"))+ cmdline = _text(_nested(ocsf, "process", "cmd_line")) or ""+ device = _text(_nested(ocsf, "device", "name")) or _text(_nested(ocsf, "src_endpoint", "hostname"))+ principal = _text(_nested(ocsf, "actor", "user", "name"))+ if not name:+ return []+ base = _basename(name)++ if base in CODING_AGENT_PROCESSES:+ attributes: dict[str, Any] = {"process": base}+ # The flag an agent is started with to stop asking. Read from the+ # command line because that is the only place it appears; an agent+ # running this way takes no human confirmation before acting.+ lowered = cmdline.lower()+ if any(flag in lowered for flag in ("--dangerously-skip-permissions", "--yolo", "--auto-approve", "--no-confirm")):+ attributes["permission_prompts_disabled"] = True+ return [+ _Sighting(+ tenant_id=tenant_id,+ kind=KIND_CODING_AGENT,+ external_id=base,+ device=device,+ display_name=name,+ vendor=CODING_AGENT_PROCESSES[base],+ discovery_source="endpoint",+ principal=principal,+ attributes=attributes,+ count=1,+ first_seen=now,+ last_seen=now,+ )+ ]++ if any(token in base for token in MCP_SERVER_PROCESSES):+ return [+ _Sighting(+ tenant_id=tenant_id,+ kind=KIND_MCP_SERVER,+ external_id=base,+ device=device,+ display_name=name,+ discovery_source="endpoint",+ principal=principal,+ attributes={"process": base, "cmd_line": cmdline[:255]} if cmdline else {"process": base},+ count=1,+ first_seen=now,+ last_seen=now,+ )+ ]+ return []+++def _from_provider_audit(tenant_id: str, ocsf: dict[str, Any], now: float) -> list[_Sighting]:+ """Provider control-plane audit: keys minted, grants consented to.++ No device is available from any provider's audit log, and that is the+ reason `discovery_source` exists: an analyst must be able to tell an+ unlinked device from an unlinkable one.+ """+ event_type = _text(ocsf.get("activity_name")) or ""+ principal = _text(_nested(ocsf, "actor", "user", "name"))+ provider = _text(_nested(ocsf, "metadata", "product", "vendor_name"))+ subject = _text(_nested(ocsf, "finding", "uid")) or _text(ocsf.get("message"))+ if not subject:+ return []++ lowered = event_type.lower()+ if "api_key" in lowered or "service_account" in lowered:+ kind, source = KIND_PROVIDER_KEY, "provider_audit"+ elif "oauth" in lowered or "consent" in lowered or "token" in lowered:+ kind, source = KIND_OAUTH_GRANT, "oauth_audit"+ else:+ return []++ attributes: dict[str, Any] = {"event_type": event_type}+ scopes = _nested(ocsf, "finding", "evidence", "scopes")+ if isinstance(scopes, list) and scopes:+ attributes["scopes"] = sorted({str(s) for s in scopes})++ return [+ _Sighting(+ tenant_id=tenant_id,+ kind=kind,+ external_id=subject,+ device=None,+ display_name=subject,+ vendor=provider,+ discovery_source=source,+ principal=principal,+ attributes=attributes,+ count=1,+ first_seen=now,+ last_seen=now,+ )+ ]+++class AiAssetRecorder:+ """Coalesce AI-asset sightings and upsert them into Postgres."""++ def __init__(+ self,+ pool_provider: Callable[[], Any],+ *,+ max_pending: int = _MAX_PENDING,+ max_age_seconds: float = _MAX_AGE_SECONDS,+ ) -> None:+ self._pool_provider = pool_provider+ self._max_pending = max_pending+ self._max_age = max_age_seconds+ self._pending: dict[tuple[str, str, str, str], _Sighting] = {}+ self._last_flush = time.monotonic()+ self._metrics = {"observed": 0, "written": 0, "dropped": 0}++ @property+ def metrics(self) -> dict[str, int]:+ return dict(self._metrics)++ async def observe(self, message: dict[str, Any]) -> int:+ """Buffer any AI assets this event evidences. Returns how many."""+ sightings = classify(message)+ for sighting in sightings:+ existing = self._pending.get(sighting.identity)+ if existing is None:+ self._pending[sighting.identity] = sighting+ else:+ existing.merge(sighting)+ self._metrics["observed"] += len(sightings)+ if len(self._pending) >= self._max_pending:+ await self.flush()+ return len(sightings)++ async def flush_if_stale(self) -> None:+ if self._pending and (time.monotonic() - self._last_flush) >= self._max_age:+ await self.flush()++ async def flush(self) -> int:+ """Write everything buffered. Never raises into the consumer."""+ if not self._pending:+ self._last_flush = time.monotonic()+ return 0+ batch = list(self._pending.values())+ self._pending.clear()+ self._last_flush = time.monotonic()++ pool = self._pool_provider() if callable(self._pool_provider) else self._pool_provider+ if pool is None:+ self._metrics["dropped"] += len(batch)+ logger.warning(+ "ai_asset_recorder.no_pool",+ dropped=len(batch),+ detail="no database pool; AI inventory sightings were discarded",+ )+ return 0++ written = 0+ try:+ async with pool.acquire() as conn:+ for sighting in batch:+ score, reasons = _score(sighting)+ await conn.execute(+ _UPSERT_SQL,+ sighting.tenant_id,+ sighting.kind,+ sighting.external_id,+ sighting.display_name,+ sighting.vendor,+ sighting.discovery_source,+ sighting.principal,+ sighting.device,+ _json(sighting.attributes),+ score,+ _json(reasons),+ _utc(sighting.first_seen),+ _utc(sighting.last_seen),+ sighting.count,+ )+ written += 1+ except Exception as exc: # noqa: BLE001 — an inventory must never wedge promotion+ self._metrics["dropped"] += len(batch) - written+ logger.warning("ai_asset_recorder.flush_failed", error=str(exc)[:300], dropped=len(batch) - written)+ self._metrics["written"] += written+ return written+++def _json(value: Any) -> str:+ return json.dumps(value, default=str)+++def _utc(epoch: float) -> datetime:+ return datetime.fromtimestamp(epoch or time.time(), tz=UTC)+++def _score(sighting: _Sighting) -> tuple[int, list[str]]:+ """Risk for a freshly observed asset.++ Mirrors ``services/api/app/services/ai_inventory.py::score_risk`` for the+ inputs a sighting carries. The two services cannot import each other, so+ ``scripts/check_ai_asset_inventory.py`` is not the thing holding them+ together — ``services/fusion/tests/test_ai_asset_recorder.py`` asserts+ the two agree on a shared table of cases, which is the only way a mirror+ stays a mirror.++ `sanctioned` is always None here: a newly observed asset is by definition+ one nobody has judged yet, and the sanction route recomputes the score+ when somebody does.+ """+ points = 0+ reasons: list[str] = []+ if not sighting.principal:+ points += 15+ reasons.append("No person is linked: nobody is accountable for what it does.")+ if not sighting.device and sighting.kind in {KIND_CODING_AGENT, KIND_IDE_EXTENSION, KIND_MCP_SERVER}:+ points += 10+ reasons.append("No device is linked, so containment has nowhere to act.")+ points += 20+ reasons.append("Not declared in the inventory: nobody has reviewed it.")+ if sighting.attributes.get("permission_prompts_disabled"):+ points += 25+ reasons.append("Started with its permission prompts disabled, so a human confirms nothing.")+ source = str(sighting.attributes.get("install_source") or "")+ if source and source not in {"official", "vendor", "internal"}:+ points += 20+ reasons.append(f"Installed from an unvetted source ({source}).")+ secret_kinds = sighting.attributes.get("prompt_secret_kinds") or []+ if secret_kinds:+ points += 20+ reasons.append(f"Credential material has appeared in its prompts ({', '.join(sorted(secret_kinds)[:3])}).")+ tools = {str(t) for t in (sighting.attributes.get("tools") or [])}+ risky = sorted(tools & _HIGH_RISK_TOOLS)+ if risky:+ points += 15+ reasons.append(f"Calls tools that change an estate ({', '.join(risky[:3])}).")+ scopes = {str(s) for s in (sighting.attributes.get("scopes") or [])}+ broad = sorted(scopes & _BROAD_OAUTH_SCOPES)+ if broad:+ points += 25+ reasons.append(f"Holds an OAuth scope covering a whole mailbox, drive or org ({broad[0]}).")+ return min(points, 100), reasons+++#: Mirrors of the two tables in `app/services/ai_inventory.py`, kept here for+#: the same reason the capability vocabulary is mirrored: two independently+#: deployable services, one shared meaning, and a test that compares them.+_HIGH_RISK_TOOLS: frozenset[str] = frozenset(+ {+ "execute_command",+ "run_shell",+ "write_file",+ "delete_file",+ "send_email",+ "create_user",+ "grant_permission",+ "deploy",+ "terraform_apply",+ "database_write",+ }+)++_BROAD_OAUTH_SCOPES: frozenset[str] = frozenset(+ {+ "https://mail.google.com/",+ "https://www.googleapis.com/auth/drive",+ "https://www.googleapis.com/auth/gmail.modify",+ "https://www.googleapis.com/auth/admin.directory.user",+ "Mail.ReadWrite",+ "Mail.Read",+ "Files.ReadWrite.All",+ "Sites.ReadWrite.All",+ "Directory.ReadWrite.All",+ "repo",+ "admin:org",+ }+)diff --git a/services/fusion/app/workers/consumer.py b/services/fusion/app/workers/consumer.pyindex 07f60a422..cfc9fca75 100644--- a/services/fusion/app/workers/consumer.py+++ b/services/fusion/app/workers/consumer.py@@ -15,6 +15,7 @@ from aiokafka import AIOKafkaConsumer, AIOKafkaProducerfrom app.core.config import settingsfrom app.core.kafka_security import kafka_client_kwargsfrom app.models.alert import FusionDecision, RawAlert+from app.services.ai_asset_recorder import AiAssetRecorderfrom app.services.alert_sink import AlertSink, PersistOutcome, PersistResultfrom app.services.detection_engine import DetectionEnginefrom app.services.dlq import DeadLetter, DeadLetterQueue, LoggingDLQ, safe_record@@ -42,6 +43,7 @@ _METRICS = {"detected": 0,"dead_lettered": 0,"errors": 0,+ "ai_assets_observed": 0,}@@ -59,6 +61,7 @@ class FusionWorker:first_seen: Any | None = None,ueba_cache: UebaSignalCache | None = None,overlays: OverlayCache | None = None,+ ai_assets: AiAssetRecorder | None = None,) -> None:self._engine = engineself._sink = sink@@ -67,6 +70,10 @@ class FusionWorker:self._windowed = windowed_detectorself._first_seen = first_seenself._ueba_cache = ueba_cache+ #: Depth 6.1 — the observed AI estate. Optional in the same sense the+ #: lake writer is: a deployment that passes nothing behaves exactly+ #: as before, and `main.py` passes one on every profile.+ self._ai_assets = ai_assets#: Per-tenant detection tuning (parity 5.4). Optional, so a#: deployment that passes nothing behaves exactly as before.self._overlays = overlays@@ -149,6 +156,8 @@ class FusionWorker:await asyncio.sleep(interval)if self._lake is not None:await self._lake.flush_if_stale()+ if self._ai_assets is not None:+ await self._ai_assets.flush_if_stale()except asyncio.CancelledError: # pragma: no cover — shutdown pathpass@@ -167,6 +176,10 @@ class FusionWorker:await self._sink.stop()if self._lake is not None:await self._lake.stop()+ # Flush the inventory buffer on the way out, so a clean shutdown does+ # not discard up to 30 seconds of sightings.+ if self._ai_assets is not None:+ await self._ai_assets.flush()logger.info("Fusion worker stopped", metrics=_METRICS)async def _consume_loop(self) -> None:@@ -291,6 +304,15 @@ class FusionWorker:if self._lake is not None and await self._lake.write_event(payload):_METRICS["laked"] += 1+ # Depth 6.1 — the observed AI estate is built here rather than by+ # a separate worker reading the lake, for one reason: this is the+ # branch every normalized event already travels on the default+ # profile. A reader of the lake would be a second service CORE+ # does not start, and the inventory page would be empty on the+ # deployment most likely to have an ungoverned AI estate.+ if self._ai_assets is not None:+ _METRICS["ai_assets_observed"] += await self._ai_assets.observe(payload)+# Resolved once and shared by both engines. Parity 5.4: without# the overlay the stateless engine evaluated the shared corpus and# nothing else, so a tenant who disabled a noisy rule in the