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.

chore(depth): defer to phase 9's claim and move the AI-assets migration to 110

Beenu Arora5b52dd1a8f1e
diff --cc CHANGELOG.md
index cfc173f50,59b54ed67..adae0ecb8
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -191,40 -231,6 +231,40 @@@ and this project adheres to [Semantic V
### Added
+- **An AI-estate inventory built from observation rather than registration**
- (depth plan 6.1). `aisoc_ai_assets` (migration `105`, tenant-scoped with
++ (depth plan 6.1). `aisoc_ai_assets` (migration `110`, tenant-scoped with
+ forced row-level security) holds every AI app, coding agent, MCP server,
+ IDE extension, model-provider key and OAuth grant AiSOC has seen, with the
+ person and device behind each. The gap it closes is that `aisoc_mcp_servers`
+ records what an operator *declared*, and the row that matters in an AI
+ governance review is the one present in observation and absent from the
+ declaration.
+
+ Measured the way the recurring defect here demands: the writer is in the
+ fusion consumer's raw-events branch, the one path every normalized event
+ already travels on the default profile, because a recorder behind a flag or
+ in a service CORE does not start is a table nothing writes and a page that
+ renders "no AI estate" to a tenant that has one.
+ `scripts/check_ai_asset_inventory.py` makes that a rule rather than a
+ comment — it requires the consumer to call the recorder *and* the service
+ to construct it, since an unconstructed recorder is a `None` every call
+ site skips in silence. `ai-estate-live.yml` writes a fixture estate of
+ three kinds into a real PostgreSQL as the DML-only `aisoc_app` role, and
+ two negative controls re-inject real defects: reverting `NULLS NOT
+ DISTINCT` on the identity constraint turns one provider-key row into
+ three, and a tenant policy of `USING (true)` lets one tenant read
+ another's estate.
+
+ Also: graph schema `v1.2 → v1.3` adds the `AIAsset` label with
+ `(:User)-[:OPERATES]->(:AIAsset)` and `(:Endpoint)-[:HOSTS]->(:AIAsset)`,
+ emitted by `services/ingest` as a post-pass rather than a connector case —
+ AI telemetry arrives on three connector types and as plain process
+ activity, so keying on the connector would have covered one of them and
+ looked complete. A new `ai_estate:read` / `ai_estate:write` permission
+ pair, held by real roles and mintable into an API key, because the
+ inventory names which agent on which laptop holds which provider key and
+ `hunts:read` already demonstrated what a permission no role holds is worth.
+
- `services/api/app/models/detection_rule.py` maps the `author` column, which
has existed since `001_init.sql` and was mapped by nothing — while fusion's
tenant overlay reads it on every reload to say *who* silenced a rule when it
diff --cc DEPTH_PROGRESS.md
index 204dd08c5,a75a88df4..7deca27e2
--- a/DEPTH_PROGRESS.md
+++ b/DEPTH_PROGRESS.md
@@@ -58,20 -58,23 +58,41 @@@ is written. Next free at capture: migra
| ADR `0010` | 2.7 — entity and session context in CORE | **landed**, `docs/decisions/0010-entity-and-session-context-in-core.md`, accepted |
| migration `102` | 2.4 — `102_sessions.sql` | claimed |
| migration `103` | 2.5 — `103_posture_snapshots.sql` | claimed |
- | migration `104` | 5.4 — `104_playbook_verification.sql` | claimed on `depth/5.4-5.6-lane-c`, recorded here because the lane took it without a row |
- | migration `105` | 6.1 — `105_ai_assets.sql` | claimed |
- | migration `106` | 6.4 — `106_ai_agent_identities.sql` | claimed |
+ | migration `104` | 9.1 — `104_mcp_access.sql` | claimed |
+ | migration `105` | 9.2 — `105_semantic_memory.sql` | claimed |
+ | migration `106` | 9.3 — `106_case_depth.sql` | claimed |
+ | migration `107` | 9.4 — `107_case_war_rooms.sql` | claimed |
+ | migration `108` | 9.5 — `108_hunt_reports.sql` | claimed |
+ | migration `109` | 9.6 — `109_push_devices.sql` | claimed |
++| migration `110` | 6.1 — `110_ai_assets.sql` | claimed |
++| migration `111` | 6.4 — `111_ai_agent_identities.sql` | claimed |
+| ADR `0011` | 6.6 — AI containment arms off by default, and the rollback a kill-switch needs | claimed |
++| — | 5.4 — `104_playbook_verification.sql` on `depth/5.4-5.6-lane-c`, and 7.1 — `104_phishing_campaigns.sql` on `depth/7.1-7.3-phishing` | **collision, unresolved here.** Both lanes wrote a `104` on a branch without a row in this table. Phase 9's `104` is the one with a claim, so these two need renumbering by their own lanes; recorded rather than renamed from outside, because renaming another lane's migration from here is how a branch comes back to a file that no longer exists |
Highest migration on `main` at claim time was `101_audit_immutable_nullify.sql`,
so `095`--`101` were taken by sibling lanes between the capture above and this
claim; re-read `services/api/migrations/` rather than trusting the capture row.
- The same is true of this table: `104` was already written on a sibling lane's
- branch with no row here, which is how two lanes collide. Phase 6's numbers
- above were picked after reading `services/api/migrations/` on `main` **and**
++The same is true of this table: `104` was already written on two sibling
++lanes' branches with no row here, which is how lanes collide. Phase 6's
++numbers were picked after reading `services/api/migrations/` on `main` **and**
+`git ls-tree` over every `origin/*` branch, not from the row above.
+
+ Phase 9 re-read `services/api/migrations/` on 2026-10-11 before claiming:
+ `101_audit_immutable_nullify.sql` was still the highest on `main`, and `102`
+ and `103` were already spoken for in the table above, so Phase 9 takes `104`
+ through `109`, one per item. A number left unused at the end of the phase is
+ released by striking its row rather than by silently leaving a gap.
+
++**Phase 6 moved `105`/`106` to `110`/`111` on 2026-10-11**, because Phase 9's
++claim for `104`--`109` reached this table on `main` first and a claim table
++nobody defers to is not a coordination mechanism. The lesson is the one this
++section already states and that three lanes still fell to: the table is
++authoritative only for lanes that write to it **before** the file, and four
++branches now carry a `104` or a `105` that was never claimed here. Reading
++`main` is not enough; read `git ls-tree` over every `origin/*` branch as
++well, which is what found this.
++
## Phase 0: Kickoff
- [x] **0.1** `DEPTH_PROGRESS.md` exists (this file), modelled on
@@@ -393,51 -396,7 +414,51 @@@ invented fields on the first run of th
## Phase 6: AI agent security
-- [ ] **6.1** AI asset inventory
+- [x] **6.1** AI asset inventory. Reproduced:
+ `scripts/check_ai_asset_inventory.py` on the unmodified tree reported nine
+ problems across five of its eight rules — no migration creates the table,
+ no model maps it, no route reads it, no writer exists, and the graph
+ vocabulary has no label for an AI asset. Implemented `aisoc_ai_assets`
- (migration `105`, tenant-scoped, `FORCE ROW LEVEL SECURITY`, granted to
++ (migration `110`, tenant-scoped, `FORCE ROW LEVEL SECURITY`, granted to
+ `aisoc_app`), the ORM model, `GET /ai-assets`, `GET /ai-assets/{id}` and
+ `POST /ai-assets/{id}/sanction` behind a new `ai_estate:read` /
+ `ai_estate:write` pair held by five roles and mintable into an API key,
+ `AiAssetRecorder` in the fusion consumer's raw-events branch, the `AIAsset`
+ graph label with `OPERATES` and `HOSTS` edges emitted at ingest (schema
+ `v1.2 -> v1.3`), and the `/ai-estate` console page. 21 new fusion tests
+ (suite 662 -> 683), 8 new Go tests in `internal/graph`, 5 live-Postgres
+ cases in `tests/isolation/test_ai_estate_live.py`.
+
+ **The writer is the whole item**, and the gate says so rather than the
+ prose: the `WRITER` rule requires the consumer to call the recorder *and*
+ `main.py` to construct it, because an unconstructed recorder is a `None`
+ every call site skips in silence and the page would render "no AI estate"
+ to a tenant that has one — the second half of this repository's recurring
+ defect, the half module reachability cannot see.
+
+ Two negative controls, both re-injecting a real defect rather than an
+ invented one, both run against a real PostgreSQL 16 with every migration
+ applied and the suite connected as the DML-only `aisoc_app` role: reverting
+ the identity constraint from `UNIQUE NULLS NOT DISTINCT` to plain `UNIQUE`
+ turns one provider-key row into **three**, each claiming to be first seen
+ now (measured, not predicted — a provider key has no device, so under the
+ default NULL semantics every sighting inserts); and a tenant policy of
+ `USING (true)` lets tenant A read tenant B's estate. Each fails the suite
+ and each is a step in `ai-estate-live.yml`. The gate's own self-test
+ injects one violation per rule and found two blind spots in the gate while
+ being written — it read its own component's docstring as a fabrication, and
+ a `NodeAIAsset,` substring match would have passed on a commented-out
+ `// NodeAIAsset,`.
+
+ **Two limits, stated rather than left to be found.** Phase 2.5 is open, so
+ `effective_permissions` is a column with a resolver behind it and nothing
+ writing it yet; the risk scorer returns `False` for an absent snapshot
+ rather than treating unknown as privileged, and the console says in words
+ that permissions did not contribute. And the three discovery sources see
+ genuinely different things — runtime telemetry never carries a device, a
+ provider audit log never carries either — so `discovery_source` is stored
+ per row and the page prints what each source can and cannot see, because
+ an unlinked device and an unlinkable one are different facts.
- [ ] **6.2** Endpoint discovery with no new agent
- [ ] **6.3** Provider coverage beyond OpenAI and Anthropic
- [ ] **6.4** Agent identity and baselines (parity 6.7)
@@@ -482,5 -441,4 +503,5 @@@
| 2026-10-09 | 3.3 | Identity privilege (18 rules) and a per-tenant first-seen store (2) built; 5 rules were never unreachable (gate operator drift, D9); 18 retired with a reason (D10). `MAX_UNREACHABLE` 45 → 2, the two remaining both needing the 3.4 baseline. Two matcher operators three shipped rules already used were implemented. |
| 2026-10-09 | 3.2 | Ordered and unordered sequences in the windowed engine; all four translatable Sigma correlation types compile, seven refusal reasons recorded. No upstream correlation rule exists in this tree to import (D8), so the corpus is first-party and labelled as such. |
| 2026-10-09 | 4.1 | Reproduced: `check_cloud_native_collection.py` on the unmodified tree reported all three collection paths absent. Implemented `aws_cloudtrail_s3` (SQS-notified S3 objects; management events, data events and VPC flow logs; delete-after-emit), `gcp_pubsub` (REST pull on a log-sink subscription; ack-after-read) and `azure_event_hubs` (Capture blobs over the Data Lake Gen2 JSON API, with a focused Avro OCF reader). Negative controls recorded in the PR: deleting the SQS message before the object is read, acknowledging the Pub/Sub batch before it is built, ignoring the Avro union branch index, and ignoring the flow-log header line each fail a named test, and all were restored. Connectors suite 1014 -> 1098 passed. |
- | 2026-10-11 | 6.1 | Reproduced: the new gate reported nine problems across five of eight rules on the unmodified tree. Built `aisoc_ai_assets` (migration 105), its routes behind a new `ai_estate:*` permission pair, the fusion recorder that writes it on the default profile, the `AIAsset` graph label with `OPERATES`/`HOSTS` edges, and the `/ai-estate` page. Two negative controls against a real PostgreSQL: reverting `NULLS NOT DISTINCT` turns one provider-key row into three, and a `USING (true)` policy leaks across tenants. Claim matrix 302 -> 303 rows, 300 GATED. Writing the gate found two blind spots in the gate itself. |
++| 2026-10-11 | 6.1 | Reproduced: the new gate reported nine problems across five of eight rules on the unmodified tree. Built `aisoc_ai_assets` (migration 110), its routes behind a new `ai_estate:*` permission pair, the fusion recorder that writes it on the default profile, the `AIAsset` graph label with `OPERATES`/`HOSTS` edges, and the `/ai-estate` page. Two negative controls against a real PostgreSQL: reverting `NULLS NOT DISTINCT` turns one provider-key row into three, and a `USING (true)` policy leaks across tenants. Claim matrix 302 -> 303 rows, 300 GATED. Writing the gate found two blind spots in the gate itself. |
| 2026-10-09 | 3.1 | All 74 decided. 50 translated into `wd-*` rules derived from each original's own clauses and replayed through the real engine (162 assertions); 24 refused with a reason across five kinds. `MAX_UNREACHABLE` 119 → 45, published executable 2,603 → 2,529, windowed 18 → 68. Three findings recorded as D4–D6 below. |
diff --cc services/api/app/models/ai_asset.py
index 0e04a9722,000000000..55746951b
mode 100644,000000..100644
--- a/services/api/app/models/ai_asset.py
+++ b/services/api/app/models/ai_asset.py
@@@ -1,89 -1,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
++``110_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 --cc services/api/migrations/110_ai_assets.sql
index b784db118,000000000..8a8e251b4
mode 100644,000000..100644
--- a/services/api/migrations/110_ai_assets.sql
+++ b/services/api/migrations/110_ai_assets.sql
@@@ -1,168 -1,0 +1,168 @@@
- -- 105: the AI estate a tenant actually runs, as opposed to the one it registered.
++-- 110: 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
+$$;