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(triage): ask the provider for JSON instead of correcting prose afterwards (#896)
Beenu Arora618e1e8b5817
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 888331fe4..80beb7aa5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,81 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- **Auto-triage never asked the provider for JSON, so a third of the bundled+ model's replies were thrown away.** `run_auto_triage` parses the reply as a+ JSON object, but nothing in `services/agents/app/llm/` ever set+ `response_format`, leaving the model free to emit prose shaped like JSON and+ the parser to correct it afterwards. Measured over 50 alerts from the+ committed synthetic corpus, through the LiteLLM gateway exactly as production+ routes, against the bundled `llama3.2:3b-instruct-q4_K_M` at the production+ `temperature=0.0` / `max_tokens=512`: replies triage could use went from+ **44 of 50 to 50 of 50** once the reply was constrained to a JSON object.++ The failure shape is worth recording, because it was not the one expected.+ **Every one of the six failures carried a correct `verdict` and `confidence`+ and a malformed `rationale`** — `"rationale": The alert is...` with the+ opening quote simply missing, a raw newline before an unquoted value, or an+ invalid `\'` escape. `finish_reason` was `stop` on all 50 calls, so+ truncation was not involved and `max_tokens` is exonerated. A model that had+ reasoned correctly was being discarded over its punctuation, which is+ precisely what constraining the grammar prevents and no amount of parsing+ after the fact can.++ The gateway ships `drop_params: true`, so a provider that does not support+ the parameter has it dropped rather than erroring. Requested through+ `model_kwargs` rather than as a top-level argument, because langchain warns+ on every construction otherwise.++- **The published "7 of 19" reliability figure does not reproduce.** Re-measured+ on the production call path at the sample sizes above, the pre-fix tree reads+ 44 of 50. The original number's conditions are not recoverable — it was taken+ during a QA run whose host had exhausted its disk — so rather than restate it,+ `scripts/measure_triage_reliability.py` now produces the figure repeatably and+ records *why* each failed attempt failed. Every surface that published the old+ ratio now carries the new one and names the method.++- **A valid verdict was discarded when one field had the wrong type.**+ `float(data.get("confidence", 0.5))` was unguarded, so `"confidence": "high"`+ raised `ValueError`, which the caller converts into an `AutoTriageError` and a+ deterministic fallback — losing a verdict and rationale that may have been+ perfectly good. `_coerce_confidence` now reads numeric strings and+ percentages and degrades to a neutral 0.5 otherwise. That is safe here and+ only here: auto-close requires `confidence >= AUTO_CLOSE_THRESHOLD` (0.85 by+ default), so an unread field escalates to a human instead of closing an+ alert. The verdict itself still fails closed. Not a cause of the measured+ failures, but reachable by any model on any alert.++- **`structured_output.py` described itself as the single fail-closed parser+ while nothing in production imported it.** Its docstring said each agent+ "had its own ad-hoc `_parse_llm_response`", past tense; all five still did,+ and its only callers were its own tests — a passing test on an uncalled+ function is indistinguishable from a working feature. `auto_triage_agent` now+ shares its extraction step, and the docstring records that `cloud_agent`,+ `identity_agent`, `insider_threat_agent` and `phishing_agent` still carry+ their own, rather than describing the consolidation as finished.++ Extracting is also now brace-balanced and string-aware. It trimmed prose+ before the opening `{` and nothing after the closing `}`, so a model that+ answered correctly and added "Hope that helps!" was scored unparseable — and+ a `}` inside a string value would have ended the scan early. An unclosed+ object is still handed to the JSON parser to report rather than silently+ trimmed to the last balanced point, because extraction may read what the+ model said and must not guess at what it meant.++### Added++- **`scripts/measure_triage_reliability.py`** — the measurement behind the+ figures above. It imports the production prompt, envelope and parser rather+ than restating them, and uses a *different* alert per attempt: production+ pins `temperature=0.0`, so asking one alert twenty times measures one reply+ twenty times, not a rate. Failed attempts record the model's own words, since+ "Expecting value: line 4 column 16" cannot be diagnosed without the text it+ indexes into. With no model reachable it prints SKIPPED and says that nothing+ was measured, because a skip is not a pass.++## [11.1.0] — 2026-09-25### Fixeddiff --git a/README.md b/README.mdindex 5faaf03aa..b43ef598a 100644--- a/README.md+++ b/README.md@@ -132,9 +132,9 @@ alert, and **it needs no credentials to do either** — for two reasons.**The model ships with the gateway.** Ollama runs a pinned ~2 GB`llama3.2:3b-instruct-q4_K_M` sized for CPU-only inference, so `make up`produces real triage verdicts with real token counts in the Investigation-Ledger — not a stub. It is also not a frontier model, and the difference shows:-in a measured run of 19 auto-triages it returned schema-valid output 7 times,-and the other 12 fell back to the deterministic path, which the rail labels.+Ledger — not a stub. It is also not a frontier model: over 50 alerts it gave+triage usable output 44 times before the reply was constrained to JSON and 50+after ([method](scripts/measure_triage_reliability.py)), and the rail labels which path answered.To upgrade, set `OPENAI_API_KEY`, `AISOC_LLM_MODEL_FAST`, `AISOC_LLM_MODEL_DEEP`and an empty `AISOC_LLM_API_BASE`. **No hosted provider has ever been exercisedhere** — there is no funded key, so per-model rows read *not measured* ratherdiff --git a/RELEASES.md b/RELEASES.mdindex d036bf9d1..88f3d9b74 100644--- a/RELEASES.md+++ b/RELEASES.md@@ -12,7 +12,7 @@ This file mirrors what used to live in the "What's new" section of [`README.md`]**Nothing in this release requires you to act, which is why it is a minor.** `AISOC_API_URL`, `AISOC_AGENTS_URL` and `AISOC_REALTIME_URL` configure the console at run time and fall back to the addresses that were previously compiled in. `AISOC_CONSOLE_BIND_ADDR` and `AISOC_BIND_ADDR` both default to loopback, so a laptop install still exposes nothing by omission. The only removals are two variables the console never read.-**What is measured, and what is not.** A fresh `make up` runs AI triage against the bundled `llama3.2:3b-instruct-q4_K_M` with no credentials. In a measured run of 19 auto-triages that model returned schema-valid JSON **7 times**; the other 12 fell back to the deterministic path and logged that they had. In the live QA for this release **both** triage runs fell back to that deterministic path — the token counts are real because the model genuinely was called; what failed was the shape of its reply. The recorded walkthrough's closing card states this rather than hiding it. **No hosted provider has ever been exercised** — there is still no funded key, and that remains a separate, unmade claim. The npm and PyPI packages are built and packed on every tag and **are still not uploaded**, because no registry credential exists; treat any install command for them as unavailable rather than broken.+**What is measured, and what is not.** A fresh `make up` runs AI triage against the bundled `llama3.2:3b-instruct-q4_K_M` with no credentials. At the time this shipped the published figure was 7 schema-valid replies in a measured run of 19. **That figure does not reproduce**: re-measured later over 50 alerts through the gateway, on the same model and the same production call, it reads **44 of 50** — see `[Unreleased]` in `CHANGELOG.md` for the method and for the change that took it to 50 of 50. When validation fails, triage falls back to the deterministic path and logs that it did. In the live QA for this release **both** triage runs fell back to that deterministic path — the token counts are real because the model genuinely was called; what failed was the shape of its reply. The recorded walkthrough's closing card states this rather than hiding it. **No hosted provider has ever been exercised** — there is still no funded key, and that remains a separate, unmade claim. The npm and PyPI packages are built and packed on every tag and **are still not uploaded**, because no registry credential exists; treat any install command for them as unavailable rather than broken.**v11.1.0 highlights (September 25, 2026)**- **The console's upstream addresses were frozen at image-build time, so a documented variable could not work.** `next build` inlines every `NEXT_PUBLIC_*` value into the JavaScript bundle *and* compiles the destinations returned by `rewrites()` into `routes-manifest.json`. `next start` re-reads the config and logs that it did, which makes this look configurable while production routing is served from the manifest — so a pulled image could only ever talk to the hosts it was built against. It worked on the bundled stack by coincidence, because the baked `http://api:8000` is that service's DNS name on that network. The entrypoint now re-evaluates the real `rewrites()` against the container's environment before the server starts, and an address that is set and cannot be applied stops the container and names itself rather than starting on the built-in defaults.@@ -33,7 +33,7 @@ The full inventory — 19 entries — lives under `[11.1.0]` in [`CHANGELOG.md`]**Read the BREAKING section of the changelog before upgrading.** Two items need action. `POST /v1/ingest` and `POST /v1/ingest/batch` now require a credential and take the tenant from it; previously they read `X-Tenant-ID`, believed it, and wrote alerts into whatever tenant the caller named. And CORE now needs **8 GB of memory and 20 GB of free disk**, up from `~6.5 GB`, because the threat-intelligence feed, its vector store and a local model moved into it.-**What is measured, and what is not.** A fresh `make up` now runs AI triage against the bundled `llama3.2:3b-instruct-q4_K_M` with no credentials. In a measured run of 19 auto-triages that model returned schema-valid JSON **7 times**; the other 12 fell back to the deterministic path and logged that they had. That ratio is published here, in the README and on the architecture page rather than implied away. **No hosted provider has ever been exercised** — there is still no funded key, and that remains a separate, unmade claim. The npm and PyPI packages are built and packed on every tag and **are still not uploaded**, because no registry credential exists; treat any install command for them as unavailable rather than broken.+**What is measured, and what is not.** A fresh `make up` now runs AI triage against the bundled `llama3.2:3b-instruct-q4_K_M` with no credentials. At the time this shipped the published figure was 7 schema-valid replies in a measured run of 19. **That figure does not reproduce**: re-measured later over 50 alerts through the gateway, on the same model and the same production call, it reads **44 of 50** — see `[Unreleased]` in `CHANGELOG.md` for the method and for the change that took it to 50 of 50. When validation fails, triage falls back to the deterministic path and logs that it did. That ratio is published here, in the README and on the architecture page rather than implied away. **No hosted provider has ever been exercised** — there is still no funded key, and that remains a separate, unmade claim. The npm and PyPI packages are built and packed on every tag and **are still not uploaded**, because no registry credential exists; treat any install command for them as unavailable rather than broken.**v11.0.0 highlights (September 25, 2026)**- **The ingest API authenticated nothing.** It read `X-Tenant-ID`, believed it, and wrote events for whatever tenant the caller named — so anyone who could reach the port could write alerts into any tenant. The comment in `server.go` asserting the endpoint was "token-authenticated per request" had been false since it was written. It is true now: a minted push token or a service token, with `X-Tenant-ID` intersected against what the credential authorises rather than trusted, and no dev-mode bypass.diff --git a/ROADMAP.md b/ROADMAP.mdindex 82966b9e3..de5860d69 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -746,8 +746,9 @@ Re-measured rather than restated: CORE is 14 long-running services plus aone-shot model pull and `full` is 22; resident memory for the whole stack went1.72 GiB → 4.84 GiB. A fresh `make up` now holds 1,723 real CISA KEV entrieswithin a minute of boot with no credentials, and runs triage against a bundled-3B model — which returned schema-valid JSON **7 times in a measured run of 19**,-the other 12 falling back to the deterministic path. No hosted provider has+3B model — which returned usable triage output **44 times in 50 before its reply+was constrained to a JSON object, and 50 of 50 after**, the remainder falling+back to the deterministic path and logging that they had. No hosted provider hasbeen exercised; there is still no funded key.Full inventory under `[11.0.0]` in [`CHANGELOG.md`](CHANGELOG.md).diff --git a/apps/docs/docs/deployment/walkthrough.mdx b/apps/docs/docs/deployment/walkthrough.mdxindex fe51b4671..01bffd438 100644--- a/apps/docs/docs/deployment/walkthrough.mdx+++ b/apps/docs/docs/deployment/walkthrough.mdx@@ -173,16 +173,26 @@ Triage runs automatically on every fused alert. It is a real model call: the**Cost Dashboard** reports measured prompt and completion tokens against theresolved model name, and the per-run record carries the same figures.-:::warning The bundled model is small, and it shows+:::warning The bundled model is small, and the recording predates a fix`llama3.2:3b-instruct-q4_K_M` is chosen to run on CPU in 8 GB of RAM, not to be-accurate. It returns schema-valid triage JSON a minority of the time — in one-measured run, 7 of 19. When validation fails, triage falls back to a+accurate. When its reply cannot be validated, triage falls back to adeterministic path and **labels which one answered**: the run's `model_used`-reads `kafka:auto_triage:deterministic` rather than naming a model. Both runs-in the recorded walkthrough took that fallback. The token counts are still-real, because the model really was called; what failed was the shape of its-reply. Set `OPENAI_API_KEY` with `AISOC_LLM_MODEL_FAST` / `AISOC_LLM_MODEL_DEEP`-to route to a hosted model instead.+reads `kafka:auto_triage:deterministic` rather than naming a model. The token+counts are still real, because the model really was called; what failed was the+shape of its reply.++**Both triage runs in the recorded walkthrough took that fallback, and that is+no longer representative.** Triage now asks the provider to constrain its reply+to a JSON object. Measured over 50 alerts through the gateway, replies triage+could use went from **44 of 50 to 50 of 50**; every one of the six failures+carried a correct verdict and confidence with a malformed `rationale`, and none+was truncated. Reproduce it with+`python3 scripts/measure_triage_reliability.py --attempts 50 --json-mode`.++The video is kept as recorded rather than re-cut to flatter the product, so+expect it to show the fallback the older build took. Set `OPENAI_API_KEY` with+`AISOC_LLM_MODEL_FAST` / `AISOC_LLM_MODEL_DEEP` to route to a hosted model+instead — no hosted provider has been exercised here.:::Measured spend reads `$0.00` because the model runs beside the stack and costsdiff --git a/apps/web/public/demo/README.md b/apps/web/public/demo/README.mdindex 5f6438cc3..fe5cec687 100644--- a/apps/web/public/demo/README.md+++ b/apps/web/public/demo/README.md@@ -25,10 +25,15 @@ downstream of it is the product's own work. Terminal waits are shortened,disclosed by an on-screen badge for the whole of every segment it applies to;browser sections run at real speed.-The bundled local model returns schema-valid triage JSON a minority of the-time. In this recording both triage runs fell back to the deterministic path,-which the console labels (`model_used` reads `kafka:auto_triage:deterministic`).-That is the honest common case and the closing card says so.+In this recording both triage runs fell back to the deterministic path, which+the console labels (`model_used` reads `kafka:auto_triage:deterministic`), and+the closing card says so.++**That is no longer the common case.** Triage now asks the provider to+constrain its reply to a JSON object: measured over 50 alerts through the+gateway, replies triage could use went from 44 of 50 to 50 of 50. The recording+predates that change and is kept as recorded rather than re-cut to flatter the+product, so it shows the fallback the older build took.## How it was produceddiff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsxindex 786999eba..ffe5918a9 100644--- a/apps/web/src/app/page.tsx+++ b/apps/web/src/app/page.tsx@@ -179,7 +179,7 @@ const faqJsonLd = {acceptedAnswer: {'@type': 'Answer',text:- 'It is a 3B quantized model sized for CPU inference, and the difference from a frontier model is visible. In a measured run of 19 auto-triages on a core stack, 7 returned schema-valid output and 12 did not; the 12 fell back to the deterministic path and the Investigation Rail shows which path produced the verdict it is displaying. Point the gateway at a hosted provider and that changes — but no hosted provider has ever been exercised in this repository, so those rows read "not measured" rather than zero.',+ 'It is a 3B quantized model sized for CPU inference, and the difference from a frontier model is visible. Measured over 50 alerts on a core stack, it returned output triage could use 44 times before its reply was constrained to a JSON object and 50 times after; each of the six failures carried a correct verdict and confidence with a malformed rationale. When validation does fail the run falls back to the deterministic path, and the Investigation Rail shows which path produced the verdict it is displaying. Point the gateway at a hosted provider and that changes — but no hosted provider has ever been exercised in this repository, so those rows read "not measured" rather than zero.',},},{diff --git a/scripts/measure_triage_reliability.py b/scripts/measure_triage_reliability.pynew file mode 100644index 000000000..41c3e2bd9--- /dev/null+++ b/scripts/measure_triage_reliability.py@@ -0,0 +1,261 @@+#!/usr/bin/env python3+"""Measure how often the local model returns usable auto-triage output.++The published figure for the bundled ``llama3.2:3b-instruct-q4_K_M`` was+"7 of 19", with no breakdown — so nobody could say which fix would help, or+prove that one had. This harness produces that number reproducibly and, for+every attempt that failed, records *why*.++It drives the production prompt and the production parser by importing them:+``_SYSTEM_PROMPT``, ``system_rule``, ``_build_alert_context`` and+``_parse_llm_response`` all come from ``auto_triage_agent``. A harness that+restated either would measure whether a copy agrees with itself.++Two things about the method, because they change what the number means:++* Every attempt uses a **different** alert. Production pins+ ``temperature=0.0``, so asking one alert twenty times measures one reply+ twenty times, not a rate.+* The alerts come from the committed synthetic corpus, so the sample is fixed+ and a before/after comparison is of the same work.++Usage::++ python3 scripts/measure_triage_reliability.py --attempts 20+ python3 scripts/measure_triage_reliability.py --json out.json++Exit status is 0 whenever the measurement ran. This reports a number; it does+not gate on one. With no reachable model it prints SKIPPED and exits 0 — a+skip is not a pass, and it says which it did.+"""++from __future__ import annotations++import argparse+import json+import sys+import time+import urllib.error+import urllib.request+from collections import Counter+from pathlib import Path+from typing import Any+from uuid import uuid4++REPO_ROOT = Path(__file__).resolve().parent.parent+AGENTS_ROOT = REPO_ROOT / "services" / "agents"+sys.path.insert(0, str(AGENTS_ROOT))++CORPUS = AGENTS_ROOT / "tests" / "eval_data" / "synthetic_incidents.json"++# Production values, read from the call site in auto_triage_agent.run_auto_triage.+# If these drift from production the measurement stops describing production,+# so they are asserted against it in tests/test_triage_reliability_harness.py.+TEMPERATURE = 0.0+MAX_TOKENS = 512++DEFAULT_BASE_URL = "http://localhost:11434"+DEFAULT_MODEL = "llama3.2:3b-instruct-q4_K_M"++# Why an attempt did not yield a usable verdict. Ordered most to least+# specific: the first that matches is recorded.+OUTCOME_USABLE = "usable"+OUTCOME_EMPTY = "empty_response"+OUTCOME_INVALID_JSON = "invalid_json"+OUTCOME_NOT_OBJECT = "not_a_json_object"+OUTCOME_FIELD_TYPE = "field_wrong_type"+OUTCOME_OTHER = "other_error"+++def _load_alerts(limit: int) -> list[dict[str, Any]]:+ """Fixed, deterministic alerts drawn from the committed synthetic corpus."""+ raw = json.loads(CORPUS.read_text())+ incidents = raw if isinstance(raw, list) else raw.get("incidents", raw)+ alerts: list[dict[str, Any]] = []+ for inc in incidents[:limit]:+ alerts.append(+ {+ "id": inc.get("id", ""),+ "title": inc.get("title", ""),+ "description": inc.get("description", ""),+ "severity": inc.get("severity", "medium"),+ "mitre_techniques": inc.get("expected_techniques", []),+ }+ )+ return alerts+++def _build_messages(alert: dict[str, Any]) -> list[dict[str, str]]:+ """The exact system and user content production sends."""+ from app.agents.auto_triage_agent import _SYSTEM_PROMPT, _build_alert_context+ from app.models.state import InvestigationState+ from app.prompting.envelope import make_nonce, system_rule++ state = InvestigationState(+ incident_id=uuid4(),+ tenant_id=uuid4(),+ alert_summary=f"{alert['title']} — {alert['description']}",+ raw_alert=alert,+ )+ nonce = make_nonce()+ return [+ {"role": "system", "content": _SYSTEM_PROMPT + "\n\n" + system_rule(nonce)},+ {"role": "user", "content": _build_alert_context(state)},+ ]+++def _call_model(+ base_url: str,+ model: str,+ messages: list[dict[str, str]],+ timeout: float,+ json_mode: bool = False,+) -> tuple[str, str]:+ """Return (content, finish_reason). Raises on transport failure."""+ payload: dict[str, Any] = {+ "model": model,+ "messages": messages,+ "temperature": TEMPERATURE,+ "max_tokens": MAX_TOKENS,+ }+ if json_mode:+ # What the fix under test asks for: the gateway translates this to+ # Ollama's `format: json`, which constrains generation so the grammar+ # errors we measured (an unquoted value, an invalid escape) cannot be+ # emitted in the first place.+ payload["response_format"] = {"type": "json_object"}+ req = urllib.request.Request( # noqa: S310 — operator-supplied localhost gateway+ f"{base_url.rstrip('/')}/v1/chat/completions",+ data=json.dumps(payload).encode(),+ headers={"Content-Type": "application/json", "Authorization": "Bearer local"},+ method="POST",+ )+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310+ body = json.loads(resp.read())+ choice = (body.get("choices") or [{}])[0]+ return choice.get("message", {}).get("content", ""), choice.get("finish_reason", "")+++def _classify(raw_text: str) -> tuple[str, str]:+ """Run the production parser and say what happened. Returns (outcome, detail)."""+ from app.agents.auto_triage_agent import _parse_llm_response++ if not (raw_text or "").strip():+ return OUTCOME_EMPTY, "model returned no content"+ try:+ _parse_llm_response(raw_text)+ except json.JSONDecodeError as exc:+ return OUTCOME_INVALID_JSON, str(exc)+ except AttributeError as exc:+ # `.get` on a list or scalar: valid JSON, wrong shape.+ return OUTCOME_NOT_OBJECT, str(exc)+ except (ValueError, TypeError) as exc:+ # Reached `float(confidence)` or similar with something uncoercible.+ # The verdict and rationale may have been perfectly good.+ return OUTCOME_FIELD_TYPE, str(exc)+ except Exception as exc: # noqa: BLE001 — anything else still counts as a failure+ return OUTCOME_OTHER, f"{type(exc).__name__}: {exc}"+ return OUTCOME_USABLE, ""+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--attempts", type=int, default=20, help="Number of distinct alerts to triage (default 20).")+ parser.add_argument("--base-url", default=DEFAULT_BASE_URL, help="OpenAI-compatible base URL of the local model.")+ parser.add_argument("--model", default=DEFAULT_MODEL, help="Model name to request.")+ parser.add_argument("--timeout", type=float, default=180.0, help="Per-call timeout in seconds.")+ parser.add_argument("--json", dest="json_out", help="Write the full per-attempt record here.")+ parser.add_argument(+ "--json-mode",+ action="store_true",+ help="Request response_format=json_object, constraining generation to valid JSON.",+ )+ args = parser.parse_args(argv)++ alerts = _load_alerts(args.attempts)+ if not alerts:+ print(f"refusing to report a rate over no alerts — {CORPUS} yielded none", file=sys.stderr)+ return 1++ records: list[dict[str, Any]] = []+ counts: Counter[str] = Counter()+ truncated = 0+ started = time.monotonic()++ for idx, alert in enumerate(alerts, start=1):+ messages = _build_messages(alert)+ try:+ content, finish = _call_model(args.base_url, args.model, messages, args.timeout, args.json_mode)+ except (urllib.error.URLError, TimeoutError, OSError) as exc:+ if idx == 1:+ print(f"SKIPPED — no model reachable at {args.base_url}: {exc}")+ print("This is a skip, not a pass: nothing was measured.")+ return 0+ print(f" attempt {idx}: transport failure after {idx - 1} measured — {exc}", file=sys.stderr)+ break++ outcome, detail = _classify(content)+ counts[outcome] += 1+ if finish == "length":+ truncated += 1+ record = {+ "alert_id": alert["id"],+ "outcome": outcome,+ "detail": detail,+ "finish_reason": finish,+ "response_chars": len(content or ""),+ }+ if outcome != OUTCOME_USABLE:+ # "Expecting value: line 4 column 16" is not diagnosable without the+ # text it indexes into. Production learned this and logs an excerpt+ # on failure; a harness whose whole job is explaining failures has+ # less excuse. Only failures, and only the model's own words about a+ # synthetic alert from the committed corpus.+ record["response"] = (content or "")[:1200]+ records.append(record)+ print(f" [{idx:>2}/{len(alerts)}] {alert['id']:<14} {outcome}{(' — ' + detail[:70]) if detail else ''}")++ measured = len(records)+ usable = counts[OUTCOME_USABLE]+ elapsed = time.monotonic() - started++ print()+ print(f"usable triage output: {usable} of {measured}", end="")+ print(f" ({usable / measured:.0%})" if measured else "")+ print(f"model {args.model}")+ print(f"temperature/max_tokens {TEMPERATURE} / {MAX_TOKENS} (production values)")+ print(f"structured output {'response_format=json_object' if args.json_mode else 'not requested'}")+ print(f"alerts {measured} distinct, from {CORPUS.name}")+ print(f"elapsed {elapsed:.0f}s")+ if truncated:+ print(f"hit the token ceiling {truncated} time(s) — finish_reason=length")+ if measured - usable:+ print("\nwhy the rest failed:")+ for outcome, n in counts.most_common():+ if outcome != OUTCOME_USABLE:+ print(f" {n:>3} {outcome}")++ if args.json_out:+ Path(args.json_out).write_text(+ json.dumps(+ {+ "model": args.model,+ "temperature": TEMPERATURE,+ "max_tokens": MAX_TOKENS,+ "json_mode": args.json_mode,+ "attempts": measured,+ "usable": usable,+ "truncated": truncated,+ "outcomes": dict(counts),+ "records": records,+ },+ indent=2,+ )+ + "\n"+ )+ print(f"\nwrote {args.json_out}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/agents/app/agents/auto_triage_agent.py b/services/agents/app/agents/auto_triage_agent.pyindex e12c18212..a1a1944f2 100644--- a/services/agents/app/agents/auto_triage_agent.py+++ b/services/agents/app/agents/auto_triage_agent.py@@ -38,6 +38,7 @@ from app.context.organisation_memory import render_for_promptfrom app.investigator.prompt_sanitizer import sanitize_text, wrap_untrustedfrom app.llm import safe_ainvokefrom app.llm.factory import make_chat_model+from app.llm.structured_output import extract_json_blockfrom app.models.state import AgentStatus, InvestigationStatefrom app.prompt_serialization import format_extra_fields_for_llmfrom app.prompting.envelope import make_nonce, scan_evidence_fields, system_rule@@ -243,13 +244,58 @@ def _close_truncated_json(fragment: str) -> str:return repaired + "".join(reversed(stack))+_NEUTRAL_CONFIDENCE = 0.5+++def _coerce_confidence(value: Any) -> float:+ """Read a confidence, and never discard a verdict over this field alone.++ ``float(value)`` was unguarded here. A model answering ``"confidence":+ "high"`` raised ``ValueError``, which the caller turns into an+ ``AutoTriageError``, throwing away a verdict and rationale that may have+ been perfectly good because one field of three was the wrong type.++ Not observed in the 70 measured calls behind this change — the failures+ there were all malformed ``rationale`` — but it is reachable by any model+ on any alert, and the cost of it firing is a fallback nobody can explain.++ Degrading to a neutral value is safe *here* specifically because confidence+ is a gate, not a verdict: ``run_auto_triage`` auto-closes only when+ ``confidence >= AUTO_CLOSE_THRESHOLD``, which defaults to 0.85, so 0.5+ routes to a human. An operator who lowers that below the neutral value is+ choosing to auto-close on an unread field, which is why this returns the+ neutral constant rather than 0.0 — a deployment that trusts everything+ should not be handed a number that also fails every other comparison.+ It is the verdict itself that must never be guessed, and that still fails+ closed through ``normalize_disposition``.+ """+ if isinstance(value, bool): # bool is an int; "confidence": true means nothing+ return _NEUTRAL_CONFIDENCE+ if isinstance(value, int | float):+ return max(0.0, min(1.0, float(value)))+ if isinstance(value, str):+ text = value.strip().rstrip("%")+ try:+ number = float(text)+ except ValueError:+ return _NEUTRAL_CONFIDENCE+ # "85%" and "85" both mean 0.85; a bare 0.85 already does.+ if number > 1.0:+ number /= 100.0+ return max(0.0, min(1.0, number))+ return _NEUTRAL_CONFIDENCE++def _parse_llm_response(text: str) -> dict[str, Any]:- """Extract the JSON verdict from the LLM response, tolerating markdown fences."""- cleaned = text.strip()- if cleaned.startswith("```"):- lines = cleaned.split("\n")- lines = [line for line in lines if not line.strip().startswith("```")]- cleaned = "\n".join(lines).strip()+ """Extract the JSON verdict from the LLM response, tolerating markdown fences.++ Extraction is shared with every other caller through+ ``app.llm.structured_output.extract_json_block``: fences, and prose on+ either side of the body. What stays here is the part that is specific to a+ triage verdict — the taxonomy, the confidence gate, and the one repair+ below. Extraction is a property of LLM replies; a verdict is not.+ """+ cleaned = extract_json_block(text)try:data = json.loads(cleaned)@@ -272,8 +318,7 @@ def _parse_llm_response(text: str) -> dict[str, Any]:if verdict not in LLM_VERDICTS:verdict = TRUE_POSITIVE- confidence = float(data.get("confidence", 0.5))- confidence = max(0.0, min(1.0, confidence))+ confidence = _coerce_confidence(data.get("confidence"))rationale = data.get("rationale", "No rationale provided by LLM.")@@ -312,7 +357,7 @@ async def run_auto_triage(state: InvestigationState) -> InvestigationState:# and auto_triage_node catches AutoTriageError specifically — so# constructing outside would have failed the whole graph run over a# configuration problem the deterministic path handles fine.- llm = make_chat_model("triage", temperature=0.0, max_tokens=512)+ llm = make_chat_model("triage", temperature=0.0, max_tokens=512, json_output=True)response = await safe_ainvoke(llm,[diff --git a/services/agents/app/llm/factory.py b/services/agents/app/llm/factory.pyindex 877fad935..46a6366a8 100644--- a/services/agents/app/llm/factory.py+++ b/services/agents/app/llm/factory.py@@ -121,6 +121,7 @@ def make_chat_model(*,temperature: float = 0.0,max_tokens: int | None = None,+ json_output: bool = False,**kwargs: Any,) -> ChatOpenAI:"""Build a :class:`ChatOpenAI` for a task ``role`` (alias + gateway base URL).@@ -128,12 +129,38 @@ def make_chat_model(The returned model is **not** contract-guarded — every caller still routes theinvocation through :func:`app.llm.safe_ainvoke`, which enforces the inputcontract. Extra ``kwargs`` pass straight through to ``ChatOpenAI``.++ Set ``json_output`` when the caller parses the reply as JSON. It asks the+ provider to constrain generation to a valid JSON object instead of leaving+ the model free to emit prose that merely looks like one.++ This is worth more than it sounds on a small local model. Measured over 50+ alerts through the gateway against the bundled+ ``llama3.2:3b-instruct-q4_K_M``, replies the triage parser could use went+ from 44/50 to 50/50. Every one of the six failures had a correct verdict and+ confidence and a malformed ``rationale`` — an unquoted value, or an invalid+ ``\\'`` escape. None was truncated. Constraining the grammar removes that+ class outright, which no amount of parsing after the fact can.++ Safe on providers that do not support it: the gateway ships+ ``drop_params: true`` (``infra/litellm/config.yaml``), so the parameter is+ dropped rather than erroring, and the caller degrades to today's behaviour."""override = _llm_override.get()model = (override or {}).get("model") or resolve_model_alias(role)params: dict[str, Any] = {"model": model, "temperature": temperature}if max_tokens is not None:params["max_tokens"] = max_tokens+ if json_output:+ # Via ``model_kwargs`` rather than as a top-level argument. ChatOpenAI+ # does not declare ``response_format`` as a field, so passing it+ # directly still works but warns "response_format is not default+ # parameter" on every single construction — noise on a hot path, for a+ # parameter we are deliberately setting.+ params["model_kwargs"] = {+ **kwargs.pop("model_kwargs", {}),+ "response_format": {"type": "json_object"},+ }base_url = (override or {}).get("base_url") or resolve_base_url(model)assert_routable(model, base_url)if base_url:diff --git a/services/agents/app/llm/structured_output.py b/services/agents/app/llm/structured_output.pyindex 1600a8646..937d1f10f 100644--- a/services/agents/app/llm/structured_output.py+++ b/services/agents/app/llm/structured_output.py@@ -1,11 +1,19 @@"""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.+preamble, or emit a field that violates the contract. Passing a half-parsed+structured output downstream (into an autonomy decision, a ledger entry) is+worse than failing.++This module claimed to have replaced the agents' ad-hoc parsers. It had not:+until `auto_triage_agent` was wired to `extract_json_block`, nothing in+production imported it at all, and its tests were the only callers — a passing+test on an uncalled function looks exactly like a working feature.++`auto_triage_agent` now shares the extraction step. `cloud_agent`,+`identity_agent`, `insider_threat_agent` and `phishing_agent` each still carry+their own `_parse_llm_response`; that is a real remaining gap, recorded here+rather than described as done.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@@ -35,19 +43,60 @@ class ParseResult: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.+ Strips ``` fences and prose on *both* sides of the JSON body. Does NOT+ attempt to repair invalid JSON — a reply we can't parse cleanly is a+ failure, by design.++ Trailing prose used to defeat this: it trimmed everything before the first+ ``{`` and nothing after the last ``}``, so a model that answered correctly+ and then added "Hope that helps!" was scored as unparseable. Extraction and+ repair are different things — finding where the JSON ends is still reading+ what the model said, not guessing at what it meant.++ The scan is brace-balanced and string-aware, because a closing brace inside+ a string value ("rationale": "he typed }") is not the end of the object."""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()+ starts = [i for i in (stripped.find("{"), stripped.find("[")) if i != -1]+ if not starts:+ return stripped.strip()+ start = min(starts)+ end = _matching_close(stripped, start)+ return (stripped[start:end] if end is not None else stripped[start:]).strip()+++def _matching_close(text: str, start: int) -> int | None:+ """Index just past the bracket that closes the one at ``start``.++ ``None`` when it is never closed, so the caller keeps the remainder and+ lets the JSON parser report the truncation rather than silently trimming.+ """+ opener = text[start]+ closer = {"{": "}", "[": "]"}[opener]+ depth = 0+ in_string = False+ escaped = False+ for idx in range(start, len(text)):+ char = text[idx]+ if in_string:+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == '"':+ in_string = False+ continue+ if char == '"':+ in_string = True+ elif char == opener:+ depth += 1+ elif char == closer:+ depth -= 1+ if depth == 0:+ return idx + 1+ return Nonedef parse_structured(diff --git a/services/agents/tests/test_structured_output_extraction.py b/services/agents/tests/test_structured_output_extraction.pynew file mode 100644index 000000000..ad4a092b4--- /dev/null+++ b/services/agents/tests/test_structured_output_extraction.py@@ -0,0 +1,75 @@+"""The shared extractor must survive prose on both sides of the JSON.++It trimmed everything before the first ``{`` and nothing after the last ``}``,+so a model that answered correctly and then added a closing pleasantry was+scored unparseable. Small local models do this constantly.++The module also advertised itself as the replacement for the agents' ad-hoc+parsers while nothing in production imported it. These tests pin both halves:+the extraction behaviour, and that auto-triage actually calls it.+"""++from __future__ import annotations++import ast+import json+from pathlib import Path++import pytest+from app.llm.structured_output import extract_json_block, parse_structured++AGENT_SOURCE = Path(__file__).resolve().parent.parent / "app" / "agents" / "auto_triage_agent.py"+++ ("reply", "expected"),+ [+ ('{"a": 1}', {"a": 1}),+ ('{"a": 1}\n\nHope that helps!', {"a": 1}),+ ('Sure! Here is the verdict:\n{"a": 1}\nLet me know.', {"a": 1}),+ ('```json\n{"a": 1}\n```', {"a": 1}),+ ('```json\n{"a": 1}\n```\nAnything else?', {"a": 1}),+ ('[{"a": 1}]\ntrailing', [{"a": 1}]),+ # A brace inside a string is not the end of the object.+ ('{"note": "he typed }"}\nbye', {"note": "he typed }"}),+ # An escaped quote must not end the string scan early.+ ('{"note": "say \\"hi\\" }"}\nbye', {"note": 'say "hi" }'}),+ # Nesting.+ ('{"o": {"i": [1, 2]}}\nthanks', {"o": {"i": [1, 2]}}),+ ],+)+def test_extracts_the_body_whatever_surrounds_it(reply: str, expected: object) -> None:+ assert json.loads(extract_json_block(reply)) == expected+ assert parse_structured(reply).ok+++def test_an_unclosed_object_is_left_for_the_parser_to_report() -> None:+ """Truncation must surface as a parse failure, not a silent trim.++ Returning the remainder means json reports where it ran out; trimming to+ the last balanced point would invent an object the model never closed.+ """+ result = parse_structured('{"a": 1, "b": "unterminated')+ assert not result.ok+ assert "invalid JSON" in result.error+++def test_prose_with_no_json_at_all_still_fails() -> None:+ assert not parse_structured("I think this alert is fine, honestly").ok+++def test_auto_triage_uses_the_shared_extractor() -> None:+ """The wiring, read from source.++ The module documented itself as the single parser while having no+ production caller. This fails if auto-triage goes back to its own+ fence-stripping.+ """+ tree = ast.parse(AGENT_SOURCE.read_text())+ imported = {+ alias.name+ for node in ast.walk(tree)+ if isinstance(node, ast.ImportFrom) and node.module == "app.llm.structured_output"+ for alias in node.names+ }+ assert "extract_json_block" in imported, "auto-triage no longer shares the extractor"diff --git a/services/agents/tests/test_triage_confidence_coercion.py b/services/agents/tests/test_triage_confidence_coercion.pynew file mode 100644index 000000000..813552476--- /dev/null+++ b/services/agents/tests/test_triage_confidence_coercion.py@@ -0,0 +1,74 @@+"""A verdict must not be discarded because the confidence field was odd.++``float(data.get("confidence", 0.5))`` was unguarded, so a reply of+``"confidence": "high"`` raised ``ValueError``; the caller converts that into an+``AutoTriageError`` and falls back to deterministic triage, throwing away a+verdict and rationale that may have been perfectly good.++This was not the cause of the measured failures — those were all malformed+``rationale`` — but it is reachable by any model, and a fallback nobody can+explain is worse than one that names its reason.++The safety property this must not break: the *verdict* still fails closed. A+degraded confidence lands at 0.5, below the 0.85 auto-close default, so it+routes to a human.+"""++from __future__ import annotations++import json++import pytest+from app.agents.auto_triage_agent import AUTO_CLOSE_THRESHOLD, _parse_llm_response+++def _reply(confidence: object) -> str:+ return json.dumps({"verdict": "benign", "confidence": confidence, "rationale": "because"})+++ ("raw", "expected"),+ [+ (0.8, 0.8),+ (1, 1.0),+ (0, 0.0),+ ("0.8", 0.8),+ (" 0.8 ", 0.8),+ ("85%", 0.85),+ ("85", 0.85), # a bare out-of-range number is a percentage+ (1.7, 1.0), # clamped+ (-0.4, 0.0), # clamped+ ],+)+def test_reads_the_confidences_a_model_actually_emits(raw: object, expected: float) -> None:+ assert _parse_llm_response(_reply(raw))["confidence"] == pytest.approx(expected)++[email protected]("raw", ["high", "very confident", "", None, True, False, [], {}])+def test_unreadable_confidence_keeps_the_verdict_instead_of_raising(raw: object) -> None:+ """The regression: this used to raise and discard the whole reply."""+ parsed = _parse_llm_response(_reply(raw))+ assert parsed["verdict"] == "benign"+ assert parsed["rationale"] == "because"+ assert 0.0 <= parsed["confidence"] <= 1.0++[email protected]("raw", ["high", None, True])+def test_a_degraded_confidence_cannot_auto_close(raw: object) -> None:+ """The safety property. An unread field must not close an alert."""+ assert _parse_llm_response(_reply(raw))["confidence"] < AUTO_CLOSE_THRESHOLD+++def test_a_missing_confidence_still_defaults() -> None:+ parsed = _parse_llm_response(json.dumps({"verdict": "benign", "rationale": "r"}))+ assert parsed["confidence"] < AUTO_CLOSE_THRESHOLD+++def test_an_unparseable_reply_still_fails_closed() -> None:+ """Tolerance for one odd field must not become tolerance for anything.++ The fail-closed contract is the reason this module is trusted; a reply that+ is not a JSON object still raises so the caller falls back.+ """+ with pytest.raises(Exception): # noqa: B017 — any failure is the contract+ _parse_llm_response("I think this alert is probably fine, honestly")diff --git a/services/agents/tests/test_triage_structured_output.py b/services/agents/tests/test_triage_structured_output.pynew file mode 100644index 000000000..9eaf8974c--- /dev/null+++ b/services/agents/tests/test_triage_structured_output.py@@ -0,0 +1,97 @@+"""Auto-triage must ask the provider for JSON, not hope for it.++Measured over 50 alerts through the gateway against the bundled+``llama3.2:3b-instruct-q4_K_M``, replies the triage parser could use went from+44/50 to 50/50 once ``response_format={"type": "json_object"}`` was requested.+Every one of the six failures carried a correct verdict and confidence and a+malformed ``rationale`` — an unquoted value, or an invalid ``\\'`` escape — and+none was truncated. Constraining the grammar removes that class at the source.++These tests read the request payload LangChain would actually send, rather than+asserting that a keyword argument was passed. The parameter has moved between+top-level and ``model_kwargs`` across langchain-openai versions, so checking the+call signature would pass while the provider received nothing.++Reproduce the measurement with::++ python3 scripts/measure_triage_reliability.py --attempts 50 --json-mode+"""++from __future__ import annotations++import ast+import warnings+from pathlib import Path++import pytest+from app.llm.factory import make_chat_model++AGENT_SOURCE = Path(__file__).resolve().parent.parent / "app" / "agents" / "auto_triage_agent.py"+++def _payload(model) -> dict:+ return model._get_request_payload([("human", "hi")])++[email protected](autouse=True)+def _gateway(monkeypatch: pytest.MonkeyPatch) -> None:+ """A routable gateway, so the factory does not refuse an alias."""+ monkeypatch.setenv("LLM_GATEWAY_URL", "http://gateway.invalid:4000")+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+++def test_json_output_reaches_the_request_payload() -> None:+ payload = _payload(make_chat_model("triage", temperature=0.0, max_tokens=512, json_output=True))+ assert payload.get("response_format") == {"type": "json_object"}+++def test_json_output_is_opt_in() -> None:+ """A caller that parses prose must not silently get JSON mode."""+ assert "response_format" not in _payload(make_chat_model("triage", temperature=0.0))+++def test_json_output_preserves_the_other_parameters() -> None:+ """The fix must not cost the sampling settings triage depends on."""+ payload = _payload(make_chat_model("triage", temperature=0.0, max_tokens=512, json_output=True))+ assert payload["temperature"] == 0.0+ # langchain-openai renamed this; accept whichever key this version emits,+ # but require the value to have survived.+ assert payload.get("max_completion_tokens", payload.get("max_tokens")) == 512+++def test_json_output_does_not_discard_caller_model_kwargs() -> None:+ """Setting response_format must merge, not replace."""+ model = make_chat_model("triage", json_output=True, model_kwargs={"seed": 7})+ payload = _payload(model)+ assert payload.get("seed") == 7+ assert payload.get("response_format") == {"type": "json_object"}+++def test_json_output_emits_no_warning() -> None:+ """Constructed on a hot path; a per-call UserWarning is log noise.++ langchain warns when an undeclared field is passed top-level, which is why+ the factory routes it through ``model_kwargs``.+ """+ with warnings.catch_warnings():+ warnings.simplefilter("error", UserWarning)+ make_chat_model("triage", temperature=0.0, max_tokens=512, json_output=True)+++def test_auto_triage_requests_structured_output() -> None:+ """The call site, read from source — this is what fails on the pre-fix tree.++ Parsed rather than grepped: a string match would be satisfied by the word+ appearing in a comment explaining why it is absent.+ """+ tree = ast.parse(AGENT_SOURCE.read_text())+ calls = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "make_chat_model"+ ]+ assert calls, "auto_triage_agent no longer calls make_chat_model — update this test"+ for call in calls:+ flag = next((kw for kw in call.keywords if kw.arg == "json_output"), None)+ assert flag is not None, "auto-triage parses the reply as JSON but does not ask for JSON"+ assert isinstance(flag.value, ast.Constant) and flag.value.value is True