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
fix(ci): what the train's first grading found, in eleven pieces
beenuara592e038073f
diff --git a/.github/workflows/verification-live.yml b/.github/workflows/verification-live.ymlindex a9c5e1b28..ea198a0a8 100644--- a/.github/workflows/verification-live.yml+++ b/.github/workflows/verification-live.yml@@ -50,7 +50,12 @@ jobs:--health-retries 20env:- LIVE_DSN: postgresql://aisoc:aisoc_ci_only@localhost:5432/aisoc+ # The suite connects as the DML-only runtime role, never the owner: a+ # superuser ignores every RLS policy even under FORCE ROW LEVEL+ # SECURITY, so the live tenancy case below would pass with the policy+ # deleted. `aisoc` (the owner) applies migrations; `aisoc_app` is what+ # the suite drives, same split as audit-retention-live.yml.+ LIVE_DSN: postgresql://aisoc_app:aisoc_app_ci_only@localhost:5432/aisocPGPASSWORD: aisoc_ci_onlyOTEL_SDK_DISABLED: "true"@@ -77,6 +82,14 @@ jobs:psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"done+ - name: Give the runtime role its password+ run: |+ set -euo pipefail+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "ALTER ROLE aisoc_app WITH PASSWORD 'aisoc_app_ci_only';"+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "GRANT USAGE ON SCHEMA public TO aisoc_app;"+# The migration applying is itself the first assertion: `102` alters a# CHECK constraint, and a constraint name that drifted would fail here# rather than on somebody's deployment.diff --git a/.gitleaksignore b/.gitleaksignoreindex fe606f9c2..397dbe39f 100644--- a/.gitleaksignore+++ b/.gitleaksignore@@ -144,3 +144,15 @@ services/connectors/tests/test_kubernetes_audit.py:generic-api-key:218# literal the suite signs with so it can then prove a *different* key fails to verify;# it authenticates nothing and exists in no deployment.services/api/tests/test_evidence_bundle.py:generic-api-key:26++# Depth 4.2 (#1322): the TAXII live job's signing secret is a CI-only literal+# that names itself as one; the workflow's Postgres and app both live and die+# inside the job. Not a credential for anything reachable.+.github/workflows/taxii-live.yml:generic-api-key:65++# Rule-id lock entries: `"<slug>": "det-threat-anomaly-NNN"` pins a detection+# rule's id so regeneration cannot renumber it. The scanner's key/value+# heuristic reads the pair as an api key; it is a rule identifier in a+# generated lock file.+detections/rule-ids.lock.json:generic-api-key:841+detections/rule-ids.lock.json:generic-api-key:854diff --git a/.security/allowlist.yml b/.security/allowlist.ymlindex a64d6f455..4f6f50b4e 100644--- a/.security/allowlist.yml+++ b/.security/allowlist.yml@@ -226,7 +226,24 @@ ceilings:error: 44measured_with: "1.86.0"checkov:- failed: 219+ # 219 -> 272 (the 2026-10-12 merge train). The chart stopped describing+ # seven services and started installing CORE (depth 4.5, #1326: three more+ # services through the generic template, litellm/ollama/qdrant as their+ # own workloads) plus the opt-in MCP server (#1304). Every added workload+ # contributes the same per-container classes the existing 219 already+ # accepted — image digests a version-templated chart cannot pin, secrets+ # delivered as env from Secret refs, imagePullPolicy IfNotPresent, no+ # read-only root for services that write temp files. What could be fixed+ # without risking boot was fixed in the same change and is why this is+ # 272 and not 293: the new templates gained seccompProfile RuntimeDefault,+ # allowPrivilegeEscalation false, capabilities drop ALL and+ # automountServiceAccountToken false (runAsNonRoot deliberately not —+ # ollama's stock image runs as root and writes /root/.ollama, and a chart+ # that renders cleanly and CreateContainerConfigErrors on install is the+ # v10 lesson). The same pass found and fixed litellm's missing config+ # volumeMount, which no static scan flags and which made the gateway+ # unable to boot at all.+ failed: 272measured_with: "3.2.334"tfsec:total: 32diff --git a/README.md b/README.mdindex fd5b43031..4b242b28b 100644--- a/README.md+++ b/README.md@@ -17,7 +17,7 @@## What AiSOC does-Telemetry arrives from your security tools. AiSOC normalizes it, runs the 2511 executable rules of+Telemetry arrives from your security tools. AiSOC normalizes it, runs the 2535 executable rules ofits 6991-rule library, groups what fires into incidents, investigates each one with an AI agent whoseevery prompt and tool call is recorded, and proposes an action. New threat intelligence re-sweeps thehistory you already collected, and a human approves before anything reaches a vendor.diff --git a/apps/web/src/components/ai-estate/AiEstateView.test.tsx b/apps/web/src/components/ai-estate/AiEstateView.test.tsxnew file mode 100644index 000000000..04bf99b5d--- /dev/null+++ b/apps/web/src/components/ai-estate/AiEstateView.test.tsx@@ -0,0 +1,160 @@+/**+ * AiEstateView — the three rendering decisions that are the page's point.+ *+ * 1. "not learned" in the colour of a finding, never a blank, for an+ * unlinked person or device.+ * 2. A failed read says it could not load — never an empty estate, because+ * "you have no shadow AI" is the most dangerous false sentence here.+ * 3. Nothing fabricated: the empty state names the sources that feed the+ * list instead of inventing rows.+ *+ * SWR is mocked at the module boundary; the real fetcher's error path (throw+ * on !ok) is what the error state models.+ */+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const swrState: { data: unknown; error: unknown; isLoading: boolean } = {+ data: undefined,+ error: undefined,+ isLoading: false,+};+const mutateMock = vi.fn();++vi.mock('swr', () => ({+ __esModule: true,+ default: () => ({ data: swrState.data, error: swrState.error, isLoading: swrState.isLoading }),+ mutate: (...args: unknown[]) => mutateMock(...args),+}));++vi.mock('@/lib/api', () => ({+ __esModule: true,+ apiHeaders: () => ({ 'Content-Type': 'application/json' }),+}));++import AiEstateView from './AiEstateView';++function asset(overrides: Record<string, unknown> = {}) {+ return {+ id: 'a1',+ kind: 'coding_agent',+ externalId: 'agent-7',+ displayName: 'cursor',+ vendor: 'anysphere',+ discoverySource: 'endpoint',+ principal: '[email protected]',+ device: 'MAC-0042',+ effectivePermissions: null,+ attributes: {},+ risk: 12,+ riskReasons: [],+ sanctioned: null,+ firstSeen: '2026-10-01T09:00:00Z',+ lastSeen: '2026-10-11T17:00:00Z',+ observationCount: 41,+ ...overrides,+ };+}++beforeEach(() => {+ swrState.data = undefined;+ swrState.error = undefined;+ swrState.isLoading = false;+ mutateMock.mockClear();+ vi.restoreAllMocks();+});++describe('AiEstateView', () => {+ it('loading claims nothing about the estate', () => {+ swrState.isLoading = true;+ render(<AiEstateView />);+ expect(screen.getByText('Loading the AI estate…')).toBeInTheDocument();+ });++ it('a failed read says so, and explicitly not that none exists', () => {+ swrState.error = new Error('HTTP 503');+ render(<AiEstateView />);+ expect(screen.getByText(/Could not load the AI estate/)).toBeInTheDocument();+ expect(screen.getByText(/not a report that none exists/)).toBeInTheDocument();+ expect(screen.queryByText(/No AI assets observed yet/)).not.toBeInTheDocument();+ });++ it('an empty estate names the sources that would fill it', () => {+ swrState.data = { items: [], total: 0, observedSources: [] };+ render(<AiEstateView />);+ expect(screen.getByText(/No AI assets observed yet/)).toBeInTheDocument();+ expect(screen.getByText(/if none of those is connected, this stays empty/)).toBeInTheDocument();+ });++ it('an unlinked person renders as "not learned" — a finding, not a blank', () => {+ swrState.data = {+ items: [asset({ principal: null, device: null })],+ total: 1,+ observedSources: ['provider_audit'],+ };+ render(<AiEstateView />);+ const notLearned = screen.getAllByText('not learned');+ expect(notLearned).toHaveLength(2); // person and device+ expect(notLearned[0]).toHaveAttribute('title', expect.stringContaining('No source linked a person'));+ });++ it('the source-limits legend states what each source cannot see', () => {+ swrState.data = { items: [asset()], total: 1, observedSources: ['endpoint', 'ai_runtime'] };+ render(<AiEstateView />);+ expect(screen.getByText(/knows the device and the binary. Never the model/)).toBeInTheDocument();+ expect(screen.getByText(/knows the agent, the model and the tools. Never the device/)).toBeInTheDocument();+ });++ it('sanction state renders all three ways, never a default of approved', () => {+ swrState.data = {+ items: [+ asset({ id: 'a1', sanctioned: true }),+ asset({ id: 'a2', externalId: 'agent-8', sanctioned: false }),+ asset({ id: 'a3', externalId: 'agent-9', sanctioned: null }),+ ],+ total: 3,+ observedSources: [],+ };+ render(<AiEstateView />);+ expect(screen.getByText('approved')).toBeInTheDocument();+ expect(screen.getByText('refused')).toBeInTheDocument();+ expect(screen.getByText('undecided')).toBeInTheDocument();+ });++ it('expanding a row explains the score, and an unraised score says so', async () => {+ swrState.data = { items: [asset({ risk: 12, riskReasons: [] })], total: 1, observedSources: [] };+ render(<AiEstateView />);+ await userEvent.click(screen.getByText('cursor'));+ expect(screen.getByText(/Why it scores 12/)).toBeInTheDocument();+ expect(screen.getByText('Nothing about this asset raised its score.')).toBeInTheDocument();+ expect(screen.getByText(/Seen 41 times via endpoint/)).toBeInTheDocument();+ expect(screen.getByText(/No permission snapshot was available/)).toBeInTheDocument();+ });++ it('risk reasons are listed when the score was earned', async () => {+ swrState.data = {+ items: [asset({ risk: 80, riskReasons: ['provider key with no owner', 'seen on 14 devices'] })],+ total: 1,+ observedSources: [],+ };+ render(<AiEstateView />);+ await userEvent.click(screen.getByText('cursor'));+ expect(screen.getByText('provider key with no owner')).toBeInTheDocument();+ expect(screen.getByText('seen on 14 devices')).toBeInTheDocument();+ });++ it('the sanction buttons post the decision and revalidate', async () => {+ swrState.data = { items: [asset()], total: 1, observedSources: [] };+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) });+ vi.stubGlobal('fetch', fetchMock);+ render(<AiEstateView />);+ await userEvent.click(screen.getByText('cursor'));+ await userEvent.click(screen.getByRole('button', { name: 'Approve' }));+ await waitFor(() => expect(fetchMock).toHaveBeenCalled());+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('/api/v1/ai-assets/a1/sanction');+ expect(JSON.parse((init as RequestInit).body as string)).toEqual({ sanctioned: true });+ await waitFor(() => expect(mutateMock).toHaveBeenCalled());+ });+});diff --git a/apps/web/src/components/cases/WarRoomPanel.test.tsx b/apps/web/src/components/cases/WarRoomPanel.test.tsxnew file mode 100644index 000000000..5a0c9a110--- /dev/null+++ b/apps/web/src/components/cases/WarRoomPanel.test.tsx@@ -0,0 +1,160 @@+/**+ * WarRoomPanel — every state the panel can honestly be in.+ *+ * The panel's job is to tell an analyst the truth about a channel that is+ * supposed to mirror the case: "not mirroring" with the vendor's reason,+ * "waiting for the first sync" (a room nobody has swept) as a different fact+ * from a quiet case, and a failed open surfacing the vendor's own sentence+ * rather than "something went wrong". These tests pin each of those renders,+ * plus the contract that bit on the merge train: the SWR key answers with a+ * *list*, and a non-list is a crash, not a render.+ */+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { WarRoom } from '@/lib/api';++const swrState: {+ data: WarRoom[] | undefined;+ error: unknown;+ isLoading: boolean;+} = { data: undefined, error: undefined, isLoading: false };++const mutate = vi.fn(async () => undefined);++vi.mock('swr', () => ({+ __esModule: true,+ default: () => ({+ data: swrState.data,+ error: swrState.error,+ isLoading: swrState.isLoading,+ mutate,+ }),+}));++const openMock = vi.fn();++vi.mock('@/lib/api', () => {+ class ApiError extends Error {+ status: number;+ body: string;+ constructor(message: string, status: number, body: string) {+ super(message);+ this.status = status;+ this.body = body;+ }+ }+ return {+ __esModule: true,+ ApiError,+ warRoomApi: {+ forCase: vi.fn(async () => []),+ open: (...args: unknown[]) => openMock(...args),+ },+ };+});++import { ApiError } from '@/lib/api';+import { WarRoomPanel } from './WarRoomPanel';++function room(overrides: Partial<WarRoom> = {}): WarRoom {+ return {+ id: 'wr-1',+ case_id: 'c1',+ provider: 'slack',+ channel_id: 'C0123',+ channel_name: 'aisoc-case-0001',+ channel_url: 'https://example.slack.com/archives/C0123',+ state: 'open',+ opened_by: '[email protected]',+ last_synced_at: null,+ last_error: '',+ ...overrides,+ };+}++beforeEach(() => {+ swrState.data = undefined;+ swrState.error = undefined;+ swrState.isLoading = false;+ mutate.mockClear();+ openMock.mockReset();+});++describe('WarRoomPanel', () => {+ it('renders the loading state before claiming anything about rooms', () => {+ swrState.isLoading = true;+ render(<WarRoomPanel caseId="c1" />);+ expect(screen.getByText('Loading…')).toBeInTheDocument();+ });++ it('a failed load says it could not load, never an empty estate', () => {+ swrState.error = new Error('boom');+ render(<WarRoomPanel caseId="c1" />);+ expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load war rooms");+ expect(screen.queryByText(/No war room yet/)).not.toBeInTheDocument();+ });++ it('an empty list is the no-room state, with the explanation of what opening does', () => {+ swrState.data = [];+ render(<WarRoomPanel caseId="c1" />);+ expect(screen.getByText(/No war room yet/)).toBeInTheDocument();+ });++ it('a never-synced room reads "waiting for the first sync", not as quiet', () => {+ swrState.data = [room({ last_synced_at: null })];+ render(<WarRoomPanel caseId="c1" />);+ expect(screen.getByText('waiting for the first sync')).toBeInTheDocument();+ });++ it('a room that stopped mirroring surfaces the vendor reason as an alert', () => {+ swrState.data = [room({ last_error: 'Slack refused: account_inactive' })];+ render(<WarRoomPanel caseId="c1" />);+ expect(screen.getByRole('alert')).toHaveTextContent('not mirroring — Slack refused: account_inactive');+ });++ it('a synced room shows when, and a closed room says so', () => {+ swrState.data = [+ room({ last_synced_at: '2026-10-12T05:00:00Z' }),+ room({ id: 'wr-2', state: 'closed', channel_name: 'aisoc-case-0001-b' }),+ ];+ render(<WarRoomPanel caseId="c1" />);+ expect(screen.getByText(/mirroring · last synced/)).toBeInTheDocument();+ expect(screen.getByText('(closed)')).toBeInTheDocument();+ });++ it('opening posts the provider and refreshes the list', async () => {+ swrState.data = [];+ openMock.mockResolvedValue(room());+ render(<WarRoomPanel caseId="c1" />);+ await userEvent.click(screen.getByRole('button', { name: 'Open in Slack' }));+ await waitFor(() => expect(openMock).toHaveBeenCalledWith('c1', 'slack'));+ expect(mutate).toHaveBeenCalled();+ });++ it('a refused open surfaces the vendor sentence verbatim, not a generic apology', async () => {+ swrState.data = [];+ openMock.mockRejectedValue(new ApiError('Bad Gateway', 502, 'Slack refused to create #aisoc-case-0001: restricted_action'));+ render(<WarRoomPanel caseId="c1" />);+ await userEvent.click(screen.getByRole('button', { name: 'Open in Slack' }));+ expect(await screen.findByText(/restricted_action/)).toBeInTheDocument();+ expect(screen.queryByText('Open failed.')).not.toBeInTheDocument();+ });++ it('the teams button asks for teams', async () => {+ swrState.data = [];+ openMock.mockResolvedValue(room({ provider: 'teams' }));+ render(<WarRoomPanel caseId="c1" />);+ await userEvent.click(screen.getByRole('button', { name: 'Open in Teams' }));+ await waitFor(() => expect(openMock).toHaveBeenCalledWith('c1', 'teams'));+ });++ it('a non-Error rejection still renders a failure rather than nothing', async () => {+ swrState.data = [];+ openMock.mockRejectedValue('wat');+ render(<WarRoomPanel caseId="c1" />);+ await userEvent.click(screen.getByRole('button', { name: 'Open in Slack' }));+ expect(await screen.findByText('Open failed.')).toBeInTheDocument();+ });+});diff --git a/apps/web/src/components/settings/MfaView.test.tsx b/apps/web/src/components/settings/MfaView.test.tsxindex 20fb83530..08c2d3034 100644--- a/apps/web/src/components/settings/MfaView.test.tsx+++ b/apps/web/src/components/settings/MfaView.test.tsx@@ -19,6 +19,7 @@ import { render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";+import { mfaApi } from "@/lib/api";import { MfaView } from "./MfaView";const status = vi.fn();@@ -128,4 +129,57 @@ describe("MfaView", () => {expect(screen.queryByRole("button", { name: /^platform admin$/i })).toBeNull();expect(screen.queryByRole("button", { name: /^admin$/i })).toBeNull();});++ it("enrolment walks begin → secret shown → confirm → recovery codes shown once", async () => {+ status.mockResolvedValue(aStatus());+ vi.mocked(mfaApi.enrollBegin).mockResolvedValue({+ secret: "JBSWY3DPEHPK3PXP",+ otpauth_uri: "otpauth://totp/AiSOC:alice?secret=JBSWY3DPEHPK3PXP",+ });+ vi.mocked(mfaApi.enrollConfirm).mockResolvedValue({+ recovery_codes: ["aaaa-bbbb", "cccc-dddd"],+ });+ const user = userEvent.setup();+ render(<MfaView />);+ await user.click(await screen.findByRole("button", { name: "Set up" }));++ // The shared secret is rendered for the authenticator, then the code+ // the app shows is what confirms — not the secret itself.+ expect(await screen.findByText("JBSWY3DPEHPK3PXP")).toBeInTheDocument();+ await user.type(screen.getByPlaceholderText("123456"), "000000");+ await user.click(screen.getByRole("button", { name: "Confirm" }));++ expect(vi.mocked(mfaApi.enrollConfirm)).toHaveBeenCalledWith("000000");+ expect(await screen.findByText(/Save these recovery codes/)).toBeInTheDocument();+ expect(screen.getByText("aaaa-bbbb")).toBeInTheDocument();+ });++ it("removing the factor requires a current code and sends it", async () => {+ status.mockResolvedValue(aStatus({ enrolled: true, has_totp: true, recovery_codes_remaining: 7 }));+ vi.mocked(mfaApi.disable).mockResolvedValue(undefined as never);+ const user = userEvent.setup();+ render(<MfaView />);++ expect(await screen.findByText(/7 recovery codes left/)).toBeInTheDocument();+ const remove = screen.getByRole("button", { name: "Remove" });+ // No code, no removal: a stolen session cannot strip the factor.+ expect(remove).toBeDisabled();+ await user.type(screen.getByPlaceholderText("Code or recovery code"), "11112222");+ await user.click(remove);+ await waitFor(() => expect(vi.mocked(mfaApi.disable)).toHaveBeenCalledWith("11112222"));+ });++ it("a refused confirmation surfaces an actionable alert, not silence", async () => {+ status.mockResolvedValue(aStatus());+ vi.mocked(mfaApi.enrollBegin).mockResolvedValue({ secret: "S", otpauth_uri: "otpauth://x" });+ vi.mocked(mfaApi.enrollConfirm).mockRejectedValue(new Error("422"));+ const user = userEvent.setup();+ render(<MfaView />);+ await user.click(await screen.findByRole("button", { name: "Set up" }));+ await user.type(await screen.findByPlaceholderText("123456"), "999999");+ await user.click(screen.getByRole("button", { name: "Confirm" }));+ // The component deliberately translates the refusal into what to do+ // about it — the clock hint — rather than echoing a bare status.+ expect(await screen.findByRole("alert")).toHaveTextContent(/That code is not valid/);+ });});diff --git a/apps/web/src/lib/responder/format.test.ts b/apps/web/src/lib/responder/format.test.tsindex f06f850e3..9e18f8ede 100644--- a/apps/web/src/lib/responder/format.test.ts+++ b/apps/web/src/lib/responder/format.test.ts@@ -1,77 +1,103 @@/**- * format — unit tests- * ===================- *- * The mobile responder UI leans on these formatters to keep severity, status- * and time strings consistent across the alert/case surface. They're pure- * functions, so we test them directly without a DOM.- *- * Coverage map:- * - severityTone: every tier in the v1.5 five-tier ladder- * (`critical | high | medium | low | info`) has a tone entry, ranks are- * strictly monotonic, fallback path returns `info` rather than throwing,- * and case-insensitive matching works (some upstreams emit `"Critical"`).- *- * If a refactor accidentally drops a tier — e.g. squashes `critical` back into- * `high` like the pre-v1.5 four-tier ladder — these tests catch it before the- * mobile UI starts rendering blanks for P1 incidents.+ * The responder formatting helpers are pure functions the mobile surface+ * leans on for every list row, so each branch is pinned: the relative-time+ * ladder, the "until" inverse, the five severity tones with their ranks, and+ * the status maps — including the rule the CASE_STATUS comment records, that+ * only the six database statuses exist and anything else falls through to a+ * grey tone that still shows the raw label rather than lying with a known one.*/+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { describe, expect, it } from 'vitest';+import { alertStatusTone, caseStatusTone, formatRelative, formatUntil, severityTone } from './format';-import { severityTone } from './format';+const NOW = new Date('2026-10-12T12:00:00Z');-describe('severityTone', () => {- const tiers = ['critical', 'high', 'medium', 'low', 'info'] as const;-- it.each(tiers)('returns a tone for %s', (tier) => {- const tone = severityTone(tier);- expect(tone.bg).toMatch(/^bg-/);- expect(tone.fg).toMatch(/^text-/);- expect(tone.border).toMatch(/^border-l-/);- expect(tone.glyph).toHaveLength(1);- expect(typeof tone.rank).toBe('number');+beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+});++afterEach(() => {+ vi.useRealTimers();+});++describe('formatRelative', () => {+ it('renders a dash for nothing, and for garbage', () => {+ expect(formatRelative(null)).toBe('—');+ expect(formatRelative(undefined)).toBe('—');+ expect(formatRelative('not-a-date')).toBe('—');+ });++ it('walks the ladder: just now, seconds, minutes, hours, days', () => {+ expect(formatRelative(new Date(NOW.getTime() - 2_000).toISOString())).toBe('just now');+ expect(formatRelative(new Date(NOW.getTime() - 30_000).toISOString())).toBe('30s ago');+ expect(formatRelative(new Date(NOW.getTime() - 5 * 60_000).toISOString())).toBe('5m ago');+ expect(formatRelative(new Date(NOW.getTime() - 3 * 3_600_000).toISOString())).toBe('3h ago');+ expect(formatRelative(new Date(NOW.getTime() - 2 * 86_400_000).toISOString())).toBe('2d ago');+ });++ it('falls back to a calendar date past a week', () => {+ const old = new Date(NOW.getTime() - 30 * 86_400_000).toISOString();+ expect(formatRelative(old)).not.toMatch(/ago$/);+ });++ it('clamps the future to now rather than inventing negative time', () => {+ expect(formatRelative(new Date(NOW.getTime() + 60_000).toISOString())).toBe('just now');+ });+});++describe('formatUntil', () => {+ it('is null for nothing, garbage, and the past', () => {+ expect(formatUntil(null)).toBeNull();+ expect(formatUntil('not-a-date')).toBeNull();+ expect(formatUntil(new Date(NOW.getTime() - 1_000).toISOString())).toBeNull();+ });++ it('renders minutes, hours and days ahead', () => {+ expect(formatUntil(new Date(NOW.getTime() + 25 * 60_000).toISOString())).toBe('25m');+ expect(formatUntil(new Date(NOW.getTime() + 5 * 3_600_000).toISOString())).toBe('5h');+ expect(formatUntil(new Date(NOW.getTime() + 3 * 86_400_000).toISOString())).toBe('3d');});+});- it('assigns strictly monotonic ranks across the five-tier ladder', () => {- const ranks = tiers.map((t) => severityTone(t).rank);- // critical = 4, high = 3, medium = 2, low = 1, info = 0 — so the list as- // ordered should be strictly descending.- expect(ranks).toEqual([4, 3, 2, 1, 0]);+describe('severityTone', () => {+ it('ranks the five tiers in order', () => {+ const ranks = ['info', 'low', 'medium', 'high', 'critical'].map((s) => severityTone(s).rank);+ expect(ranks).toEqual([0, 1, 2, 3, 4]);});- it('falls back to the info tone for unknown severities', () => {- const info = severityTone('info');- const unknown = severityTone('not-a-real-severity');- expect(unknown).toEqual(info);+ it('is case-insensitive and falls back to info for the unknown', () => {+ expect(severityTone('CRITICAL').glyph).toBe('C');+ expect(severityTone('made-up').rank).toBe(0);+ expect(severityTone(null).rank).toBe(0);});+});- it('falls back to the info tone for nullish severities', () => {- const info = severityTone('info');- expect(severityTone(null)).toEqual(info);- expect(severityTone(undefined)).toEqual(info);- expect(severityTone('')).toEqual(info);+describe('alertStatusTone', () => {+ it('labels the known statuses', () => {+ expect(alertStatusTone('new').label).toBe('New');+ expect(alertStatusTone('false_positive').label).toBe('FP');+ expect(alertStatusTone('snoozed').label).toBe('Snoozed');});- it('is case-insensitive (some upstreams emit Title-Case)', () => {- expect(severityTone('Critical')).toEqual(severityTone('critical'));- expect(severityTone('HIGH')).toEqual(severityTone('high'));- expect(severityTone('Medium')).toEqual(severityTone('medium'));+ it('an unknown status keeps its own name in grey rather than borrowing a known label', () => {+ const tone = alertStatusTone('quarantined');+ expect(tone.label).toBe('quarantined');+ expect(tone.bg).toContain('slate');});+});- it('uses distinct background colors for each tier', () => {- // Catches a refactor where someone copy-pastes a row but forgets to- // update the color — easy to miss in code review.- const bgs = new Set(tiers.map((t) => severityTone(t).bg));- expect(bgs.size).toBe(tiers.length);+describe('caseStatusTone', () => {+ it('covers exactly the six statuses the database permits', () => {+ for (const s of ['new', 'triaged', 'investigating', 'contained', 'resolved', 'closed']) {+ expect(caseStatusTone(s).label.toLowerCase()).toBe(s);+ }});- it('uses the red palette for critical (P1 wallboard contract)', () => {- // The wallboard relies on `red` being the unambiguous P1 signal. If a- // theme refactor recolors `critical` to e.g. magenta, this catches it.- const crit = severityTone('critical');- expect(crit.bg).toContain('red');- expect(crit.fg).toContain('red');- expect(crit.border).toContain('red');+ it('the statuses nothing can write fall through honestly', () => {+ // `open` and `pending` were map entries nothing could match; the fix was+ // to delete them, so they must render as themselves in grey.+ expect(caseStatusTone('open').label).toBe('open');+ expect(caseStatusTone('pending').bg).toContain('slate');});});diff --git a/infra/helm/aisoc/templates/core-platform.yaml b/infra/helm/aisoc/templates/core-platform.yamlindex e5d7feb1e..a85cb763a 100644--- a/infra/helm/aisoc/templates/core-platform.yaml+++ b/infra/helm/aisoc/templates/core-platform.yaml@@ -51,8 +51,17 @@ spec:checksum/litellm-config: {{ .Values.llmGateway.config | sha256sum }}spec:serviceAccountName: {{ include "aisoc.serviceAccountName" . }}+ # None of these processes talks to the Kubernetes API.+ automountServiceAccountToken: false+ securityContext:+ seccompProfile:+ type: RuntimeDefaultcontainers:- name: litellm+ securityContext:+ allowPrivilegeEscalation: false+ capabilities:+ drop: [\"ALL\"]image: "{{ .Values.llmGateway.image.repository }}:{{ .Values.llmGateway.image.tag }}"imagePullPolicy: {{ .Values.llmGateway.image.pullPolicy }}args: ["--config", "/etc/litellm/config.yaml", "--port", "4000"]@@ -84,6 +93,13 @@ spec:periodSeconds: 10resources:{{- toYaml .Values.llmGateway.resources | nindent 12 }}+ # The args above name /etc/litellm/config.yaml; without this mount+ # the gateway boots into a config that does not exist and the probe+ # below reports a live process that fails every completion.+ volumeMounts:+ - name: config+ mountPath: /etc/litellm+ readOnly: truevolumes:- name: configconfigMap:@@ -138,8 +154,17 @@ spec:app.kubernetes.io/component: ollamaspec:serviceAccountName: {{ include "aisoc.serviceAccountName" . }}+ # None of these processes talks to the Kubernetes API.+ automountServiceAccountToken: false+ securityContext:+ seccompProfile:+ type: RuntimeDefaultcontainers:- name: ollama+ securityContext:+ allowPrivilegeEscalation: false+ capabilities:+ drop: [\"ALL\"]image: "{{ .Values.ollama.image.repository }}:{{ .Values.ollama.image.tag }}"imagePullPolicy: {{ .Values.ollama.image.pullPolicy }}ports:@@ -228,8 +253,17 @@ spec:app.kubernetes.io/component: qdrantspec:serviceAccountName: {{ include "aisoc.serviceAccountName" . }}+ # None of these processes talks to the Kubernetes API.+ automountServiceAccountToken: false+ securityContext:+ seccompProfile:+ type: RuntimeDefaultcontainers:- name: qdrant+ securityContext:+ allowPrivilegeEscalation: false+ capabilities:+ drop: [\"ALL\"]image: "{{ .Values.qdrant.image.repository }}:{{ .Values.qdrant.image.tag }}"imagePullPolicy: {{ .Values.qdrant.image.pullPolicy }}ports:diff --git a/infra/helm/aisoc/templates/mcp-deployment.yaml b/infra/helm/aisoc/templates/mcp-deployment.yamlindex d0df3899c..bb9c55d50 100644--- a/infra/helm/aisoc/templates/mcp-deployment.yaml+++ b/infra/helm/aisoc/templates/mcp-deployment.yaml@@ -32,6 +32,11 @@ spec:{{- include "aisoc.selectorLabels" . | nindent 8 }}app.kubernetes.io/component: mcpspec:+ # The MCP server talks to the AiSOC API, never the Kubernetes API.+ automountServiceAccountToken: false+ securityContext:+ seccompProfile:+ type: RuntimeDefaultcontainers:- name: mcpimage: "{{ required "mcp.image.repository must be set to install the MCP server; no image is published for it yet" .Values.mcp.image.repository }}:{{ .Values.mcp.image.tag | default .Chart.AppVersion }}"diff --git a/scripts/check_route_auth.py b/scripts/check_route_auth.pyindex 573246b46..ef2b0b465 100644--- a/scripts/check_route_auth.py+++ b/scripts/check_route_auth.py@@ -110,6 +110,10 @@ PUBLIC_ROUTES: dict[str, str] = {# -- Prometheus scrape endpoints, gated by METRICS_TOKEN in the handler ---"services/api/app/main.py::metrics": "Prometheus scrape; refuses without METRICS_TOKEN outside a development environment","services/fusion/app/api/router.py::metrics": "Prometheus scrape of worker counters; no tenant data, numeric series only",+ "services/fusion/app/api/router.py::scale_hint": (+ "lag-based autoscaling signal (depth 4.4): a cluster scaler scrapes it on the same footing as /metrics — "+ "a lag count and a replica suggestion, no tenant data. AiSOC publishes it and does not act on it (ADR-0012)"+ ),# -- sign-in: the request that establishes a credential cannot carry one --"services/api/app/api/v1/endpoints/auth.py::login": "the sign-in request itself; it is what mints the credential","services/api/app/api/v1/endpoints/auth.py::sso_status": (@@ -163,6 +167,13 @@ PUBLIC_ROUTES: dict[str, str] = {#: Routes whose credential is verified inside the handler. ``(verifier, reason)``#: — the verifier must still be called or the exemption lapses.IN_BAND_CREDENTIAL_ROUTES: dict[str, tuple[str, str]] = {+ "services/agents/app/api/playbooks.py::answer_verification": (+ "resume_verification",+ "the signed answer link is the whole credential (depth 5.4): resume_verification recomputes the HMAC over "+ "(token, answer, stage) with hmac.compare_digest and refuses with one sentence for every failure shape, so "+ "the route is not an oracle for whether a token was ever valid. The person clicking holds no AiSOC session "+ "by design — the prompt went to chat or email",+ ),"services/slack-bot/app/main.py::slack_events": ("SlackRequestHandler","Slack Bolt verifies the request signature against SLACK_SIGNING_SECRET before the handler sees the body",diff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.pyindex 9eb21f5a7..468bb9a6d 100644--- a/scripts/check_tenant_query_predicates.py+++ b/scripts/check_tenant_query_predicates.py@@ -379,6 +379,53 @@ RATCHET: dict[str, str] = {"SQL is seed_tenant_catalog's INSERT INTO permissions/roles/""role_permissions/user_roles, each bound to :t"),+ # ── the 2026-10-12 merge train (depth 5.4, 9.4, 4.3) ────────────────────+ "services/agents/app/playbook/pause.py::find_verification_by_token::aisoc_playbook_pauses": (+ "the signed answer link is the whole credential, exactly the find_wait_by_token shape above: "+ "the person clicking holds no AiSOC session, so there is no tenant to filter by. The HMAC "+ "covers (token, answer, stage) so a guessed token still answers nothing, and "+ "`kind = 'verification'` is in the predicate so an approval cannot be discharged this way"+ ),+ "services/agents/app/playbook/pause.py::due_verifications::aisoc_playbook_pauses": (+ "the verification sweeper asks 'which prompts passed their stage deadline', the same "+ "discover-a-working-set shape as due_waits beside it; escalation then acts on one row at a "+ "time with the tenant read off the row"+ ),+ "services/api/app/api/v1/endpoints/war_rooms.py::channel_decision::aisoc_case_war_rooms": (+ "the bot presents the shared service token and a war-room id; it holds no tenant and the "+ "request body deliberately has no tenant field to get wrong. The handler reads the row by "+ "id, binds set_rls_context to the row's own tenant before acting, and refuses without the "+ "token — the tenant comes from the row the bot named, never from the caller"+ ),+ "services/api/app/services/lake_query_runner.py::claim_statement::lake_query_jobs": (+ "the claim is one conditional UPDATE by job id where status = 'queued' — a worker claiming "+ "work enqueued by tenant-scoped routes, the same shape as approval_expiry.run_once. The "+ "routes that create and read jobs bind the tenant; the runner executes whichever replica won"+ ),+ "services/api/app/services/lake_query_runner.py::_record_progress::lake_query_jobs": (+ "progress lands on the claimed job by id; the claim above is what decided whose job it is"+ ),+ "services/api/app/services/lake_query_runner.py::_finish::lake_query_jobs": (+ "terminal state lands on the claimed job by id, guarded so a finished job is never revived; "+ "same claim-then-act shape as _record_progress"+ ),+ "services/api/app/services/lake_query_runner.py::list_stuck_jobs::lake_query_jobs": (+ "the stuck sweep asks 'which running jobs lost their runner', tenant-unbound by the same "+ "discover-a-working-set reasoning as due_deliveries; it only moves jobs to a terminal state"+ ),+ "services/api/app/services/war_room.py::sync_war_room::aisoc_case_war_rooms": (+ "the sweep is a pure function of the case row: it reads the room by id handed to it by the "+ "worker's cross-tenant discovery below, and every post it writes is keyed to that room; the "+ "analyst-facing routes in endpoints/war_rooms.py all filter on the session tenant"+ ),+ "services/api/app/services/war_room.py::sync_war_room::aisoc_war_room_posts": (+ "the posted-keys read is scoped to one war_room_id — the room decides the tenant, and the "+ "unique constraint on (war_room_id, event_key) is what makes the sweep idempotent"+ ),+ "services/api/app/workers/war_room_sync.py::<module>::aisoc_case_war_rooms": (+ "the sweep worker's 'which rooms are open' discovery, the same cross-tenant working-set "+ "shape as report_scheduler.run_once; sync_war_room then handles one room at a time"+ ),}#: Raising this is a deliberate act with a diff attached. Appending to RATCHETdiff --git a/scripts/integration/spine_test.py b/scripts/integration/spine_test.pyindex 6b47d8fa5..583e7ff8e 100644--- a/scripts/integration/spine_test.py+++ b/scripts/integration/spine_test.py@@ -291,9 +291,14 @@ async def full_spine_test() -> None:# fingerprint of the original telemetry, not a bare title.alert = await get_alert_titled(client, title)assert alert is not None- for field, expected in [("severity", "critical"), ("status", "new")]:- if alert.get(field) != expected:- raise SystemExit(f"alert.{field}={alert.get(field)!r}, expected {expected!r}")+ if alert.get("severity") != "critical":+ raise SystemExit(f"alert.severity={alert.get('severity')!r}, expected 'critical'")+ # 'new' is the state the row is born in; 'triaged' means auto-triage+ # already reached it, which depth 4.4's per-entity concurrency now+ # routinely manages inside this test's own window. Both prove the+ # spine delivered the alert; anything else is a real wrong state.+ if alert.get("status") not in ("new", "triaged"):+ raise SystemExit(f"alert.status={alert.get('status')!r}, expected 'new' or 'triaged'")techniques = alert.get("mitre_techniques") or []if "T1003" not in techniques:raise SystemExit(f"ATT&CK enrichment lost in transit: {techniques}")diff --git a/services/actions/tests/test_mailbox_remediation.py b/services/actions/tests/test_mailbox_remediation.pyindex b1b6d3ebf..87e281023 100644--- a/services/actions/tests/test_mailbox_remediation.py+++ b/services/actions/tests/test_mailbox_remediation.py@@ -291,6 +291,7 @@ class TestTheRequestShapeIsWhatTheVendorDocuments:return_value=httpx.Response(200, json=GMAIL_LIST))client = factories._gmail_client(GMAIL_CREDENTIALS)+ assert client is not None, "the factory refused credentials the fixture declares complete"# Minting a token needs a real RSA key; the search itself is what is# under test, so the token cache is primed directly.client._tokens[MAILBOX] = ("unit-test-token", 2**31)@@ -536,7 +537,9 @@ class TestVendorSelection:for capability in STATE_CHANGING_VERBS:executor = registry.get_executor(vendor, capability)assert executor is not None- assert executor._vendor_pin == vendor # noqa: SLF001+ # The pin is the concrete adapter's own attribute; the registry's+ # base type deliberately does not declare it.+ assert executor._vendor_pin == vendor # type: ignore[attr-defined] # noqa: SLF001def test_each_adapters_strip_list_is_its_factorys_key_set(self) -> None:"""The hand-copied list is the shape that let a 'dry run' reach production Splunk."""@@ -548,7 +551,8 @@ class TestVendorSelection:for capability in STATE_CHANGING_VERBS:executor = registry.get_executor(vendor, capability)assert executor is not None- assert set(executor._credential_keys) == expected[vendor] # noqa: SLF001+ # Same: an adapter internal asserted on purpose, absent from the base type.+ assert set(executor._credential_keys) == expected[vendor] # type: ignore[attr-defined] # noqa: SLF001@pytest.mark.parametrize(("vendor", "factory", "credentials"),diff --git a/services/agents/app/playbook/engine.py b/services/agents/app/playbook/engine.pyindex be3401e27..6f090fe56 100644--- a/services/agents/app/playbook/engine.py+++ b/services/agents/app/playbook/engine.py@@ -1755,6 +1755,8 @@ def _verification_ttl(step: PlaybookStep) -> float:if raw is not None:return float(raw)except (TypeError, ValueError):+ # An unparseable author value falls through to the derived default+ # below — a wrong TTL must not stop the question being asked.passtotal = verification.user_stage_seconds() + verification.manager_stage_seconds()return max(DEFAULT_VERIFICATION_TTL_HOURS, (total / 3600.0) * 2)diff --git a/services/api/app/api/v1/endpoints/effective_permissions.py b/services/api/app/api/v1/endpoints/effective_permissions.pyindex 3c73d28a9..db837a334 100644--- a/services/api/app/api/v1/endpoints/effective_permissions.py+++ b/services/api/app/api/v1/endpoints/effective_permissions.py@@ -114,8 +114,10 @@ async def _record_snapshot(await db.rollback()logger.warning("effective_permissions.snapshot_not_recorded provider=%s: %s",- provider,- str(exc).replace("\n", " ")[:200],+ # Caller-influenced; sanitised inline because the taint tracker+ # does not follow a helper (the py/log-injection house pattern).+ str(provider).replace("\r", "").replace("\n", " ")[:64],+ str(exc).replace("\r", "").replace("\n", " ")[:200],)diff --git a/services/api/app/services/lake_query_runner.py b/services/api/app/services/lake_query_runner.pyindex 7fb878ec3..442059709 100644--- a/services/api/app/services/lake_query_runner.py+++ b/services/api/app/services/lake_query_runner.py@@ -232,7 +232,7 @@ async def run_job(finally:poller.cancel()with contextlib.suppress(asyncio.CancelledError):- await poller+ _ = await poller # the await is the point: let the cancellation settleawait _finish(session_factory,diff --git a/services/api/migrations/114_lake_query_jobs.sql b/services/api/migrations/114_lake_query_jobs.sqlindex 8c00b3f92..85f4101dc 100644--- a/services/api/migrations/114_lake_query_jobs.sql+++ b/services/api/migrations/114_lake_query_jobs.sql@@ -95,10 +95,15 @@ BEGINEXECUTE 'ALTER TABLE lake_query_jobs ENABLE ROW LEVEL SECURITY';EXECUTE 'ALTER TABLE lake_query_jobs FORCE ROW LEVEL SECURITY';EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON lake_query_jobs';+ -- The unbound-session arm in WITH CHECK mirrors USING, and is the same+ -- shape 079/081/104/117/118 use: the claim runner and the stuck sweep are+ -- GUC-less worker sessions whose UPDATEs re-check the new row, so without+ -- it no job could ever be claimed or finished under the runtime role —+ -- the live suite caught exactly that once its DSN moved off the owner.EXECUTE'CREATE POLICY tenant_isolation ON lake_query_jobs ''USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '- 'WITH CHECK (tenant_id = current_tenant_id())';+ 'WITH CHECK (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)';IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THENEXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON lake_query_jobs TO aisoc_app';diff --git a/services/api/tests/test_lake_cold_query.py b/services/api/tests/test_lake_cold_query.pyindex afa2155f3..485d25ffa 100644--- a/services/api/tests/test_lake_cold_query.py+++ b/services/api/tests/test_lake_cold_query.py@@ -13,6 +13,8 @@ that.from __future__ import annotations+from typing import Any+import pytestfrom app.services.lake_cold_query import (COLD_VOLUME_NAMES,@@ -155,7 +157,7 @@ def test_zero_cold_bytes_with_a_price_is_zero_not_none(monkeypatch):def _estimate(**overrides) -> ScanEstimate:- base = {+ base: dict[str, Any] = {"estimated_rows": 1_000,"estimated_parts": 3,"estimated_bytes": 2_000,diff --git a/services/api/tests/test_taxii_projection.py b/services/api/tests/test_taxii_projection.pyindex 2fc8dec79..060f3b0bf 100644--- a/services/api/tests/test_taxii_projection.py+++ b/services/api/tests/test_taxii_projection.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport uuidfrom datetime import UTC, datetime, timedelta+from typing import Anyimport pytestfrom app.services.taxii import (@@ -40,7 +41,7 @@ NOW = datetime(2026, 10, 11, 9, 0, 0, tzinfo=UTC)def row(**overrides) -> IndicatorRow:- base = {+ base: dict[str, Any] = {"id": uuid.UUID("11111111-1111-1111-1111-111111111111"),"ioc_type": "domain","value": "evil.example.com",diff --git a/services/ingest/internal/otlp/receiver.go b/services/ingest/internal/otlp/receiver.goindex 33a6a16cc..db0f2d5c1 100644--- a/services/ingest/internal/otlp/receiver.go+++ b/services/ingest/internal/otlp/receiver.go@@ -398,6 +398,18 @@ func assign(payload map[string]any, key string, value any) {cur := payloadfor i, p := range parts {if i == len(parts)-1 {+ if existing, isMap := cur[p].(map[string]any); isMap {+ if _, incomingIsMap := value.(map[string]any); !incomingIsMap {+ // The mirror of the scalar-in-the-way case below, which+ // map iteration order decides: `service.name` arrived+ // first and built a map, and the scalar `service` would+ // overwrite it, silently dropping the attribute. Demote+ // the map's entries to their literal dotted names first —+ // the exact payload the opposite arrival order produces,+ // so the outcome stops depending on iteration order.+ flattenInto(payload, strings.Join(parts, "."), existing)+ }+ }cur[p] = valuereturn}@@ -417,6 +429,21 @@ func assign(payload map[string]any, key string, value any) {}}+// flattenInto writes a nested map's leaves under their literal dotted names,+// never overwriting a key that already exists.+func flattenInto(payload map[string]any, prefix string, m map[string]any) {+ for k, v := range m {+ full := prefix + "." + k+ if sub, ok := v.(map[string]any); ok {+ flattenInto(payload, full, sub)+ continue+ }+ if _, occupied := payload[full]; !occupied {+ payload[full] = v+ }+ }+}+func attributesToMap(attrs []*commonpb.KeyValue) map[string]any {if len(attrs) == 0 {return nildiff --git a/services/teams-bot/app/war_room.py b/services/teams-bot/app/war_room.pyindex f43ff1232..618ea67be 100644--- a/services/teams-bot/app/war_room.py+++ b/services/teams-bot/app/war_room.py@@ -259,6 +259,14 @@ async def post_to_war_room()tenant, client_id, secret, team_id = configchannel_id = require_channel_id(body.channel_id)+ # The taint tracker does not follow that guard across the function+ # boundary, so the same fullmatch is restated here, in the frame that+ # builds the URL: the value interpolated below is the regex's own match,+ # not the request's string.+ matched = _CHANNEL_ID_RE.fullmatch(channel_id)+ if matched is None: # pragma: no cover — require_channel_id already raised+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="channel_id is not a Microsoft Graph channel id.")+ channel_id = matched.group(0)async with httpx.AsyncClient(timeout=_TIMEOUT) as http:token = await _graph_token(tenant, client_id, secret, http)diff --git a/tests/test_load_harness_realistic_mix.py b/tests/test_load_harness_realistic_mix.pyindex 2908210b2..29d874f6a 100644--- a/tests/test_load_harness_realistic_mix.py+++ b/tests/test_load_harness_realistic_mix.py@@ -32,6 +32,10 @@ PRODUCER_GO = REPO_ROOT / "services" / "demo-producer" / "main.go"def _load(name: str, relative: str):spec = importlib.util.spec_from_file_location(name, REPO_ROOT / relative)+ # `spec_from_file_location` is `ModuleSpec | None`, and a None here means+ # the harness file moved — a sentence beats an AttributeError three lines+ # down, and the narrowing is what lets mypy read the rest.+ assert spec is not None and spec.loader is not None, f"no loadable module at {relative}"module = importlib.util.module_from_spec(spec)sys.modules[name] = modulespec.loader.exec_module(module)