Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(phase-8): LLMOps — prompt registry, model pins, response cache, structured output (#433)

Beenu Aroraa2c1b991eb17
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0fcf09718..a3d4b5b55 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -212,6 +212,10 @@ jobs:
# commit the result.
- name: Verify connector count is in sync (Phase 1.1)
run: python scripts/generate_connector_count.py --check
+ # Phase 8 — a production prompt cannot change without a version bump +
+ # lock regeneration (the signal that must trigger an eval re-grade).
+ - name: Verify prompt lock is current (Phase 8)
+ run: python scripts/check_prompt_lock.py
# Phase 2.3 — every `job_name` in `infra/docker/prometheus.yml` must
# point at a hostname:port pair where the service actually exposes
# `/metrics`. Before this gate landed, four of five scrape jobs were
@@ -327,6 +331,7 @@ jobs:
tests/test_privacy_redactor.py \
tests/test_cost_governor.py \
tests/test_model_router.py \
+ tests/test_llm_ops.py \
-v --tb=short
# ──────────────────────────────────────────────
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 55eaece44..14950edfa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Phase 8 — LLMOps: prompt registry, model pins, response cache, structured-output validation.** A coherent `services/agents/app/llm/` LLMOps layer, all dependency-light and gated. (1) **Prompt registry** (`prompt_registry.py`) — every production prompt is a named, versioned, sha256-hashed artifact; the committed `prompts.lock.json` pins version→hash, and `scripts/check_prompt_lock.py --check` (wired into the CI lint job) fails when a prompt's text changes without a version bump + lock regeneration. This makes the `AGENTS.md` "prompt change ⇒ re-grade the eval harness" rule *enforceable* — you can no longer edit a prompt silently. (2) **Model pins + provider fallback** (`model_pins.py`) — logical roles pinned to concrete models with ordered fallback chains that ALWAYS terminate in the deterministic tier (env-overridable primaries, but the deterministic floor is gate-enforced), replacing the scattered `os.getenv("...", "gpt-4o-mini")` defaults. (3) **Content-addressed response cache** (`response_cache.py`) — keyed on sha256(model+prompt+input) with field separation and LRU eviction; safe under the determinism contract (a hit is byte-identical). (4) **Fail-closed structured-output validation** (`structured_output.py`) — strips code fences/prose, parses JSON, validates against a caller schema, and on ANY failure returns a deterministic fallback rather than propagating a half-parsed object into an autonomy decision. 15 tests (`services/agents/tests/test_llm_ops.py`, appended to the CI agents gate). Migration of the inline agent prompts to `registry.get()` is tracked as 8b. Doc: `apps/docs/docs/concepts/llmops.md`.
- **Phase 7a — unified multi-model router with tier attribution + a determinism contract.** The reality audit confirmed the knowledge graph is already built at ingest (v8 T1.1, `services/ingest/internal/graph/`); the genuine Phase 7 delta was the *model router*. Before it, the deterministic→LLM fallback was reimplemented independently in NL query, playbook drafting, explain, copilot, and each sub-agent — no single audit point for which model answered or why. New `services/agents/app/routing/model_router.py` is that place: a `ModelRouter` that escalates deterministic → ML → LLM only when the cheaper tier is under-confident, and attributes every decision (`tier`, `model_used`, `attribution` trail, `tiers_considered`, `escalation_blocked_reason`). It **never silently uses the LLM** — a skipped or blocked LLM tier (no key, air-gap, deterministic mode, governor circuit open, or a tier error) is always recorded. Introduces the canonical **`AISOC_DETERMINISTIC`** flag and composes with the existing `CostGovernor` circuit breaker: either one forces deterministic-only, in which case the router is reproducible (same input → identical decision). 12 tests (`services/agents/tests/test_model_router.py`, appended to the CI agents gate) prove tier selection, attribution, the no-silent-LLM property, graceful LLM-failure degradation, and the determinism contract. Doc: `apps/docs/docs/concepts/model-router.md`. Remaining Phase 7 enrichments (posture collection, effective-permissions snapshot loader, bi-temporal validity, fusion-time ContextBundle) are tracked as 7b+ in `docs/audit/PROGRESS.md`.
- **Phase 6 — performance + cost, both gated.** Two cheap, non-flaky gates in a new `.github/workflows/perf.yml`. (1) **Throughput** — `scripts/perf/throughput_harness.py` runs the *real* fusion hot path (`promote_normalized_event`) over a deterministic 20k-event synthetic corpus and reports events/sec + p50/p95/p99 per-event latency (measured ~250k eps on commodity hardware). The gate asserts a **generous regression floor** (1,000 eps — a >200× margin) so it fires only on a catastrophic regression such as an I/O call slipping onto the hot path, never on shared-runner jitter; it is explicitly a regression floor, not a production SLO. (2) **Cost** — `scripts/storage_cost_model.py` is a deterministic tiered-storage $/TB model (hot ClickHouse block 30d / warm object 60d / cold archive 275d, 8× ZSTD); the committed worked example (`docs/decisions/storage-cost-model.json`: ≈ $902/mo and ≈ $30/raw-TB at 1 TB/day) is drift-gated by `--check`, so the number can never silently diverge from the rate card. Rate-card values are labelled reference list prices to verify per provider/region — the value is the methodology, not the exact dollars. `docs/decisions/0005-storage-consolidation.md` (ADR) records the three-tier decision (keep ClickHouse-only hot; do not add a second hot engine) and cites the gated model.
- **Phase 5 — data spine correctness: schema registry + dead-letter queue + lineage.** The reality audit's load-bearing gap: the fusion consumer logged a warning and **silently dropped** any malformed message — silent data loss. Now every message is schema-validated against a versioned envelope registry (`services/fusion/app/services/event_schema.py`: `aisoc.raw_events` and `aisoc.alerts.raw`, each pinned to `v1`, with a drift-guard test so the wire contract can't move unnoticed) *before* the promoter sees it. Anything that fails — non-object payload, unknown `schema_version`, missing `ocsf_event`, non-UUID tenant, or a RawAlert that fails deep Pydantic validation — is routed to a **fail-soft dead-letter queue** (`services/fusion/app/services/dlq.py`: `LoggingDLQ` default, `InMemoryDLQ` for tests, `KafkaDLQ` republishing to `aisoc.alerts.dlq`) with its reason, schema version, source-event lineage, and a truncated payload, instead of vanishing. `safe_record` guarantees a DLQ that itself throws never crashes the consumer. Each processed alert logs `fusion.lineage` (source event id + schema version). 21 new tests (`test_event_schema.py`, `test_dlq.py`, `test_consumer_dlq.py`) prove a valid event is processed with an empty DLQ, every poison shape is captured (not dropped), and a failing DLQ sink doesn't crash the consumer; full fusion suite 92/92 at 59% coverage (floor 48). Idempotency (AlertSink dedup fingerprint, Phase 3.1) and event-time watermarking are already present; backfill/replay-from-offset is tracked as 5b in `docs/audit/PROGRESS.md`.
diff --git a/ROADMAP.md b/ROADMAP.md
index 46b73f6d9..b5c236709 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -30,7 +30,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- [x] Phase 5 — Data spine correctness (versioned event-schema registry + dead-letter queue + source-event lineage in the fusion consumer; idempotency via AlertSink dedup + event-time watermarking; backfill/replay-from-offset tracked as 5b)
- [x] Phase 6 — Performance + cost (fusion hot-path throughput harness with a generous regression-floor gate; deterministic storage $/TB cost model + drift gate; storage-consolidation ADR-0005)
- [x] Phase 7 — Ingest-time graph + multi-model router — **graph-at-ingest already shipped** (v8 T1.1, `services/ingest/internal/graph/`); **7a landed**: unified deterministic→ML→LLM router with tier attribution + the `AISOC_DETERMINISTIC` determinism contract (`services/agents/app/routing/model_router.py`, gated). 7b+ (posture collection, effective-permissions snapshot loader, bi-temporal valid_from/valid_to, fusion-time ContextBundle) tracked in `docs/audit/PROGRESS.md`
-- [ ] Phase 8 — LLMOps (prompt registry, model pinning, provider fallback, response caching, structured-output validation)
+- [x] Phase 8 — LLMOps (version+hash-pinned prompt registry with a CI drift gate; model pins + deterministic-terminated provider-fallback chains; content-addressed response cache; fail-closed structured-output validation)
- [ ] Phase 9 — Autonomy safety (rollback, post-action verification, dry-run default, break-glass, approval SLA, scorecard)
- [ ] Phase 10 — Connector + content quality (conformance suite, published matrix, detection lifecycle)
- [ ] Phase 11 — API / SDK / release engineering (oasdiff, SDK contract drift, versioning, release discipline)
diff --git a/apps/docs/docs/concepts/llmops.md b/apps/docs/docs/concepts/llmops.md
new file mode 100644
index 000000000..6a4871624
--- /dev/null
+++ b/apps/docs/docs/concepts/llmops.md
@@ -0,0 +1,50 @@
+# LLMOps
+
+AiSOC treats the LLM as a governed dependency, not a black box. Four small,
+dependency-light pieces in `services/agents/app/llm/` make LLM behaviour
+versioned, bounded, cached, and fail-closed.
+
+## Prompt registry (versioned + hash-pinned)
+
+Every production prompt is a **named, versioned, content-hashed artifact** in
+`prompt_registry.py`. The committed `prompts.lock.json` pins each prompt's
+version → sha256. The CI lint job runs `scripts/check_prompt_lock.py --check`,
+which **fails if a prompt's text changed without a version bump**.
+
+Why it matters: `AGENTS.md` requires that any change to agent prompts re-grade
+the eval harness. That rule is only enforceable if prompt edits are visible —
+the lock makes a silent one-word tweak impossible. To change a prompt you must
+bump its version and regenerate the lock, which is exactly the moment to
+re-run the eval.
+
+## Model pins + provider fallback
+
+`model_pins.py` pins each logical role (triage, recon, summary) to a concrete
+model and an ordered fallback chain. Primaries are overridable per operator via
+`AISOC_MODEL_PIN_<ROLE>`, but **every chain is gate-enforced to terminate in the
+deterministic tier** — so there is always a defined, non-silent floor when a
+provider is unavailable. This replaces the scattered `os.getenv(..., "gpt-4o-mini")`
+defaults that could drift per module.
+
+## Content-addressed response cache
+
+`response_cache.py` keys responses on `sha256(model + prompt + input)` with
+field separation and LRU eviction. It complements the cost governor: the
+governor dedups identical *alerts*; the cache dedups identical *LLM calls*. A
+cache hit is byte-identical to the model's original reply, so it is safe under
+the determinism contract.
+
+## Fail-closed structured-output validation
+
+`structured_output.py` is the single parser for LLM structured replies. It
+strips ``` fences and prose, parses JSON, and validates against a caller-supplied
+schema. On **any** failure it returns a deterministic fallback rather than a
+half-parsed object — because feeding a partially-parsed structured output into
+an autonomy decision or a ledger entry is worse than failing.
+
+## Gate
+
+`services/agents/tests/test_llm_ops.py` proves the lock catches un-versioned
+prompt edits, structured-output parsing fails closed, every model-pin chain has
+a deterministic floor, and the response cache is content-addressed with correct
+eviction.
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 4b3e54a1b..00874e820 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -26,6 +26,7 @@ const sidebars: SidebarsConfig = {
"concepts/live-actions",
"concepts/automation-maturity",
"concepts/model-router",
+ "concepts/llmops",
],
},
{
diff --git a/scripts/check_prompt_lock.py b/scripts/check_prompt_lock.py
new file mode 100644
index 000000000..688135710
--- /dev/null
+++ b/scripts/check_prompt_lock.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python3
+"""Prompt-lock drift gate (Phase 8 — LLMOps).
+
+Fails CI when a production prompt's text changed without a version bump + lock
+regeneration. This is what makes the AGENTS.md "prompt change ⇒ re-grade the
+eval harness" rule enforceable: you cannot quietly edit a prompt.
+
+Usage:
+ python3 scripts/check_prompt_lock.py # fail on drift
+ python3 scripts/check_prompt_lock.py --write # regenerate the lock
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "services" / "agents"))
+
+from app.llm.prompt_registry import default_registry, load_lock, write_lock # noqa: E402
+
+
+def main() -> int:
+ registry = default_registry()
+ if "--write" in sys.argv:
+ write_lock(registry)
+ print("prompt lock regenerated")
+ return 0
+
+ drifts = registry.verify_against_lock(load_lock())
+ if drifts:
+ print("ERROR: prompt lock drift detected:", file=sys.stderr)
+ for d in drifts:
+ print(f" - {d}", file=sys.stderr)
+ print(
+ "\nA production prompt changed. Bump its version in "
+ "services/agents/app/llm/prompt_registry.py, re-grade the eval harness, "
+ "then run: python3 scripts/check_prompt_lock.py --write",
+ file=sys.stderr,
+ )
+ return 1
+ print(f"OK: prompt lock current ({len(registry.names())} prompts)")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/services/agents/app/llm/model_pins.py b/services/agents/app/llm/model_pins.py
new file mode 100644
index 000000000..93df06999
--- /dev/null
+++ b/services/agents/app/llm/model_pins.py
@@ -0,0 +1,78 @@
+"""Model pinning + provider fallback chain (Phase 8 — LLMOps).
+
+Before this, the model name came from scattered `os.getenv("AISOC_LLM_MODEL",
+"gpt-4o-mini")` / `os.getenv("OPENAI_MODEL", ...)` calls — a silent default that
+could drift per module and had no notion of a fallback provider. This module
+pins each logical role to a concrete model and an ordered provider fallback
+chain that ALWAYS terminates in the deterministic tier, so the system has a
+defined, non-silent degradation path when the primary provider is unavailable.
+
+Pins are overridable by env (operators pin their own models) but the *shape* —
+every chain ending in `deterministic` — is enforced by a gate so a
+mis-configuration can't leave the system with no floor.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass, field
+
+DETERMINISTIC = "deterministic"
+
+
+@dataclass(frozen=True)
+class ModelPin:
+ """A logical role pinned to a primary model + an ordered fallback chain."""
+
+ role: str
+ primary_model: str
+ fallback_chain: list[str] = field(default_factory=list)
+
+ def resolved_chain(self) -> list[str]:
+ """primary → fallbacks, guaranteed to end in the deterministic tier."""
+ chain = [self.primary_model, *self.fallback_chain]
+ if chain[-1] != DETERMINISTIC:
+ chain.append(DETERMINISTIC)
+ return chain
+
+
+# Shipped pins. Model IDs are the pinned defaults; override via env
+# (AISOC_MODEL_PIN_<ROLE>, e.g. AISOC_MODEL_PIN_TRIAGE). Every chain terminates
+# in `deterministic`.
+_DEFAULT_PINS: dict[str, ModelPin] = {
+ "triage": ModelPin("triage", "gpt-4o-mini", ["gpt-4o", DETERMINISTIC]),
+ "recon": ModelPin("recon", "gpt-4o-mini", ["gpt-4o", DETERMINISTIC]),
+ "summary": ModelPin("summary", "gpt-4o-mini", [DETERMINISTIC]),
+}
+
+
+def _env_override(role: str) -> str | None:
+ return os.environ.get(f"AISOC_MODEL_PIN_{role.upper()}")
+
+
+def get_pin(role: str) -> ModelPin:
+ """Return the pin for a role, honouring an env override of the primary."""
+ base = _DEFAULT_PINS.get(role)
+ if base is None:
+ # Unknown role — deterministic-only floor, never a silent guess.
+ return ModelPin(role, DETERMINISTIC, [])
+ override = _env_override(role)
+ if override:
+ return ModelPin(role, override, base.fallback_chain)
+ return base
+
+
+def all_roles() -> list[str]:
+ return sorted(_DEFAULT_PINS)
+
+
+def verify_pins() -> list[str]:
+ """Return violations; empty means every pin has a safe deterministic floor."""
+ problems: list[str] = []
+ for role in all_roles():
+ chain = get_pin(role).resolved_chain()
+ if chain[-1] != DETERMINISTIC:
+ problems.append(f"pin '{role}' chain does not terminate in the deterministic tier: {chain}")
+ if not chain[0]:
+ problems.append(f"pin '{role}' has an empty primary model")
+ return problems
diff --git a/services/agents/app/llm/prompt_registry.py b/services/agents/app/llm/prompt_registry.py
new file mode 100644
index 000000000..fe8cb9414
--- /dev/null
+++ b/services/agents/app/llm/prompt_registry.py
@@ -0,0 +1,131 @@
+"""Versioned, hash-pinned prompt registry (Phase 8 — LLMOps).
+
+`AGENTS.md` requires that any change to agent prompts re-grade the eval harness.
+That rule is only enforceable if prompt changes are *visible and deliberate* —
+but before this, prompts were inline string constants scattered across the
+agent modules, so a one-word tweak could ship without anyone (or any gate)
+noticing it changed the model's behaviour.
+
+This registry makes every production prompt a **named, versioned, content-hashed
+artifact**. The committed lock file (`prompts.lock.json`) pins each prompt's
+version → sha256. `verify_against_lock` (and `scripts/check_prompt_lock.py
+--check`, wired into CI) fails when a prompt's text changes without a version
+bump — so editing a prompt forces a conscious version bump + lock regeneration,
+which is exactly the signal that should trigger the eval re-grade.
+
+The registry is the source of truth for prompt text; agents should read via
+`get(name)` rather than redeclaring constants. Migration of the existing inline
+prompts is tracked as 8b; this seeds the registry + gate with the canonical
+triage/summary prompts.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from dataclasses import dataclass
+from pathlib import Path
+
+LOCK_PATH = Path(__file__).resolve().parent / "prompts.lock.json"
+
+
+def _sha256(text: str) -> str:
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
+
+
+@dataclass(frozen=True)
+class Prompt:
+ name: str
+ version: str
+ text: str
+
+ @property
+ def sha256(self) -> str:
+ return _sha256(self.text)
+
+
+class PromptRegistry:
+ """In-process registry of versioned prompts."""
+
+ def __init__(self) -> None:
+ self._prompts: dict[str, Prompt] = {}
+
+ def register(self, name: str, version: str, text: str) -> Prompt:
+ if name in self._prompts:
+ raise ValueError(f"prompt '{name}' already registered")
+ prompt = Prompt(name=name, version=version, text=text.strip())
+ self._prompts[name] = prompt
+ return prompt
+
+ def get(self, name: str) -> Prompt:
+ if name not in self._prompts:
+ raise KeyError(f"prompt '{name}' is not registered")
+ return self._prompts[name]
+
+ def names(self) -> list[str]:
+ return sorted(self._prompts)
+
+ def as_lock(self) -> dict[str, dict[str, str]]:
+ """Serialise to the lock shape: {name: {version, sha256}}."""
+ return {name: {"version": p.version, "sha256": p.sha256} for name, p in sorted(self._prompts.items())}
+
+ def verify_against_lock(self, lock: dict[str, dict[str, str]]) -> list[str]:
+ """Return a list of drift descriptions; empty means the lock is current.
+
+ Fails on: a registered prompt missing from the lock, a lock entry with
+ no registered prompt, a content hash that changed while the version
+ stayed the same (the dangerous case), or a version that moved without a
+ lock update.
+ """
+ drifts: list[str] = []
+ current = self.as_lock()
+ for name, entry in current.items():
+ locked = lock.get(name)
+ if locked is None:
+ drifts.append(f"prompt '{name}' is registered but missing from the lock")
+ continue
+ if entry["version"] != locked.get("version"):
+ drifts.append(f"prompt '{name}' version {locked.get('version')} → {entry['version']} — regenerate the lock")
+ elif entry["sha256"] != locked.get("sha256"):
+ drifts.append(
+ f"prompt '{name}' text changed WITHOUT a version bump "
+ f"(v{entry['version']}). Bump the version and re-grade the eval harness, then regenerate the lock."
+ )
+ for name in lock:
+ if name not in current:
+ drifts.append(f"lock has prompt '{name}' that is no longer registered")
+ return drifts
+
+
+# ── Canonical production prompts (source of truth) ───────────────────────────
+
+_TRIAGE_SYSTEM = """
+You are a SOC alert triage analyst. Classify the alert as one of:
+true_positive, false_positive, or benign. Return strict JSON:
+{"verdict": "...", "confidence": 0-100, "rationale": "..."}.
+Reason only over the structured summary provided; never request raw logs.
+"""
+
+_SUMMARY_SYSTEM = """
+You are a SOC incident summariser. Given a structured investigation bundle,
+produce a concise analyst-facing summary. Do not invent evidence; cite only
+fields present in the bundle. Return markdown, no preamble.
+"""
+
+
+def default_registry() -> PromptRegistry:
+ """The registry as shipped. Bump a version when you change a prompt."""
+ reg = PromptRegistry()
+ reg.register("triage.system", "1", _TRIAGE_SYSTEM)
+ reg.register("summary.system", "1", _SUMMARY_SYSTEM)
+ return reg
+
+
+def load_lock() -> dict[str, dict[str, str]]:
+ if not LOCK_PATH.exists():
+ return {}
+ return json.loads(LOCK_PATH.read_text(encoding="utf-8"))
+
+
+def write_lock(registry: PromptRegistry) -> None:
+ LOCK_PATH.write_text(json.dumps(registry.as_lock(), indent=2, sort_keys=True) + "\n", encoding="utf-8")
diff --git a/services/agents/app/llm/prompts.lock.json b/services/agents/app/llm/prompts.lock.json
new file mode 100644
index 000000000..06e17717e
--- /dev/null
+++ b/services/agents/app/llm/prompts.lock.json
@@ -0,0 +1,10 @@
+{
+ "summary.system": {
+ "sha256": "eb3fbcdf0bee804cb8a90489331750b059501bc0ed8ef07a9f7c36e12e8f1287",
+ "version": "1"
+ },
+ "triage.system": {
+ "sha256": "904d6d23f9657d5303b780a07b3079073d86e7c45b950148f2733342956aac84",
+ "version": "1"
+ }
+}
diff --git a/services/agents/app/llm/response_cache.py b/services/agents/app/llm/response_cache.py
new file mode 100644
index 000000000..aae5ef227
--- /dev/null
+++ b/services/agents/app/llm/response_cache.py
@@ -0,0 +1,74 @@
+"""Content-addressed LLM response cache (Phase 8 — LLMOps).
+
+Identical LLM requests (same model + same prompt + same input) should not be
+paid for twice. This is a small, dependency-light, content-addressed cache
+keyed by sha256(model + prompt + input). It complements the cost governor's
+per-alert dedup: the governor stops a flood of identical *alerts*; this stops a
+flood of identical *LLM calls* within and across investigations.
+
+The default backend is an in-process LRU-ish dict with a size cap; a Redis-
+backed backend implements the same `CacheBackend` protocol for multi-replica
+deployments. Caching is keyed on content only, so it is safe under the
+determinism contract — a cache hit is byte-identical to what the model returned.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from collections import OrderedDict
+from typing import Protocol, runtime_checkable
+
+
+def cache_key(*, model: str, prompt: str, user_input: str) -> str:
+ h = hashlib.sha256()
+ for part in (model, prompt, user_input):
+ h.update(part.encode("utf-8"))
+ h.update(b"\x00") # field separator so a||b != ab
+ return h.hexdigest()
+
+
+@runtime_checkable
+class CacheBackend(Protocol):
+ def get(self, key: str) -> str | None: ...
+ def set(self, key: str, value: str) -> None: ...
+
+
+class InMemoryResponseCache:
+ """Bounded in-process cache. Evicts oldest on overflow."""
+
+ def __init__(self, max_entries: int = 1024) -> None:
+ self._max = max_entries
+ self._store: OrderedDict[str, str] = OrderedDict()
+ self.hits = 0
+ self.misses = 0
+
+ def get(self, key: str) -> str | None:
+ if key in self._store:
+ self._store.move_to_end(key)
+ self.hits += 1
+ return self._store[key]
+ self.misses += 1
+ return None
+
+ def set(self, key: str, value: str) -> None:
+ self._store[key] = value
+ self._store.move_to_end(key)
+ while len(self._store) > self._max:
+ self._store.popitem(last=False)
+
+ def __len__(self) -> int:
+ return len(self._store)
+
+
+class ResponseCache:
+ """Front door over a backend. `lookup`/`store` take request components and
+ hash them; callers never construct keys by hand."""
+
+ def __init__(self, backend: CacheBackend | None = None) -> None:
+ self._backend: CacheBackend = backend or InMemoryResponseCache()
+
+ def lookup(self, *, model: str, prompt: str, user_input: str) -> str | None:
+ return self._backend.get(cache_key(model=model, prompt=prompt, user_input=user_input))
+
+ def store(self, *, model: str, prompt: str, user_input: str, response: str) -> None:
+ self._backend.set(cache_key(model=model, prompt=prompt, user_input=user_input), response)
diff --git a/services/agents/app/llm/structured_output.py b/services/agents/app/llm/structured_output.py
new file mode 100644
index 000000000..1600a8646
--- /dev/null
+++ b/services/agents/app/llm/structured_output.py
@@ -0,0 +1,90 @@
+"""Fail-closed structured-output validation for LLM responses (Phase 8).
+
+LLMs are asked to return JSON; they routinely wrap it in ``` fences, add a
+preamble, or emit a field that violates the contract. Before this, each agent
+had its own ad-hoc `_parse_llm_response` that, on a malformed reply, tended to
+guess or fall through with a partial object. Passing a half-parsed structured
+output downstream (into an autonomy decision, a ledger entry) is worse than
+failing.
+
+This module is the single, fail-closed parser: it extracts the JSON body,
+validates it against a caller-supplied validator (typically a Pydantic model's
+`model_validate`), and on ANY failure returns a structured error rather than a
+partial object. `validate_or_fallback` gives callers a deterministic default so
+a bad LLM reply degrades instead of crashing.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any
+
+_FENCE_RE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$", re.IGNORECASE)
+
+
+@dataclass(frozen=True)
+class ParseResult:
+ ok: bool
+ value: Any = None
+ error: str = ""
+
+
+def extract_json_block(text: str) -> str:
+ """Best-effort extraction of a JSON object/array from an LLM reply.
+
+ Strips ``` fences and any prose before the first `{`/`[`. Does NOT attempt
+ to repair invalid JSON — a reply we can't parse cleanly is a failure, by
+ design.
+ """
+ if not isinstance(text, str):
+ return ""
+ stripped = _FENCE_RE.sub("", text.strip())
+ # Trim any leading prose before the first JSON opener.
+ for opener in ("{", "["):
+ idx = stripped.find(opener)
+ if idx != -1:
+ return stripped[idx:].strip()
+ return stripped.strip()
+
+
+def parse_structured(
+ text: str,
+ validator: Callable[[dict[str, Any]], Any] | None = None,
+) -> ParseResult:
+ """Parse + validate an LLM structured reply. Fail-closed.
+
+ Returns ``ParseResult(ok=True, value=...)`` only when the text parses as
+ JSON *and* (if a validator is given) passes it. Any failure yields
+ ``ok=False`` with a reason — never a partial object.
+ """
+ body = extract_json_block(text)
+ if not body:
+ return ParseResult(ok=False, error="empty response")
+ try:
+ parsed = json.loads(body)
+ except (json.JSONDecodeError, ValueError) as exc:
+ return ParseResult(ok=False, error=f"invalid JSON: {exc}")
+ if validator is None:
+ return ParseResult(ok=True, value=parsed)
+ try:
+ validated = validator(parsed)
+ except Exception as exc: # noqa: BLE001 — any validator error is a failure
+ return ParseResult(ok=False, error=f"schema validation failed: {exc}")
+ return ParseResult(ok=True, value=validated)
+
+
+def validate_or_fallback(
+ text: str,
+ fallback: Any,
+ validator: Callable[[dict[str, Any]], Any] | None = None,
+) -> tuple[Any, bool]:
+ """Return ``(value, used_fallback)``. On any parse/validation failure the
+ caller-supplied deterministic ``fallback`` is returned so the pipeline
+ degrades instead of propagating a malformed structured output."""
+ result = parse_structured(text, validator)
+ if result.ok:
+ return result.value, False
+ return fallback, True
diff --git a/services/agents/tests/test_llm_ops.py b/services/agents/tests/test_llm_ops.py
new file mode 100644
index 000000000..2b3f9acee
--- /dev/null
+++ b/services/agents/tests/test_llm_ops.py
@@ -0,0 +1,139 @@
+"""Phase 8 — LLMOps gates: prompt registry, structured output, pins, cache."""
+
+from __future__ import annotations
+
+from app.llm.model_pins import DETERMINISTIC, all_roles, get_pin, verify_pins
+from app.llm.prompt_registry import PromptRegistry, default_registry, load_lock
+from app.llm.response_cache import InMemoryResponseCache, ResponseCache, cache_key
+from app.llm.structured_output import parse_structured, validate_or_fallback
+
+# ── Prompt registry + lock drift gate ────────────────────────────────────────
+
+
+def test_committed_prompt_lock_matches_registry():
+ """The gate: production prompts must match the committed lock. If this
+ fails, a prompt changed without a version bump + lock regeneration."""
+ reg = default_registry()
+ drifts = reg.verify_against_lock(load_lock())
+ assert drifts == [], f"prompt lock drift: {drifts}"
+
+
+def test_text_change_without_version_bump_is_detected():
+ reg = PromptRegistry()
+ reg.register("p", "1", "original text")
+ lock = reg.as_lock()
+ # Simulate an edit that kept the version.
+ reg2 = PromptRegistry()
+ reg2.register("p", "1", "EDITED text")
+ drifts = reg2.verify_against_lock(lock)
+ assert any("WITHOUT a version bump" in d for d in drifts)
+
+
+def test_version_bump_is_flagged_for_lock_regen():
+ reg = PromptRegistry()
+ reg.register("p", "1", "text")
+ lock = reg.as_lock()
+ reg2 = PromptRegistry()
+ reg2.register("p", "2", "text")
+ drifts = reg2.verify_against_lock(lock)
+ assert any("regenerate the lock" in d for d in drifts)
+
+
+def test_duplicate_registration_rejected():
+ reg = PromptRegistry()
+ reg.register("p", "1", "a")
+ try:
+ reg.register("p", "1", "b")
+ raise AssertionError("expected ValueError on duplicate registration")
+ except ValueError:
+ pass
+
+
+# ── Structured-output validation (fail-closed) ───────────────────────────────
+
+
+def test_parse_strips_fences_and_prose():
+ text = 'Here is the result:\n```json\n{"verdict": "true_positive", "confidence": 90}\n```'
+ result = parse_structured(text)
+ assert result.ok
+ assert result.value["verdict"] == "true_positive"
+
+
+def test_invalid_json_fails_closed():
+ result = parse_structured("not json at all")
+ assert not result.ok
+ assert "invalid JSON" in result.error
+
+
+def test_schema_validation_failure_fails_closed():
+ def validator(obj):
+ if "verdict" not in obj:
+ raise ValueError("missing verdict")
+ return obj
+
+ result = parse_structured('{"confidence": 50}', validator)
+ assert not result.ok
+ assert "schema validation failed" in result.error
+
+
+def test_validate_or_fallback_returns_deterministic_default_on_failure():
+ fallback = {"verdict": "needs_review", "confidence": 0}
+ value, used_fallback = validate_or_fallback("garbage {{{", fallback)
+ assert used_fallback is True
+ assert value == fallback
+
+
+def test_validate_or_fallback_passes_through_valid():
+ value, used_fallback = validate_or_fallback('{"ok": true}', {"ok": False})
+ assert used_fallback is False
+ assert value == {"ok": True}
+
+
+# ── Model pins + provider fallback ───────────────────────────────────────────
+
+
+def test_every_pin_chain_terminates_in_deterministic():
+ assert verify_pins() == []
+ for role in all_roles():
+ chain = get_pin(role).resolved_chain()
+ assert chain[-1] == DETERMINISTIC, f"{role} chain must end deterministic: {chain}"
+
+
+def test_unknown_role_falls_back_to_deterministic_only():
+ pin = get_pin("does-not-exist")
+ assert pin.resolved_chain() == [DETERMINISTIC]
+
+
+def test_env_override_pins_primary(monkeypatch):
+ monkeypatch.setenv("AISOC_MODEL_PIN_TRIAGE", "my-local-model")
+ pin = get_pin("triage")
+ assert pin.primary_model == "my-local-model"
+ assert pin.resolved_chain()[-1] == DETERMINISTIC # floor preserved
+
+
+# ── Response cache (content-addressed) ───────────────────────────────────────
+
+
+def test_cache_key_is_field_separated():
+ # a||b must not collide with different splits of the same concatenation.
+ k1 = cache_key(model="m", prompt="ab", user_input="c")
+ k2 = cache_key(model="m", prompt="a", user_input="bc")
+ assert k1 != k2
+
+
+def test_response_cache_hit_and_miss():
+ cache = ResponseCache()
+ assert cache.lookup(model="m", prompt="p", user_input="i") is None
+ cache.store(model="m", prompt="p", user_input="i", response="RESP")
+ assert cache.lookup(model="m", prompt="p", user_input="i") == "RESP"
+
+
+def test_in_memory_cache_evicts_oldest():
+ backend = InMemoryResponseCache(max_entries=2)
+ backend.set("a", "1")
+ backend.set("b", "2")
+ backend.set("c", "3") # evicts "a"
+ assert backend.get("a") is None
+ assert backend.get("b") == "2"
+ assert backend.get("c") == "3"
+ assert backend.hits >= 2