From d987eb87201d68d9ce7cc48756934b75af830de3 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Tue, 10 Nov 2026 05:09:28 +0000 Subject: [PATCH 1/3] Add LLM structured output guardrails skill --- skillbook/skills.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/skillbook/skills.json b/skillbook/skills.json index 9224311..fe293d4 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -1060,6 +1060,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-pii-redaction.instructions.md` with applyTo for `**/llm/**`, `**/*Redact*.java`, `**/*Pii*.java`, `**/*Vault*.java`, `**/gateway/**`, and `**/application*.{yml,yaml,properties}`. Optional on-demand procedure at `.github/skills/llm-pii-redaction-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-pii-redaction-guardrails/SKILL.md` plus a CLAUDE.md fact that provider calls, logs, traces, caches, and eval fixtures see only the redacted view, and the default policy is fail-closed. Codex: a short \"LLM redaction\" brief in root `AGENTS.md` (the pipeline order, the route policy, the leak-test command) while the procedure stays in SKILL.md. Pair with llm-app-prompt-injection-guardrails for trust boundaries and output sinks, spring-boot-structured-logging-guardrails for log shape, llm-gateway-routing-fallback-guardrails for the call that happens after redaction, llm-eval-ci-regression-gate for golden-set hygiene, and llm-cost-latency-budget-guardrails for the latency stage. This skill owns detection, redaction modes, the per-request vault, streaming hold-back, and the leak tests.", "body": "# Skill: LLM PII and Secret Redaction Guardrails\n\n## Goal\n\nKeep personal data and secrets out of places they do not belong when a Java or Spring Boot service calls a model. The gateway (or the app in front of Azure OpenAI, Amazon Bedrock, OpenRouter, or any OpenAI-compatible provider) produces one redacted view of the prompt, and that view is what the provider, the logs, the traces, the prompt cache, and the eval fixtures are allowed to see.\n\nThis skill owns where that view is built, the detector stack, the three redaction modes, streaming chunk boundaries, the per-request vault, the per-route fail-closed or fail-open policy, audit counters that carry entity types and not values, the latency budget for the stage, and the test that proves a raw value never reaches the stub provider or the log appender.\n\nTrust boundaries, tool agency, and output encoding stay in **llm-app-prompt-injection-guardrails** (that skill's output screen and \"do not log the payload\" rule are the reason this pipeline exists; they are not the pipeline). Log shape — JSON, MDC, levels — stays in **spring-boot-structured-logging-guardrails**. Alias routing, fallback, and attempt metadata stay in **llm-gateway-routing-fallback-guardrails**, which runs after this stage and must not see a raw body. Golden-set versioning and the ban on real customer rows stay in **llm-eval-ci-regression-gate**. Recording this stage's time inside gateway overhead stays in **llm-cost-latency-budget-guardrails**. Column masking inside a warehouse job stays in **data-platform-pipeline-review**.\n\nA line in the system prompt that says \"do not reveal personal data\" is not a control. Public guidance on sensitive-information disclosure (OWASP LLM Top 10, sensitive information disclosure) treats that wording as bypassable. The control is this code path.\n\n## When to apply\n\n- A new LLM gateway, or a Spring AI, LangChain4j, or plain HTTP client that forwards chat or completions\n- A route whose prompt includes free text, retrieved chunks, tool results, or file extracts\n- A review that finds prompt or completion text in logs, traces, a prompt cache, or an eval JSONL file\n- Adding a named-entity recognizer beside local patterns (a hosted PII API such as Azure AI Language, or a self-hosted analyzer in the detect-then-anonymize style)\n- A streaming endpoint where a card number, an email, or a placeholder can split across chunks\n\n## Where redaction runs\n\nBuild the redacted view once, after the caller is authenticated and before any of the following:\n\n1. **Before the provider call.** Redact user and tool messages, and any retrieved text that will be copied into the prompt. Scan system instructions and tool schemas for secrets the app interpolated; do not strip role names or tool names. Every fallback attempt from **llm-gateway-routing-fallback-guardrails** sends this same view. Do not redact a different way per provider.\n2. **Before logs, metrics, and traces.** Application logs, client wire logs, span attributes, and exception messages use this view. A debug flag does not open a second path for the raw body.\n3. **Before prompt caches and eval fixtures.** The cache key and the stored completion use the redacted text. An export that builds a golden file writes the redacted view or a synthetic case, never a customer transcript. **llm-eval-ci-regression-gate** already forbids real personal data in `evals/golden`; this stage is how that file stays clean.\n\nOn the way out, only a reversible route writes original values back, and only onto the response bytes for that caller. Logs, traces, the cache, and the next provider call keep placeholders. After restore, scan the model text again for values the model introduced (a card or a secret that was not in the request). Mask those. Do not add them to the vault.\n\n## Detection layers\n\nRun the layers below and collect spans on the original string. Combine them in Overlap resolution before replacing anything. A finding record stores type, start, end, and action. It does not store the matched text. The vault, when the mode needs one, is a separate request-scoped object.\n\n### 1. Deterministic patterns and checksums (always on)\n\nIn-process, no network. Cover the types the route turns on:\n\n- **Email.** A practical `local@domain` pattern with a dot in the domain. Plus-tags (`ada+news@example.com`) match. Do not try to encode the full address RFC in one expression.\n- **Phone.** A leading `+` or a national trunk pattern the product actually receives, plus a digit length for that pattern. A bare run of digits inside an order id or a timestamp is not a phone.\n- **Payment card.** Take a 13–19 digit candidate, ignore spaces and dashes, and accept it only when it passes the Luhn check. From the right, double every second digit, subtract 9 when a product is over 9, and accept when the sum is divisible by 10. A 16-digit run that fails Luhn is not a card.\n- **National IDs.** Only schemes this service is in scope to handle. Name each scheme in config and check the published length and checksum for that scheme. Leave the detector off until at least one scheme is named. There is no single \"world ID\" pattern.\n- **API keys and other secrets.** Known assignment shapes (`api_key=`, `Bearer ` followed by a token) and published key prefixes the team has listed. A match is a credential, not a personal-data field.\n- **JWTs.** Three base64url segments whose header decodes as JSON containing `alg`. The token is a secret even when you do not check the signature. Signature checks belong to **jwt-oauth-security-review**, not here.\n\nWhen a scheme has a checksum, a pattern hit that fails the checksum is not a finding. Secrets and JWTs are never reversible, including on a route whose mode restores other entities. A longer personal-data span that contains or overlaps one does not make it reversible. Overlap resolution keeps that classification.\n\n### 2. Optional named-entity recognizer\n\nUse this for person names, street addresses, and other free text the patterns miss. Two shapes are enough:\n\n- A hosted PII API (Azure AI Language is the usual one on Azure). It returns entity category, confidence, and a redacted string. Call it with workload identity on a private endpoint. Do not enable the service's own payload logging.\n- A self-hosted analyzer in the detect-then-anonymize style: recognizers (patterns, checksums, a model) produce spans, and a second step applies an operator (mask, replace, hash). Keep that second step inside this gateway so the operator and the vault stay in one place.\n\nRules for either shape:\n\n- Off unless the route sets `ner: true`. A confidence floor is set per entity type; start from the false-positive fixtures and record the floor you picked. A low model score does not cancel a deterministic hit, and it does not remove that hit's bytes from the union in Overlap resolution.\n- Drop categories that wreck prompts. Role labels (`user`, `assistant`, `system`) and, when the product needs them, dates. Exclude them in config, not in a prompt.\n- Honor the service's per-document size cap. Chunk with overlap, detect on the chunks, and map spans back onto the original string. Do not glue the service's redacted chunks together; that shifts offsets and can break JSON.\n- The recognizer sees raw text, so its timeout is part of the route deadline. A timeout is a detector error, handled by the route policy below.\n\n### 3. Allowlist\n\nPer route, a reviewed list of literals and patterns that must survive: the public support address, product names, JSON keys, the placeholder syntax itself.\n\n- A span that matches a detector and the allowlist is kept and counted as `allowed`. That match removes only the span that matched. A different finding that overlaps it stays, including an API key or JWT.\n- Do not allowlist \"any 16 digits\", a customer-id shape with no namespace, or a test card number in a production config. Test values live in fixtures.\n- The allowlist is data, reviewed in the same pull request as a behavior change.\n\n## Overlap resolution\n\nRun this after the three layers above and before any replacement, on the request and again on the response scan. Spans use the original string, start inclusive and end exclusive. Take the findings that remain after checksum failures are dropped and allowlist matches are removed.\n\nThe sensitive set is the union of those spans. Redact every byte in the union. Split the union at each span boundary, then label the slices:\n\n1. A slice that intersects an API key, a JWT, or another secret is non-restorable. Mask it, or replace it with a typed placeholder that is absent from the vault and is never restored. The secret keeps that classification when a longer reversible NER or other personal-data span contains it, and when the two spans only partly overlap. Those shared bytes stay out of the vault, so restoring the personal-data slices does not restore the secret. If the slice intersects more than one secret, the label is the secret finding that starts earlier. If those starts are equal, the label is the secret finding that ends later. The slice stays non-restorable either way.\n2. A slice with no secret follows the route mode. If at least one deterministic finding covers it, the label is the deterministic finding that starts earlier. If those starts are equal, the label is the deterministic finding that ends later. An NER finding does not supply the label for that slice. Bytes that only an NER span covers stay in the union and follow the route mode. If every finding on the slice is from the recognizer, the label is the one that starts earlier. If those starts are equal, the label is the one that ends later.\n3. Merge two adjacent slices only when entity type, action, and restorability match. A non-restorable slice stays its own replacement, so it is not folded into a reversible token.\n\nLength and confidence are not inputs to coverage or to restorability. The replacement units are these slices. Apply them from the end of the string so earlier offsets stay valid. On a stream, resolve the buffer before flushing a prefix, and leave any byte still covered by a span in the buffer unflushed.\n\nTwo offset examples, on the original string:\n\n- Nested. NER personal-data is `[0, 100)` and an API key is `[40, 60)`. The redacted view covers `[0, 100)`. `[40, 60)` is non-restorable. `[0, 40)` and `[60, 100)` follow the route mode.\n- Partial. An email is `[0, 20)` and an API key is `[10, 40)`. The redacted view covers `[0, 40)`. `[10, 40)` is non-restorable, so the shared email bytes are not restored. `[0, 10)` follows the route mode.\n\nThis combines spans the enabled detectors returned. A value no detector marked is unchanged. A passing overlap test does not mean the recognizer or the patterns found every personal-data value or secret.\n\n## Redaction modes\n\nOne mode per route, applied to the whole request. Pick it in config.\n\n| Mode | What the model sees | Vault | What the caller sees |\n|---|---|---|---|\n| `mask` | A character mask, or last-4 only where the scheme says that remainder is safe to show | None | The same mask |\n| `typed-placeholder` | `[EMAIL_1]`, `[PHONE_2]`. The same value in this request always gets the same token, so the model can refer to it | Built and discarded. Not used to restore | The placeholders |\n| `reversible-token` | The same placeholders | In-memory map for this request only | Originals, and only on the response path |\n\nPlaceholder shape is `[TYPE_n]`: `TYPE` from a fixed enum, `n` starting at 1 per type per request. Keep the type names short and the counter small so the longest placeholder is a known bound (well under 32 characters). The model sees the type, which is what keeps the prompt usable: \"reply to [EMAIL_1]\" still has a referent. A solid mask does not.\n\nVault rules for `reversible-token`:\n\n- Request-scoped memory inside the process that calls the provider and writes the response. Clear it in a `finally` block. It is not written to logs, traces, the prompt cache, Redis, or a second replica.\n- Keyed by this request only. Two callers who both produce `[EMAIL_1]` do not share a map.\n- Restore only placeholders this request minted, and only onto the bytes written to that caller.\n- Secrets and JWTs stay on `mask` or `typed-placeholder` even when the route's mode is `reversible-token`. A personal-data token does not contain their bytes when the spans overlap. Overlap resolution is the split that enforces this.\n- A later support tool that needs the mapping is a different store: encrypted, access-logged, short retention. It is not Log Analytics and it is not the vault.\n\nCache interaction: store the redacted completion. On a hit, restore with this request's vault only. A placeholder this request did not mint stays a placeholder (or becomes a mask). Applying another request's map would attach the wrong person to the token.\n\nIf redaction leaves a message that is only placeholders, send it. The model can answer or ask for a non-sensitive restatement. Do not paste the raw text back to \"help\" the model. After replacement, parse the message list again. If the body is no longer valid JSON, fail the request with the route policy. Do not send a broken document and hope the provider accepts it.\n\nLeave JSON keys, role names, tool names, and the document delimiters from **llm-app-prompt-injection-guardrails** intact. Redact what is inside them.\n\n## Streaming and chunk boundaries\n\nThe request is fully buffered and redacted before the provider call. Chunking matters on the response, and on any detector you run over model output.\n\nA detector that looks at one chunk in isolation misses a card split as `\"4242 42\"` + `\"42 4242 4242\"` and misses a placeholder split as `\"[EMA\"` + `\"IL_1]\"`. Hold a tail:\n\n1. Append the new payload to a buffer. Redact the text of an SSE `data:` field. Leave the event framing alone, and do not put prompt text in a heartbeat comment.\n2. Resolve overlaps on the buffer, then flush only the prefix that cannot still grow into an entity you scan or into a placeholder. Hold the suffix. Leave any byte still covered by a span in the buffer unflushed.\n3. Size the hold to the longest entity you scan. Cap scanned secrets (a JWT is the usual long one; pick a cap, for example 512 characters, and document it) and add a small overlap when the response recognizer needs context. Placeholder restore holds only the longest placeholder you issue, which is much shorter.\n4. Do not split a UTF-8 sequence.\n5. When the stream ends, run the same detector and the same overlap resolution on the tail and flush it.\n6. On error or client cancel, drop the buffer and the vault. The error log gets the error class, not the buffer.\n\nBytes you flush to the log and the trace are the redacted form. In reversible mode the caller socket gets restored text, and the log still shows `[EMAIL_1]`. Restored text is not an MDC value and not a span attribute.\n\nThis hold-back is independent of the routing skill's commit rule. That rule decides whether a fallback may start. This one decides which characters of a chunk are safe to emit. Apply redaction before the gateway treats a byte as committed model output.\n\n## Fail-closed and fail-open\n\nThe policy is explicit on every route. The default is fail-closed. Fail-open is a written exception for a route whose data class is not sensitive.\n\n- **Fail-closed.** The recognizer throws, times out, or returns a result you cannot parse: do not call the provider, do not write the raw body to a cache or a log, and return problem+json `503` with code `redaction_unavailable`. Zero findings is a success, not an error.\n- **Fail-open.** The same recognizer failure: call the provider with whatever the deterministic layer already redacted, increment `detector_error`, and alert. Fail-open does not mean \"skip redaction\". If the in-process deterministic scanner throws, fail closed anyway. That throw is a bug, not a dependency outage.\n- Deterministic findings already in hand are kept under both policies.\n\n```yaml\nllm:\n redaction:\n default-policy: fail-closed\n secret-scan-cap-chars: 512\n detectors:\n deterministic:\n entities: [email, phone, payment_card, api_key, jwt]\n # national_id stays off until schemes are listed\n ner:\n enabled: false\n timeout: 200ms\n min-confidence: 0.75\n exclude: [person_type, date]\n routes:\n support-chat:\n policy: fail-closed\n mode: reversible-token\n ner: true\n public-faq:\n policy: fail-open\n mode: typed-placeholder\n ner: false\n allowlist:\n literals:\n - support@example.com\n```\n\n## Never log the raw prompt\n\nOne filter is the only code allowed to record an LLM body, and it records the redacted view.\n\n- No `log.debug` of the serialized request or response on the provider client. No HTTP wiretap that dumps bodies unless the tap runs the redactor first.\n- Problem details and provider-error handling include entity counts and types. Provider error documents often echo the prompt; do not copy them into logs (**llm-gateway-routing-fallback-guardrails** already refuses that copy).\n- Metric labels and trace attributes are route, entity type, action, and counts. Not the value, and not a hash of the value. Emails, phones, and national IDs are low-entropy; a hash is a lookup table waiting for a wordlist.\n- MDC, baggage, and the usage store from **llm-cost-latency-budget-guardrails** do not carry message text.\n\n## Audit counters\n\n- `llm_redaction_entities_total` — counter. Labels: `route`, `entity_type`, `action` (`masked`, `placeholder`, `tokenized`, `allowed`, `detector_error`).\n- `llm_redaction_seconds` — histogram. Labels: `route`, `outcome` (`ok`, `failed_closed`, `failed_open`).\n- Span attributes: `redaction.entity_count` (a number) and `redaction.mode`. No span event contains the text.\n\nAlert when `detector_error` is non-zero on a fail-closed route, and when entity counts fall to zero while traffic does not (a detector turned off by accident).\n\n## Latency budget\n\nSet a budget and measure it. A deterministic pass over a typical prompt (about 8 KB) should stay within a few milliseconds on a warm JVM; treat a p95 above about 10 ms without a recognizer as a bug (a catastrophic expression, or scanning a binary attachment that should have been skipped). Record the stage on the gateway-overhead histogram in **llm-cost-latency-budget-guardrails** (auth, redaction, routing).\n\nA recognizer adds a network call. Put its timeout in the 150–300 ms band unless the route's deadline forces a tighter cap, and subtract that time from the alias deadline before the routing walk starts, the same way `minAttemptBudget` is applied in **llm-gateway-routing-fallback-guardrails**. Call the recognizer once per request. The log path reuses the view; it does not call the recognizer again.\n\nIf recognizer p95 does not fit the route SLO, turn it off on that route. Do not move the provider call ahead of the deterministic scan to save the time.\n\n## Tests\n\nSynthetic fixtures only. No customer dumps, no production allowlist of test cards.\n\n**Golden file.** For each case: input, expected spans (type, start, end), and the expected string under `mask`, `typed-placeholder`, and `reversible-token`. Include an email with a plus-tag, a phone with a country code, a published test PAN written with spaces that passes Luhn, a JWT-shaped token, and an `api_key=` assignment. Add a national-id case only for a scheme the config names.\n\n**False positives that must not fire.** UUIDs, git SHAs, semver, epoch milliseconds, order numbers, the role words `user` and `assistant`, the placeholder `[EMAIL_1]` itself, and a 16-digit run that fails Luhn.\n\n**False negatives that must fire.** The plus-tag email, the dashed PAN, the country-code phone, and a JWT with no `Bearer` prefix.\n\n**Overlap (reversible mode).** These cases check combination. Stub the recognizer so it returns the personal-data span at the fixture offsets, and let the deterministic layer find the API key or JWT. A live recognizer is not what this test measures.\n\n- **Nested.** The stubbed personal-data span strictly contains the secret. In the stub request and the log appender, the secret is absent and the personal-data text outside the secret is absent. The caller response and the vault do not contain the secret. Restoring the personal-data slices does not put the secret back.\n- **Partial overlap.** The stubbed personal-data span and the secret span overlap, and each extends past the other. In the stub request and the log appender, the secret, the shared bytes, and the personal-data-only tail are absent. The caller response and the vault do not contain the secret, the shared bytes, or the secret-only tail.\n- The message list still parses as JSON.\n- Passing these cases does not mean every secret in real traffic was detected. A secret no enabled detector returned is outside this test.\n\n**Leak test (required).** A stub provider (WireMock, MockWebServer, or the suite's existing stub) and a log appender (`ListAppender` or `OutputCaptureExtension`). Post a chat body that contains the fixture email, the spaced PAN, and the JWT.\n\n- The stub's recorded body contains none of those strings (nor the PAN with spaces removed).\n- No logged event contains them.\n- Counters increment for `email`, `payment_card`, and `jwt`.\n- On a reversible route, the stub returns text that echoes `[EMAIL_1]`. The caller response contains the original email. The appender contains `[EMAIL_1]` and does not contain the email.\n- After the call returns, including on the exception path, the vault is empty.\n\n**Streaming.** The stub splits the PAN across two deltas. The bytes written to the client and the bytes written to the appender do not contain the PAN. A second case splits `[EMAIL_1]` across two deltas and, on a reversible route, the caller receives the restored email once.\n\n**Policy.** Recognizer throws on a fail-closed route: the stub receives zero requests, the caller gets `503` `redaction_unavailable`, and the raw fixture is absent from the appender. The same throw on a fail-open route: the deterministic email is still redacted, the stub receives one request, `detector_error` increments.\n\n**Cache.** Two requests redact to the same placeholder shape. The second response does not restore the first caller's value.\n\n## Workflow\n\n1. Inventory every call site, logger, wiretap, cache, and eval export that can see a prompt or a completion.\n2. Add the deterministic layer, the three modes, overlap resolution, and `default-policy: fail-closed`. Secrets stay non-reversible on every slice they touch, and the union of overlapping spans is what gets redacted.\n3. Point the provider client, logs, traces, cache, and fixture export at the redacted view.\n4. Add response hold-back. Add restore-on-the-way-out only for routes that set `reversible-token`.\n5. Add the counters and the latency histogram. Check the label set.\n6. Land the golden, false-positive, false-negative, streaming, policy, and leak tests before a route is enabled.\n7. Enable the recognizer only on routes whose deadline still fits the timeout, with the excluded categories written down.\n\n## Tool-specific notes\n\n- **GitHub Copilot:** path-scoped `.github/instructions/llm-pii-redaction.instructions.md` with `applyTo` for `**/llm/**`, `**/*Redact*.java`, `**/*Pii*.java`, `**/*Vault*.java`, `**/gateway/**`, and `**/application*.{yml,yaml,properties}`. Put the pipeline order, the mode table, and the fail-closed default at the top. Keep the procedure in an optional `.github/skills/llm-pii-redaction-guardrails/SKILL.md`. Ask for the call-site inventory before editing a filter.\n- **Claude Code:** `.claude/skills/llm-pii-redaction-guardrails/SKILL.md` holds the procedure. Add one `CLAUDE.md` fact: \"LLM provider calls, logs, traces, caches, and eval fixtures see only the redacted view. The default redaction policy is fail-closed. Secrets are never restored.\"\n- **Codex:** root `AGENTS.md` stays a short brief — pipeline order, the config key for the route policy, and the leak-test command. The procedure lives in `SKILL.md`, or in a nested `AGENTS.md` beside the gateway module when the repo already uses nested briefs. Do not paste this whole skill into `AGENTS.md`.\n\n## Anti-patterns\n\n- Redacting in the log encoder and still sending the raw body to the provider\n- A debug flag, wiretap, or `toString()` on the request object that prints the raw prompt in production\n- Treating a system-prompt sentence as the redaction control\n- A vault in a shared cache, keyed by a guessable id, or reused across callers\n- Restoring placeholders into the log line, the trace, or the cached completion\n- A recognizer as the only detector, so a timeout on a fail-open route sends raw cards\n- Matching every 16-digit run and skipping Luhn\n- A production allowlist of test PANs\n- Scanning each stream chunk on its own, with no tail hold\n- Fail-open as the unspoken default\n- Entity values or their hashes as metric labels\n- A customer transcript committed under `evals/golden`\n- Calling the provider after the recognizer timed out on a fail-closed route\n- One surviving span when findings overlap, chosen by length or by a deterministic tie-break only when lengths are equal, so a reversible personal-data span restores a contained API key or JWT, or a partial overlap leaves the other span's tail in clear text\n- Writing an original outer span back over slices that already separated a secret from the surrounding personal data\n\n## Done when\n\n- [ ] One redacted view is built before the provider call, and logs, traces, caches, and eval exports use that view\n- [ ] Deterministic detectors cover email, phone, Luhn-checked cards, configured national IDs, API keys, and JWTs, with checksum failures dropped\n- [ ] The recognizer is optional, confidence-gated, category-filtered, and span-mapped back onto the original text\n- [ ] Allowlist hits are explicit and counted as `allowed`\n- [ ] Each route sets `mask`, `typed-placeholder`, or `reversible-token`, and secrets are never reversible\n- [ ] Overlapping spans redact the full union. Any slice that intersects an API key, JWT, or other secret stays non-restorable. Reversible-mode tests cover a nested secret and a partial overlap: the secret is not restored, and the stub request and the log appender do not contain the secret, the shared bytes, or a personal-data tail from those spans\n- [ ] The vault is request-scoped, cleared in `finally`, and used to restore only on the caller response\n- [ ] Stream output holds a tail so entities and placeholders split across chunks are still handled\n- [ ] `default-policy` is fail-closed, and every fail-open route is named in config\n- [ ] Raw prompts are absent from logs, metric labels, and trace attributes; counters are by entity type and action\n- [ ] Redaction time is inside the gateway latency budget, and the recognizer timeout is subtracted before routing\n- [ ] Golden, false-positive, false-negative, streaming, policy, cache, and leak tests pass, including a test where the stub provider and the log appender never see the fixture values\n\n## Copy-ready SKILL.md stub\n\n```markdown\n---\nname: llm-pii-redaction-guardrails\ndescription: Use when a Java or Spring LLM gateway, or a client of Azure OpenAI, Bedrock, OpenRouter, or another OpenAI-compatible provider, must redact personal data and secrets before the provider call and before logs, traces, caches, and eval fixtures. Covers deterministic detectors (email, phone, Luhn cards, national IDs, API keys, JWTs), an optional recognizer, allowlists, mask / typed placeholder / per-request reversible tokens, streaming hold-back, fail-closed by default, counters by entity type, a latency budget, and a leak test against a stub provider and a log appender.\n---\n\nFollow LLM PII and Secret Redaction Guardrails: build one redacted view before the provider call, and send that view to logs, traces, the prompt cache, and eval fixtures. Run deterministic detectors first (checksums included; cards must pass Luhn), then an optional recognizer, then an allowlist. Choose mask, typed placeholder, or reversible tokens per route. Keep the vault in the request, clear it in finally, and restore values only on the response to that caller. Secrets and JWTs are never restored, including when a longer personal-data span contains or overlaps them. Redact the union of overlapping spans, and keep each secret slice non-restorable. Hold back the tail of a stream so a value split across chunks is still caught. Default to fail-closed when a detector errors. Count entities by type and action, never by value. Prove with a test that the stub provider and the log appender do not receive the raw fixtures.\n```\n" + }, + { + "id": "llm-structured-output-guardrails", + "title": "LLM Structured Output Guardrails", + "whenToUse": "Making a Java/Spring Boot service or LLM gateway get reliably schema-valid JSON and tool-call arguments from Azure OpenAI, OpenAI, Anthropic, Amazon Bedrock, OpenRouter, or any OpenAI-compatible provider — native schema mode where supported, closed and versioned schemas, stop-reason checks before parsing, server-side JSON Schema validation, one bounded repair then fail closed, and tool arguments treated as untrusted input.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "structured-output", + "json-schema", + "tool-calling", + "spring-boot", + "gateway" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-structured-output.instructions.md` with applyTo for `**/llm/**`, `**/*Schema*.java`, `**/*Tool*.java`, `**/gateway/**`, and `**/llm-schemas/**`. Optional on-demand procedure at `.github/skills/llm-structured-output-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-structured-output-guardrails/SKILL.md` plus a CLAUDE.md fact that model JSON and tool arguments are validated server-side against versioned schemas before use, with one repair and then a typed failure. Codex: a short \"LLM structured output\" brief in root `AGENTS.md` (schema location, validator bean, outcome enum, conformance test command) while the procedure stays in SKILL.md. Pair with llm-app-prompt-injection-guardrails for tool agency and output-sink encoding, llm-gateway-routing-fallback-guardrails for capability skips and fallbackOnBadRequest, llm-pii-redaction-guardrails for anything logged, llm-eval-ci-regression-gate for the gate that reads the conformance rate, and llm-cost-latency-budget-guardrails for the repair attempt's budget. This skill owns the schema contract, the check order, validation, repair, and the tool-argument gate.", + "body": "# Skill: LLM Structured Output Guardrails\n\n## Goal\n\nWhen a Java or Spring Boot service, or an LLM gateway, needs JSON from a model (an extraction record, a classification, a routing decision, or the arguments of a tool call), the code that consumes it gets either a document that passed the server's own schema check or a typed failure. It never gets \"probably JSON\", a half-finished object, or a refusal that was parsed as data.\n\nThis skill owns the output contract: the schema and its version, the provider mode that asks for it, the stop-reason checks before parsing, server-side validation, the single bounded repair attempt, the fail-closed result, tool-call arguments as untrusted input, counters for validation outcomes, and the conformance fixtures that keep the rate visible in CI.\n\nTrust boundaries, tool agency, and encoding output for HTML, SQL, or a shell stay in **llm-app-prompt-injection-guardrails**. This skill makes the payload well-formed. That skill decides what a well-formed payload is still not allowed to do. Capability-based target selection (`json_schema`, `tools`) and the `fallbackOnBadRequest` switch stay in **llm-gateway-routing-fallback-guardrails**. Redacting personal data before the call, and in anything logged after it, stays in **llm-pii-redaction-guardrails**. The CI gate wiring, golden-set versioning, and baselines stay in **llm-eval-ci-regression-gate**; this skill only adds the schema-conformance cases and the metric that gate reads. Token and cost accounting for the retry stays in **llm-cost-latency-budget-guardrails**. HTTP API contracts between services stay in **spring-boot-openapi-contract-guardrails**.\n\n\"Respond only with valid JSON\" in a prompt is a request, not a control. The control is this code path.\n\n## When to apply\n\n- A feature parses model output into a record, an enum, or a command, with Spring AI, LangChain4j, or a plain HTTP client\n- A tool-calling or agent loop where the model supplies arguments that the service executes\n- A gateway that forwards `response_format`, `output_config.format`, or tool definitions and has to behave the same across providers\n- A review that finds `objectMapper.readValue(...)` on raw completion text inside a broad `try/catch`, regex extraction of `{...}` from prose, or a retry loop with no limit\n- Moving from prompt-only JSON or legacy JSON mode to provider-native schema mode\n\n## Ask the provider for the schema, then still validate\n\nThere are three levels. Use the highest one the target supports, and validate on the server at every level.\n\n| Level | What it guarantees | Where it is set |\n|---|---|---|\n| Native schema mode (strict) | Output is generated against the supplied schema, except on refusal, truncation, or another stop condition | OpenAI and Azure OpenAI: `json_schema` response format or `strict` function tools. Anthropic: JSON outputs (`output_config.format`) and `strict: true` on tool definitions. Bedrock Converse and OpenAI-compatible routers: check the model's documented support and treat the rest as level 3 |\n| JSON mode | Syntactically valid JSON. No schema adherence | Legacy `json_object` response format and similar |\n| Prompt only | Nothing | Instructions plus examples |\n\nRules:\n\n- Pick the level per target from the gateway's capability list, not from the model name in a string. A target without `json_schema` is skipped or flagged by the routing skill; it is not sent the same request and expected to comply.\n- Strict modes accept a subset of JSON Schema, and the subset differs by provider. Public docs list which keywords are supported (typically `enum`, `anyOf`, `$defs`/`$ref`, numeric and array bounds, some `format` values) and which are rejected (often `allOf`, `not`, `if`/`then`/`else`, `dependentRequired`). When a keyword is rejected, move that rule into the server-side validator or into code. Do not delete it to get the request accepted.\n- Native mode does not make values correct. A well-formed record can still carry a wrong total, an invented ID, or a guess where the input had nothing to extract. Business rules are checked in code after the schema passes.\n- The first request with a new schema can be slower on some providers while the schema is compiled and cached. Warm it in a smoke test after deploy rather than on a user request.\n\n## Schema design\n\nDesign the schema for the consumer and for strict mode at the same time.\n\n- **Object root, closed objects.** The root is an object. Every object sets `additionalProperties: false`. Unknown keys are a validation error, not something Jackson silently drops.\n- **Required everything.** List every property in `required`. When a value can be absent, make it nullable (`\"type\": [\"string\", \"null\"]`) instead of optional, so \"missing\" and \"not known\" are the same explicit thing.\n- **Enums for decisions.** Labels, actions, statuses, and severities are `enum`. Add an explicit escape value (`unknown`, `insufficient_input`, `not_applicable`) so the model has a legal answer when the input does not fit. Without it, strict mode forces a guess.\n- **No free-form unions.** Avoid `anyOf` of unrelated shapes and \"any JSON\" fields. When variants are real, use a discriminator (`\"kind\": {\"enum\": [\"refund\", \"replacement\"]}`) with one closed object per kind, and keep it within the provider's nesting limits.\n- **Bounded values.** `minimum`/`maximum`, `maxItems`, and `pattern` or `maxLength` where the provider and your validator support them. A field the consumer uses as an ID matches the ID's shape.\n- **No reasoning fields you do not need.** A `reasoning` or `explanation` string is free text inside a structured result. Keep it short and bounded if the product needs it, and never feed it to another system as an instruction.\n- **Versioned.** Each schema has a stable name and a version (`invoice_extract.v3`) stored in the repo, for example `src/main/resources/llm-schemas/invoice_extract.v3.json`, with `$id` set. The version travels with the request metadata, the metric labels, and the eval fixtures. A breaking change is a new version, and both versions validate during the rollout.\n- **One source of truth.** Generate the schema from the Java record (Spring AI's bean output converter, LangChain4j's JSON schema support, or a schema generator in the build) or hand-write it and test that the record and the schema agree. Do not keep two drifting copies.\n\n```json\n{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.example.com/llm/ticket_triage.v2.json\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"schema_version\", \"category\", \"priority\", \"customer_ref\", \"summary\"],\n \"properties\": {\n \"schema_version\": { \"const\": \"ticket_triage.v2\" },\n \"category\": { \"enum\": [\"billing\", \"access\", \"outage\", \"other\", \"insufficient_input\"] },\n \"priority\": { \"enum\": [\"p1\", \"p2\", \"p3\", \"p4\"] },\n \"customer_ref\": { \"type\": [\"string\", \"null\"], \"pattern\": \"^CUS-[0-9]{8}$\" },\n \"summary\": { \"type\": \"string\", \"maxLength\": 400 }\n }\n}\n```\n\nCheck `const` and every other keyword against the target provider's strict subset before you rely on it in the request. The server-side validator enforces the full schema either way.\n\n## Order of checks on every response\n\nRun these in order. Each step that fails returns a typed outcome and stops; it never falls through to the parser.\n\n1. **Transport and provider error.** Owned by the routing skill. Nothing below runs on a non-2xx.\n2. **Stop reason.** Read it before touching the content.\n - Normal completion (`stop`, `end_turn`, `tool_use` / `tool_calls` when a tool call was expected): continue.\n - Truncation (`length`, `max_tokens`, `max_output_tokens`, an `incomplete` status, a context-window stop): outcome `truncated`. A cut-off object is not repaired by closing its braces.\n - Refusal (a separate `refusal` field or content item, `stop_reason: refusal`): outcome `refused`. The refusal text is not data and is not parsed against the schema.\n - Content filter or guardrail stop (`content_filter`, a guardrail intervention): outcome `filtered`.\n - Anything unrecognized: outcome `unexpected_stop`. Fail closed. Add the value to the mapping when you see it.\n3. **Extract.** Take the structured content from the field the mode uses (the message content in schema mode, the arguments of the named tool call in tool mode). Do not search prose for the first `{`. Exactly one document. Reject a response with zero or several when one was expected. When strict tool calling and parallel calls conflict on the provider, turn parallel calls off for that request.\n4. **Size.** Reject a document over the configured byte cap before parsing.\n5. **Parse.** Strict parser: no comments, no trailing commas, no single quotes, duplicate keys rejected. In Jackson, enable `STRICT_DUPLICATE_DETECTION` and keep `FAIL_ON_UNKNOWN_PROPERTIES` on for these records.\n6. **Validate** against the versioned schema with a JSON Schema validator (below). Collect all errors.\n7. **Bind** to the Java record, then run the business rules the schema cannot express (cross-field totals, a referenced ID exists and belongs to this tenant, a date is in range).\n8. **Use.** Only now does the value reach the caller, a tool, or a store.\n\n## Server-side validation in Java\n\nValidate even in native mode. The provider's guarantee does not cover refusal, truncation, a provider bug, a router that silently drops the schema parameter, a model swapped behind an alias, or a schema keyword the provider ignored.\n\n- **networknt json-schema-validator** is the common choice. The 3.x line targets Java 17+ and Jackson 3 (Spring Boot 4). The 2.x line targets Jackson 2 (Spring Boot 3). Its 2.x and later API uses a `SchemaRegistry` with an explicit dialect (Draft 2020-12) and returns a list of errors. Other maintained validators are fine if the repo already uses one; pick one, not two.\n- Load schemas from the classpath at startup, compile them once, and keep the registry as a singleton bean. Call `initializeValidators()` on each loaded schema so a broken `$ref` fails at boot instead of on the first request. Fail startup if a schema referenced in config is missing or does not compile. Do not fetch remote `$ref` targets at runtime (2.x and later leave remote fetching off by default; keep it off).\n- Since Draft 2019-09, `format` is an annotation unless assertion is turned on. If a field depends on `format` (`date`, `uuid`, `email`), enable format assertions in the validator's execution config or use a `pattern`, and test that a bad value fails.\n- Map each error to `{path, keyword}`, for example `{\"/priority\", \"enum\"}`. For `required`, the instance location is the parent object, so append the missing property name from the error. That pair goes into the repair message and the log; the keyword alone goes into the metric. The offending value goes nowhere.\n- Bean Validation on the bound record (`@NotNull`, `@Pattern`) is a useful second layer for business rules. It is not a substitute for schema validation, because binding has already dropped or coerced things by then.\n\n```java\n// Spring Boot 4 / Jackson 3 sketch using networknt 3.x\n@Bean\nSchemaRegistry llmSchemaRegistry() {\n return SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12);\n}\n\nValidationResult validate(String schemaId, JsonNode doc) {\n Schema schema = schemas.get(schemaId); // compiled once at startup from classpath\n List errors = schema.validate(doc);\n return errors.isEmpty()\n ? ValidationResult.ok()\n : ValidationResult.invalid(errors.stream()\n .map(e -> new SchemaViolation(String.valueOf(e.getInstanceLocation()), e.getKeyword()))\n .toList());\n}\n```\n\nTreat the sketch as shape only and check method names against the version in the build.\n\n## Bounded repair, then fail closed\n\nAt most one repair attempt per logical call, and only for outcomes repair can fix.\n\n- **Repairable:** `parse_error`, `schema_invalid`, `business_rule_invalid`. Re-ask once on the same target with the original messages, the model's previous output, and a short system-authored message listing the violations as `{path, keyword}` pairs (\"`/priority` must be one of p1, p2, p3, p4\"). Do not echo user content or field values in that message. Keep the same schema and the same mode.\n- **Truncated:** one retry with a higher output-token cap, only if the cap is still inside the route's token budget. Otherwise fail. Do not ask the model to \"continue\" a structured document and stitch the halves together.\n- **Not repairable:** `refused`, `filtered`, `unexpected_stop`, oversize, or a second failure of any kind. Return the typed failure.\n- The repair attempt counts against the route deadline and token budget (**llm-cost-latency-budget-guardrails**). It is not a routing fallback, and it does not move to another provider. Whether a provider 400 on the schema itself may fall back is the routing skill's `fallbackOnBadRequest` decision.\n- Never relax the schema, drop the strict flag, or switch to prompt-only JSON on the retry.\n- No local \"fixers\" that guess: no trimming to the last `}`, no regex quoting of keys, no defaulting a missing required field. A deterministic normalizer is allowed only for a documented, tested case (stripping a single Markdown code fence around otherwise valid JSON from a prompt-only target), and its use is counted.\n\nFail closed means the caller gets a typed error, not a partial record. For an HTTP API, problem+json with a stable code: `llm_output_invalid` (422 or 502, pick one per API and document it), `llm_output_refused`, `llm_output_truncated`. For an internal call, a sealed result type (`Valid | Invalid | Refused | Truncated | Filtered`) so the compiler forces every branch. Nothing downstream receives a default-constructed record.\n\n## Never evaluate model output\n\nStructured output is data. It is never code.\n\n- No `ScriptEngine`, SpEL, OGNL, MVEL, Groovy, JavaScript, or template evaluation of any field. No reflection on a class or method name the model supplied. No polymorphic Jackson typing (`@JsonTypeInfo` with class names, default typing) on these records.\n- A field that selects behavior is an enum mapped in a `switch` to code you wrote. A string is not a method name, a bean name, a URL, a file path, or a query fragment.\n- A field that ends up in SQL, a shell, a URL, HTML, or a log line is encoded or parameterized for that sink, as **llm-app-prompt-injection-guardrails** requires.\n\n## Tool-call arguments are untrusted input\n\nStrict tool calling guarantees the arguments match the tool's schema. It does not mean the caller is allowed to do what they describe.\n\n- The tool name must be on this route's allowlist. An unknown or disallowed name is rejected before argument parsing, even if the provider says it is valid.\n- Validate arguments against the server's copy of the tool schema, the same way as any structured output, then bind to a record.\n- Authorize as the end user (on-behalf-of or row-filtered access), not as the service. Every ID in the arguments is checked against what this caller may touch. Tenant and user come from the authenticated context, never from an argument.\n- Allowlist values that select targets: hosts, queues, table names, file roots, email domains. Bounded numbers for limits and amounts.\n- Side-effecting tools need an idempotency key from the server (not the model) and, where the action is high impact, a confirmation step. Loop limits and approval steps are in the prompt-injection skill.\n- A validation or authorization failure goes back to the model as a short tool error (\"argument `/account_id` not permitted\") so the loop can recover once, and it counts toward the same single repair limit.\n\n## Metrics and logs without payloads\n\nCount outcomes, not content.\n\n- `llm_structured_output_total`: counter. Labels: `route`, `schema` (name and version), `mode` (`native`, `json_mode`, `prompt_only`, `tool`), `outcome` (`valid`, `repaired`, `parse_error`, `schema_invalid`, `business_rule_invalid`, `refused`, `truncated`, `filtered`, `unexpected_stop`, `oversize`).\n- `llm_structured_output_violations_total`: counter. Labels: `schema`, `keyword` (`required`, `enum`, `additionalProperties`, `type`, `pattern`, ...). Use the keyword, not the instance path, so label cardinality stays fixed. Put the path in a log field if you need it.\n- `llm_tool_call_rejected_total`: counter. Labels: `route`, `tool`, `reason` (`unknown_tool`, `schema_invalid`, `not_authorized`, `not_allowlisted`).\n- Logs: request ID, route, schema version, mode, provider target, stop reason, outcome, violation `{path, keyword}` pairs, and whether repair ran. Not the completion, not the arguments, not the offending value, and not a hash of it. If a debug capture is truly needed, it goes through the redacted view from **llm-pii-redaction-guardrails** and stays off in shared environments.\n- Alert on a rise in `schema_invalid` or `refused` per schema version, and on any `unexpected_stop`. A jump after a model or alias change usually means the target lost native schema support.\n\n## Conformance fixtures in CI\n\nAdd schema conformance to the existing eval gate in **llm-eval-ci-regression-gate**. Do not build a second gate.\n\n- **Offline, deterministic (every PR).** A fixture directory per schema version with recorded or synthetic model outputs: valid documents, a missing required field, an extra property, a wrong enum, a null where not allowed, a duplicate key, a truncated object, a refusal response, a content-filter stop, a response with prose around the JSON, two tool calls where one was expected, and an unknown tool name. Each fixture asserts the outcome, the `{path, keyword}` list, and that nothing reached the consumer or the tool stub.\n- **Repair path.** A stub provider returns an invalid document, then a valid one. Assert exactly two provider calls, outcome `repaired`, and that the repair message lists keywords and paths but contains none of the fixture values. A second stub returns invalid twice: assert two calls, the typed failure, and no third call.\n- **Truncation and refusal.** The stub returns `finish_reason: length` with a half object, and a refusal. Assert no parse attempt, the right outcome, and no repair call for the refusal.\n- **Tool authz.** Valid arguments with another tenant's ID are rejected with `not_authorized`, and the tool stub sees zero calls.\n- **Schema and record agree.** A test generates or loads the schema and checks it against the Java record, and a test sends each schema to a strict-mode lint (or a recorded provider acceptance) so a rejected keyword is caught before deploy.\n- **Live conformance rate (scheduled or on prompt/model change).** Run the golden inputs against the real target and report the share of `valid` on first attempt, `repaired`, and failed, per schema version. The gate fails when first-attempt conformance drops below the agreed floor for that schema, or when `unexpected_stop` appears. Record the floor next to the schema version.\n\nFixtures are synthetic. No customer transcripts.\n\n## Workflow\n\n1. Inventory every place model output is parsed or a tool call is executed. Table: call site | schema (or none) | mode | stop reason checked? | validator? | retry policy | consumer.\n2. Write or generate versioned schemas, closed and fully required, with enums and an escape value.\n3. Turn on native schema mode or strict tools where the target supports it. Keep prompt-only targets explicit.\n4. Add the ordered checks: stop reason, extract, size, strict parse, validate, bind, business rules.\n5. Add the single repair attempt and the typed failure result. Remove unbounded loops and guessing fixers.\n6. Gate tool calls: allowlist, server-side schema, end-user authz, value allowlists.\n7. Add the counters and log fields. Check that no payload or value reaches a log, a label, or a span.\n8. Land the fixtures and wire the conformance rate into the eval gate before enabling a new schema version in production.\n\n## Tool-specific notes\n\n- **GitHub Copilot:** path-scoped `.github/instructions/llm-structured-output.instructions.md` with `applyTo` for `**/llm/**`, `**/*Schema*.java`, `**/*Tool*.java`, `**/gateway/**`, and `**/llm-schemas/**`. Put the check order, \"validate even in native mode\", and \"one repair, then fail closed\" at the top. Keep the procedure in an optional `.github/skills/llm-structured-output-guardrails/SKILL.md`. Ask for the inventory table before editing a parser.\n- **Claude Code:** `.claude/skills/llm-structured-output-guardrails/SKILL.md` holds the procedure. Add one `CLAUDE.md` fact: \"Model JSON and tool arguments are validated server-side against versioned schemas in `llm-schemas/` before use. One repair attempt, then a typed failure. Model output is never evaluated.\"\n- **Codex:** root `AGENTS.md` stays a short brief: where schemas live, the validator bean, the outcome enum, and the conformance test command. The procedure lives in `SKILL.md`, or in a nested `AGENTS.md` beside the gateway module when the repo already uses nested briefs. Do not paste this whole skill into `AGENTS.md`.\n\n## Anti-patterns\n\n- \"Return only JSON\" in the prompt as the only control\n- Trusting native schema mode and skipping server-side validation\n- Parsing before checking the stop reason, so a refusal or a truncated object reaches the parser\n- Regex-extracting the first `{...}` from prose, or closing braces on a truncated document\n- `additionalProperties` left open, optional fields with silent Jackson defaults, or free-form string fields for decisions\n- Deleting a schema rule the provider rejected instead of enforcing it in the validator\n- Unbounded \"try again until it parses\" loops, or a retry that relaxes the schema or drops strict mode\n- `ScriptEngine`, SpEL, reflection, or polymorphic typing driven by model output\n- Executing a tool because the arguments are schema-valid, without the allowlist and end-user authorization\n- Tenant or user IDs taken from tool arguments\n- Logging the completion, the arguments, or the failing value to debug a validation error\n- Instance paths or values as metric labels\n- A schema change with no version bump and no fixtures\n\n## Done when\n\n- [ ] Every parse site and tool executor is in the inventory table with its schema version and mode\n- [ ] Schemas are versioned files in the repo, closed (`additionalProperties: false`), fully required with nullable instead of optional, enums with an escape value, no free-form unions\n- [ ] Native schema mode or strict tools are used where the target supports them, and rules the provider rejects are enforced server-side\n- [ ] Stop reason is checked before parsing; refusal, truncation, filter, and unknown stops are typed outcomes\n- [ ] A JSON Schema validator compiled at startup validates every document, including in native mode, then business rules run on the bound record\n- [ ] At most one repair attempt, inside the route budget, with `{path, keyword}` feedback and no values; then a typed failure\n- [ ] Model output is never evaluated or used for reflection or polymorphic typing\n- [ ] Tool calls pass a name allowlist, server-side schema validation, end-user authorization, and value allowlists before execution\n- [ ] Counters by route, schema version, mode, outcome, and keyword; no payloads or values in logs, labels, or spans\n- [ ] Conformance fixtures run on every PR, and the first-attempt conformance rate per schema version is a gate in the existing eval pipeline\n\n## Copy-ready SKILL.md stub\n\n```markdown\n---\nname: llm-structured-output-guardrails\ndescription: Use when a Java or Spring service or LLM gateway parses JSON from a model or executes tool-call arguments. Covers provider-native schema mode vs JSON mode vs prompt-only, closed and versioned JSON Schemas (required fields, enums with an escape value, additionalProperties false, no free-form unions), checking the stop reason before parsing (refusal, truncation, filter), server-side validation with a JSON Schema validator such as networknt, one bounded repair then fail closed, never evaluating output, tool arguments as untrusted input (allowlist, end-user authz), outcome counters without payloads, and schema-conformance fixtures in CI.\n---\n\nFollow LLM Structured Output Guardrails: ask the provider for native schema mode or strict tools where supported, and still validate every document on the server. Keep schemas versioned in the repo, closed, fully required (nullable instead of optional), with enums and an explicit escape value. Check the stop reason before parsing; refusal, truncation, and filter stops are typed failures, not data. Parse strictly, validate with a compiled JSON Schema validator, bind, then check business rules. Allow one repair attempt with path and keyword feedback and no values, then fail closed. Never evaluate model output. Treat tool-call arguments as untrusted: allowlist the tool, validate, authorize as the end user. Count outcomes by schema version and keyword, never log payloads, and gate first-attempt conformance in CI.\n```\n" } ] } From 1264c161a1d937f99f9c7558506602fd3ac6ad51 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Tue, 10 Nov 2026 05:09:36 +0000 Subject: [PATCH 2/3] Add prompt for enforcing schema-valid structured output from LLM calls --- promptbook/prompts.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 4897688..0ad5c2e 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -1062,6 +1062,26 @@ ], "formatNotes": "All three. Point the tool at the gateway module, the provider client, logging config, cache keys, and eval export. Copilot: llm-pii-redaction path instructions plus those files in agent mode (or save the prompt as `.github/prompts/add-llm-pii-redaction.prompt.md`). Claude Code: the llm-pii-redaction-guardrails skill plus the filter, vault, and test files. Codex: the AGENTS.md LLM redaction section, then the diff. Leave prompt-injection trust maps, log JSON format, routing fallback, eval gate wiring, and price tables to their own skills.", "body": "Task: Add PII and secret redaction to the LLM gateway I specify. Build one redacted view of each prompt and use it for the provider call, for logs, metrics, and traces, and for prompt caches and eval fixtures. Choose mask, typed placeholder, or reversible tokens per route. Default to fail-closed when a detector errors. Hold back stream tails so a value split across chunks is still caught. Finish with a minimal diff, fixtures, and a test that a stub provider and the log appender never see the raw values.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Gateway name and module: {{GATEWAY_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI | LangChain4j | plain HTTP client | mixed)\n- Providers: {{PROVIDERS}} (Azure OpenAI, Amazon Bedrock, OpenRouter, other OpenAI-compatible base URLs)\n- Routes: {{ROUTES}} (route or alias → data class, and whether the response may restore values to the caller)\n- Mode per route: {{MODE}} (mask | typed-placeholder | reversible-token)\n- Policy per route: {{POLICY}} (fail-closed is the default; name any fail-open route and why)\n- Recognizer: {{NER}} (none | azure-language | in-process analyzer) and its timeout\n- National ID schemes in scope: {{NATIONAL_IDS}} (list, or \"none\")\n- Streaming: {{STREAMING}} (yes | no | mixed)\n- Cache and eval export: {{SINKS}} (prompt cache path, eval fixture path, or \"none\")\n- Latency budget: {{LATENCY_BUDGET}} (p95 for the deterministic stage, recognizer timeout, alias deadline)\n- Observability: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both; log appender used in tests)\n- Pain: {{PAIN}} (raw prompts in logs | PII at the provider | split tokens on the stream | no tests | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}}: the provider client, filters that log bodies, HTTP wiretaps, prompt-cache keys, eval exporters, and any existing regex or PII call\n - Table: call site | sees raw prompt? | sees raw completion? | sink (provider, log, trace, cache, fixture)\n - Flag a system-prompt sentence used as the only protection, a shared map of raw values, and a detector that treats every 16-digit run as a card\n\n2. One redacted view, in this order\n - After authn, before the provider HTTP call, redact user messages, tool results, and retrieved text. Leave role names, tool names, JSON keys, and document delimiters in place. Scan system text for interpolated secrets\n - Pass that same view to every provider and every fallback. Do not redact differently per provider\n - Logs, span attributes, the prompt cache, and eval exports under {{SINKS}} record this view. A debug flag does not open a second copy of the raw body\n - On {{MODE}} `reversible-token`, restore placeholders only on the response bytes for this caller. Logs and the cache keep placeholders. Then mask any card, email, or secret the model introduced that this request did not mint\n\n3. Detectors\n - Deterministic, in process, always on for the entities you enable: email (including plus-tags), phone (leading + or a known trunk pattern, with a digit-length check), payment cards (13–19 digits, spaces and dashes ignored, Luhn required), API-key assignment shapes, and JWTs (three base64url segments, header JSON with `alg`)\n - {{NATIONAL_IDS}}: implement only named schemes, with that scheme's published length and checksum. If the list is \"none\", leave national-id detection off\n - A checksum failure is not a finding. Secrets and JWTs are never reversible, even when the route mode restores emails or phones, and even when a longer personal-data span contains or overlaps them\n - {{NER}}: optional. Confidence floor per entity type, exclude `person_type` and any other category that marks `user` / `assistant` or dates the product needs. Map spans back onto the original string. Do not concatenate the service's own redacted chunks\n - Allowlist: reviewed literals only (support address, product names, the placeholder syntax). A span that matches the allowlist is kept and counted as `allowed`, and that match removes only that span. No test card numbers in production config\n - Overlap, on the original string, start inclusive and end exclusive. Redact the union of the surviving spans, then split that union at each span boundary. A slice that intersects an API key, a JWT, or another secret stays non-restorable: mask it, or use a placeholder that is not written to the vault and is not restored. That holds when a longer reversible NER or other personal-data span contains the secret, and when the spans only partly overlap, so the shared bytes and each exclusive tail are covered and the secret is not restored with the personal-data slices. Any other slice follows {{MODE}}. If at least one deterministic finding covers a restorable slice, label it with the deterministic finding that starts earlier. If those starts are equal, use the deterministic finding that ends later. An NER finding does not supply the label for that slice. If every finding on the slice is from the recognizer, use the one that starts earlier, and if those starts are equal, the one that ends later. If a slice intersects more than one secret, label it with the secret finding that starts earlier. If those starts are equal, use the secret finding that ends later. The slice stays non-restorable. Merge adjacent slices only when type, action, and restorability match. Length and confidence are not inputs to coverage or restorability. Replace the slices from the end of the string. Re-parse JSON and fail the request if the body no longer parses. This combines spans the enabled detectors returned. It does not mean detection is complete\n\n4. Modes and the vault\n - `mask`: irreversible character mask (last-4 only where the scheme says that remainder is safe)\n - `typed-placeholder`: `[TYPE_n]`, stable for the same value within the request, discarded after the response with no restore\n - `reversible-token`: the same placeholders plus a request-scoped in-memory vault, cleared in `finally`, not stored in Redis, logs, or the cache. Restore only tokens this request minted. An API key, JWT, or other secret is never a vault entry, and a personal-data token does not contain those bytes when the spans overlap\n - A prompt cache hit restores with this request's vault only. A placeholder this request did not mint stays a placeholder\n - Apply {{MODE}} and {{POLICY}} per route under {{ROUTES}}. `default-policy` is fail-closed\n\n5. Streaming ({{STREAMING}})\n - Redact the full request before the provider call\n - On the response, buffer and flush only the prefix that cannot still grow into an entity or a placeholder. Resolve overlaps on that buffer before flushing, and leave any byte still covered by a span in the buffer unflushed. Hold the suffix. Cap the secret scan (document the cap) and do not split a UTF-8 sequence\n - At stream end, flush the tail through the same detector. On error or cancel, drop the buffer and the vault without logging it\n - The log appender sees redacted text. The caller sees restored text only in reversible mode\n\n6. Fail-closed and fail-open\n - Recognizer throw, timeout, or unparseable result on a fail-closed route: do not call the provider, do not cache the raw body, return problem+json 503 `redaction_unavailable`. Zero findings is success\n - On a fail-open route named in {{POLICY}}: send the deterministically redacted view, increment `detector_error`, alert. If the in-process scanner throws, fail closed anyway\n - Subtract the recognizer timeout from the alias deadline before routing starts, inside {{LATENCY_BUDGET}}\n\n7. Counters and logs ({{OBSERVABILITY}})\n - `llm_redaction_entities_total` labels: `route`, `entity_type`, `action` (`masked`, `placeholder`, `tokenized`, `allowed`, `detector_error`)\n - `llm_redaction_seconds` labels: `route`, `outcome` (`ok`, `failed_closed`, `failed_open`)\n - No label, span attribute, log field, or usage-store column carries a value or a hash of a value\n - Remove or gate any wiretap or `log.debug` of the raw provider body\n\n8. Tests\n - Golden fixtures: spans plus the expected string for each mode. Synthetic values only\n - False positives that stay: UUID, git SHA, semver, epoch millis, order number, the words `user` and `assistant`, the token `[EMAIL_1]`, a 16-digit run that fails Luhn\n - False negatives that redact: plus-tag email, dashed PAN that passes Luhn, country-code phone, JWT without a `Bearer` prefix\n - Overlap, reversible mode. Stub the recognizer with a personal-data span and let the deterministic layer find the API key or JWT. Nested: the personal-data span strictly contains the secret. In the stub request and the log appender, the secret is absent and the personal-data text outside the secret is absent. Partial: the spans overlap and each extends past the other. In the stub request and the log appender, the secret, the shared bytes, and the personal-data-only tail are absent. In both, the caller response and the vault do not contain the secret, and restoring personal-data bytes outside the secret does not restore it. These fixtures do not show that every secret was detected\n - Leak test: stub provider plus the log appender from {{OBSERVABILITY}}. The recorded request and every log event omit the fixture email, the PAN (spaced and compact), and the JWT. Counters move. On a reversible route the stub echoes `[EMAIL_1]`, the caller response contains the email, the appender contains the placeholder and not the email, and the vault is empty afterward\n - Streaming: PAN split across two stub deltas never appears in the client bytes or the appender. Placeholder split across two deltas restores once on a reversible route\n - Fail-closed recognizer failure: zero stub requests, HTTP 503 `redaction_unavailable`, raw fixture absent from logs. Fail-open: deterministic hits still redacted, one stub request, `detector_error` incremented\n - Two requests that share a placeholder shape do not restore each other's values from the cache\n\n9. Verification\n - Inventory table from step 1, updated to show each sink now sees the redacted view\n - Route table: route, mode, policy, recognizer on or off, entities enabled\n - Latency note: deterministic p95 target, recognizer timeout, what was subtracted from the alias deadline\n - Tests added and what each asserts\n\nConstraints:\n- Minimal diff. Match the module's config style and test style. No new HTTP client and no new resilience library.\n- No real customer text, live endpoints, or secrets in git or in fixtures. Use synthetic values and published test PANs.\n- Do not weaken the provider call timeout to make tests pass. Drive recognizer failures with a fake client.\n- Leave prompt-injection trust maps, JSON log encoder setup, routing and fallback policy, eval CI wiring, and price tables to their existing skills. Call those hooks where this stage sits next to them; do not reimplement them.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table and the sinks that still see raw text\n2. Config and code diff (detectors, modes, vault, stream hold-back, policy, counters)\n3. Tests added and what each asserts, including the leak test\n4. Route table and the latency budget\n\nStart from {{APP_PATH}}. Wire the redacted view through the provider and the log appender, and land the leak test, before enabling a recognizer or a fail-open route.\n" + }, + { + "id": "enforce-llm-structured-output", + "title": "Enforce Schema-Valid Structured Output from LLM Calls", + "whenToUse": "Make Java/Spring LLM calls and tool calls return schema-valid JSON or a typed failure — native schema mode or strict tools where the provider supports them, versioned closed schemas, stop-reason checks before parsing, server-side JSON Schema validation, one bounded repair then fail closed, tool arguments authorized as the end user, outcome counters without payloads, and conformance fixtures in CI.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "structured-output", + "json-schema", + "tool-calling", + "spring-boot", + "gateway" + ], + "formatNotes": "All three. Point the tool at the model client, the parse sites, tool executors, the schema directory, and the eval fixtures. Copilot: llm-structured-output path instructions plus those files in agent mode (or save the prompt as `.github/prompts/enforce-llm-structured-output.prompt.md`). Claude Code: the llm-structured-output-guardrails skill plus the parser, validator, and test files. Codex: the AGENTS.md LLM structured output section, then the diff. Leave prompt-injection trust maps, routing fallback, PII redaction, eval gate wiring, and price tables to their own skills.", + "body": "Task: Make the LLM calls I specify return schema-valid JSON, or a typed failure, every time. Use provider-native schema mode or strict tools where the target supports them, and validate every document on the server against a versioned schema anyway. Check the stop reason before parsing. Allow one bounded repair, then fail closed. Treat tool-call arguments as untrusted input. Count outcomes without logging payloads, and add schema-conformance fixtures to CI. Finish with a minimal diff, the schemas, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service or gateway and module: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version and Jackson 2 or 3; Spring AI | LangChain4j | plain HTTP client | mixed)\n- Providers and targets: {{PROVIDERS}} (Azure OpenAI, OpenAI, Anthropic, Amazon Bedrock, OpenRouter, other OpenAI-compatible) and which support native schema mode or strict tools\n- Structured calls: {{CALLS}} (call site → schema name and version → consumer)\n- Tools: {{TOOLS}} (tool name → side effect → who may call it, or \"none\")\n- Schema location: {{SCHEMA_DIR}} (default `src/main/resources/llm-schemas/`)\n- Validator: {{VALIDATOR}} (networknt json-schema-validator 3.x for Jackson 3, 2.x for Jackson 2, or the one the repo already uses)\n- Failure contract: {{FAILURE_CONTRACT}} (HTTP status and problem+json codes, or the internal result type)\n- Budget: {{BUDGET}} (route deadline, max output tokens, and whether one repair fits)\n- Observability: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both)\n- Eval gate: {{EVAL_GATE}} (existing eval CI job and fixture path, or \"none\")\n- Pain: {{PAIN}} (parse exceptions | refusals parsed as data | truncated JSON | unbounded retries | unsafe tool calls | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}}: every place model output is parsed, every tool executor, every retry around a model call, and any regex that pulls `{...}` out of text\n - Table: call site | schema (or none) | mode (native | json_mode | prompt_only | tool) | stop reason checked? | server-side validator? | retry policy | consumer\n - Flag `readValue` on raw completion text in a broad catch, unbounded \"retry until it parses\" loops, brace-closing or quote-fixing helpers, `ScriptEngine`/SpEL/reflection/polymorphic typing driven by output, and tenant or user IDs taken from tool arguments\n\n2. Schemas in {{SCHEMA_DIR}}\n - One file per schema and version (`ticket_triage.v2.json`), Draft 2020-12, `$id` set, stored in the repo\n - Object root. `additionalProperties: false` on every object. Every property in `required`; use a nullable type where a value can be absent\n - Decisions are `enum`, each with an explicit escape value (`unknown`, `insufficient_input`). No free-form unions or \"any JSON\" fields. Real variants use a discriminator enum and one closed object per kind\n - Bounds on numbers, arrays, and ID-shaped strings\n - One source of truth: generate from the Java record or test that the record and the schema agree\n - Check each schema against the strict-mode subset of every target in {{PROVIDERS}}. When a keyword is rejected, enforce that rule in the server-side validator or in code. Do not delete the rule\n\n3. Request mode\n - Use native schema mode (OpenAI/Azure OpenAI `json_schema` with strict, Anthropic JSON outputs) or strict tool definitions where the target supports them. Choose per target from capability config, not from a model-name string\n - Targets without support stay explicit as `json_mode` or `prompt_only`, and get the same server-side checks\n - Disable parallel tool calls on a request where they conflict with strict schemas on that provider\n\n4. Ordered response checks (each failure is a typed outcome; nothing falls through to the parser)\n - Stop reason first. Normal completion continues. Truncation (`length`, `max_tokens`, `max_output_tokens`, incomplete status, context-window stop) → `truncated`. Refusal (a `refusal` field or item, `stop_reason: refusal`) → `refused`. Content filter or guardrail stop → `filtered`. Anything unmapped → `unexpected_stop`\n - Extract from the field the mode uses (message content, or the named tool call's arguments). Exactly one document where one is expected. No searching prose for `{`\n - Byte cap before parsing → `oversize`\n - Strict parse: duplicate keys rejected (`STRICT_DUPLICATE_DETECTION`), no comments or trailing commas, `FAIL_ON_UNKNOWN_PROPERTIES` on for these records → `parse_error`\n - Validate with {{VALIDATOR}} → `schema_invalid` with a list of `{path, keyword}` pairs. For `required`, add the missing property name to the path\n - Bind to the record, then run business rules the schema cannot express (cross-field totals, referenced ID exists and belongs to this tenant) → `business_rule_invalid`\n\n5. Validator setup\n - One registry bean with an explicit Draft 2020-12 dialect. Load schemas from the classpath at startup, compile once, preload validators so a broken `$ref` fails at boot, and fail startup when a configured schema is missing. No remote `$ref` fetching\n - Turn on format assertions if any field relies on `format`, or use `pattern`, and test a bad value\n - Validate in native mode too\n\n6. One repair, then fail closed\n - `parse_error`, `schema_invalid`, `business_rule_invalid`: re-ask once on the same target with the same schema and mode, adding a short system-authored message that lists the `{path, keyword}` violations. No field values or user text in that message\n - `truncated`: one retry with a higher output-token cap only if {{BUDGET}} allows; otherwise fail. Never stitch a \"continue\" onto a structured document\n - `refused`, `filtered`, `unexpected_stop`, `oversize`, or any second failure: no retry\n - The repair counts against the route deadline and token budget. It is not a provider fallback. Never relax the schema, drop strict mode, or switch to prompt-only on the retry\n - Remove guessing fixers. A deterministic normalizer is allowed only for a documented case (one Markdown code fence around otherwise valid JSON from a prompt-only target), and its use is counted\n - Return {{FAILURE_CONTRACT}}: problem+json codes such as `llm_output_invalid`, `llm_output_refused`, `llm_output_truncated`, or a sealed result type. Nothing downstream receives a partial or default-constructed record\n\n7. Never evaluate output\n - No ScriptEngine, SpEL, OGNL, Groovy, template evaluation, reflection on model-supplied names, or polymorphic Jackson typing on these records\n - Behavior-selecting fields are enums mapped in a `switch`. Strings that reach SQL, a shell, a URL, HTML, or a log are parameterized or encoded for that sink\n\n8. Tool calls ({{TOOLS}})\n - Tool name on this route's allowlist, checked before argument parsing\n - Arguments validated against the server's copy of the tool schema, then bound\n - Authorize as the end user. Tenant and user come from the authenticated context, never from arguments. Every ID is checked against what this caller may access\n - Allowlist target-selecting values (hosts, queues, tables, paths, domains). Bound amounts and limits\n - Side-effecting tools get a server-generated idempotency key and, where high impact, a confirmation step\n - A rejection goes back to the model as a short tool error and shares the single repair limit\n\n9. Metrics and logs ({{OBSERVABILITY}})\n - `llm_structured_output_total` labels: `route`, `schema`, `mode`, `outcome` (`valid`, `repaired`, `parse_error`, `schema_invalid`, `business_rule_invalid`, `refused`, `truncated`, `filtered`, `unexpected_stop`, `oversize`)\n - `llm_structured_output_violations_total` labels: `schema`, `keyword`. Paths go in log fields, not labels\n - `llm_tool_call_rejected_total` labels: `route`, `tool`, `reason` (`unknown_tool`, `schema_invalid`, `not_authorized`, `not_allowlisted`)\n - Log request ID, route, schema version, mode, target, stop reason, outcome, violation pairs, and whether repair ran. Never the completion, the arguments, the failing value, or a hash of it\n\n10. Tests and CI ({{EVAL_GATE}})\n - Offline fixtures per schema version, run on every PR: valid docs, missing required, extra property, wrong enum, disallowed null, duplicate key, truncated object, refusal, content-filter stop, prose around JSON, two tool calls where one was expected, unknown tool name. Each asserts the outcome, the violation list, and that the consumer or tool stub saw nothing\n - Repair: stub returns invalid then valid → two calls, `repaired`, and the repair message contains paths and keywords but no fixture values. Stub returns invalid twice → two calls, typed failure, no third call\n - Truncation and refusal: no parse attempt, correct outcome, no repair call for the refusal\n - Tool authz: valid arguments naming another tenant's ID → `not_authorized`, zero tool stub calls\n - Schema and record agree; each schema passes the strict-subset check for every target that uses it\n - Live conformance (scheduled or when prompt, model, or schema changes): first-attempt `valid` rate, `repaired` rate, and failure rate per schema version, reported into the existing eval gate. Fail below the recorded floor or on any `unexpected_stop`. Do not build a second gate\n - Synthetic fixtures only\n\n11. Verification\n - Inventory table from step 1, updated\n - Schema list with version, mode per target, and the rules enforced only server-side\n - Outcome mapping table: provider stop reason → outcome → HTTP code or result type\n - Tests added and what each asserts\n\nConstraints:\n- Minimal diff. Match the module's config, error, and test style. No new HTTP client, no second JSON library, and no second validator if one is already present.\n- No real customer text, live endpoints, or secrets in fixtures. Stub providers for every test except the scheduled live conformance run.\n- Do not weaken validation, raise the repair limit, or loosen `additionalProperties` to make a test pass.\n- Leave prompt-injection trust maps and output-sink encoding, routing and fallback (including `fallbackOnBadRequest`), PII redaction, eval gate wiring, and price tables to their existing skills. Call their hooks where this stage sits next to them.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table and the parse sites that still trust raw output\n2. Schemas and config diff (mode per target, validator bean, outcome enum)\n3. Code diff (ordered checks, repair, failure contract, tool gate, counters)\n4. Tests added and what each asserts, including the repair and tool-authz cases\n5. Outcome mapping table and the conformance floor per schema version\n\nStart from {{APP_PATH}}. Land the stop-reason checks, the server-side validator, and the offline fixtures before turning on a new schema version or a new tool.\n" } ] } From 573b5368b3e6a30973db2cee1818e91b5e3618b4 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Tue, 10 Nov 2026 05:10:16 +0000 Subject: [PATCH 3/3] Make strict JSON parsing explicit for Jackson 3 defaults --- promptbook/prompts.json | 2 +- skillbook/skills.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 0ad5c2e..44a0d4e 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -1081,7 +1081,7 @@ "gateway" ], "formatNotes": "All three. Point the tool at the model client, the parse sites, tool executors, the schema directory, and the eval fixtures. Copilot: llm-structured-output path instructions plus those files in agent mode (or save the prompt as `.github/prompts/enforce-llm-structured-output.prompt.md`). Claude Code: the llm-structured-output-guardrails skill plus the parser, validator, and test files. Codex: the AGENTS.md LLM structured output section, then the diff. Leave prompt-injection trust maps, routing fallback, PII redaction, eval gate wiring, and price tables to their own skills.", - "body": "Task: Make the LLM calls I specify return schema-valid JSON, or a typed failure, every time. Use provider-native schema mode or strict tools where the target supports them, and validate every document on the server against a versioned schema anyway. Check the stop reason before parsing. Allow one bounded repair, then fail closed. Treat tool-call arguments as untrusted input. Count outcomes without logging payloads, and add schema-conformance fixtures to CI. Finish with a minimal diff, the schemas, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service or gateway and module: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version and Jackson 2 or 3; Spring AI | LangChain4j | plain HTTP client | mixed)\n- Providers and targets: {{PROVIDERS}} (Azure OpenAI, OpenAI, Anthropic, Amazon Bedrock, OpenRouter, other OpenAI-compatible) and which support native schema mode or strict tools\n- Structured calls: {{CALLS}} (call site → schema name and version → consumer)\n- Tools: {{TOOLS}} (tool name → side effect → who may call it, or \"none\")\n- Schema location: {{SCHEMA_DIR}} (default `src/main/resources/llm-schemas/`)\n- Validator: {{VALIDATOR}} (networknt json-schema-validator 3.x for Jackson 3, 2.x for Jackson 2, or the one the repo already uses)\n- Failure contract: {{FAILURE_CONTRACT}} (HTTP status and problem+json codes, or the internal result type)\n- Budget: {{BUDGET}} (route deadline, max output tokens, and whether one repair fits)\n- Observability: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both)\n- Eval gate: {{EVAL_GATE}} (existing eval CI job and fixture path, or \"none\")\n- Pain: {{PAIN}} (parse exceptions | refusals parsed as data | truncated JSON | unbounded retries | unsafe tool calls | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}}: every place model output is parsed, every tool executor, every retry around a model call, and any regex that pulls `{...}` out of text\n - Table: call site | schema (or none) | mode (native | json_mode | prompt_only | tool) | stop reason checked? | server-side validator? | retry policy | consumer\n - Flag `readValue` on raw completion text in a broad catch, unbounded \"retry until it parses\" loops, brace-closing or quote-fixing helpers, `ScriptEngine`/SpEL/reflection/polymorphic typing driven by output, and tenant or user IDs taken from tool arguments\n\n2. Schemas in {{SCHEMA_DIR}}\n - One file per schema and version (`ticket_triage.v2.json`), Draft 2020-12, `$id` set, stored in the repo\n - Object root. `additionalProperties: false` on every object. Every property in `required`; use a nullable type where a value can be absent\n - Decisions are `enum`, each with an explicit escape value (`unknown`, `insufficient_input`). No free-form unions or \"any JSON\" fields. Real variants use a discriminator enum and one closed object per kind\n - Bounds on numbers, arrays, and ID-shaped strings\n - One source of truth: generate from the Java record or test that the record and the schema agree\n - Check each schema against the strict-mode subset of every target in {{PROVIDERS}}. When a keyword is rejected, enforce that rule in the server-side validator or in code. Do not delete the rule\n\n3. Request mode\n - Use native schema mode (OpenAI/Azure OpenAI `json_schema` with strict, Anthropic JSON outputs) or strict tool definitions where the target supports them. Choose per target from capability config, not from a model-name string\n - Targets without support stay explicit as `json_mode` or `prompt_only`, and get the same server-side checks\n - Disable parallel tool calls on a request where they conflict with strict schemas on that provider\n\n4. Ordered response checks (each failure is a typed outcome; nothing falls through to the parser)\n - Stop reason first. Normal completion continues. Truncation (`length`, `max_tokens`, `max_output_tokens`, incomplete status, context-window stop) → `truncated`. Refusal (a `refusal` field or item, `stop_reason: refusal`) → `refused`. Content filter or guardrail stop → `filtered`. Anything unmapped → `unexpected_stop`\n - Extract from the field the mode uses (message content, or the named tool call's arguments). Exactly one document where one is expected. No searching prose for `{`\n - Byte cap before parsing → `oversize`\n - Strict parse: duplicate keys rejected (`STRICT_DUPLICATE_DETECTION`), no comments or trailing commas, `FAIL_ON_UNKNOWN_PROPERTIES` on for these records → `parse_error`\n - Validate with {{VALIDATOR}} → `schema_invalid` with a list of `{path, keyword}` pairs. For `required`, add the missing property name to the path\n - Bind to the record, then run business rules the schema cannot express (cross-field totals, referenced ID exists and belongs to this tenant) → `business_rule_invalid`\n\n5. Validator setup\n - One registry bean with an explicit Draft 2020-12 dialect. Load schemas from the classpath at startup, compile once, preload validators so a broken `$ref` fails at boot, and fail startup when a configured schema is missing. No remote `$ref` fetching\n - Turn on format assertions if any field relies on `format`, or use `pattern`, and test a bad value\n - Validate in native mode too\n\n6. One repair, then fail closed\n - `parse_error`, `schema_invalid`, `business_rule_invalid`: re-ask once on the same target with the same schema and mode, adding a short system-authored message that lists the `{path, keyword}` violations. No field values or user text in that message\n - `truncated`: one retry with a higher output-token cap only if {{BUDGET}} allows; otherwise fail. Never stitch a \"continue\" onto a structured document\n - `refused`, `filtered`, `unexpected_stop`, `oversize`, or any second failure: no retry\n - The repair counts against the route deadline and token budget. It is not a provider fallback. Never relax the schema, drop strict mode, or switch to prompt-only on the retry\n - Remove guessing fixers. A deterministic normalizer is allowed only for a documented case (one Markdown code fence around otherwise valid JSON from a prompt-only target), and its use is counted\n - Return {{FAILURE_CONTRACT}}: problem+json codes such as `llm_output_invalid`, `llm_output_refused`, `llm_output_truncated`, or a sealed result type. Nothing downstream receives a partial or default-constructed record\n\n7. Never evaluate output\n - No ScriptEngine, SpEL, OGNL, Groovy, template evaluation, reflection on model-supplied names, or polymorphic Jackson typing on these records\n - Behavior-selecting fields are enums mapped in a `switch`. Strings that reach SQL, a shell, a URL, HTML, or a log are parameterized or encoded for that sink\n\n8. Tool calls ({{TOOLS}})\n - Tool name on this route's allowlist, checked before argument parsing\n - Arguments validated against the server's copy of the tool schema, then bound\n - Authorize as the end user. Tenant and user come from the authenticated context, never from arguments. Every ID is checked against what this caller may access\n - Allowlist target-selecting values (hosts, queues, tables, paths, domains). Bound amounts and limits\n - Side-effecting tools get a server-generated idempotency key and, where high impact, a confirmation step\n - A rejection goes back to the model as a short tool error and shares the single repair limit\n\n9. Metrics and logs ({{OBSERVABILITY}})\n - `llm_structured_output_total` labels: `route`, `schema`, `mode`, `outcome` (`valid`, `repaired`, `parse_error`, `schema_invalid`, `business_rule_invalid`, `refused`, `truncated`, `filtered`, `unexpected_stop`, `oversize`)\n - `llm_structured_output_violations_total` labels: `schema`, `keyword`. Paths go in log fields, not labels\n - `llm_tool_call_rejected_total` labels: `route`, `tool`, `reason` (`unknown_tool`, `schema_invalid`, `not_authorized`, `not_allowlisted`)\n - Log request ID, route, schema version, mode, target, stop reason, outcome, violation pairs, and whether repair ran. Never the completion, the arguments, the failing value, or a hash of it\n\n10. Tests and CI ({{EVAL_GATE}})\n - Offline fixtures per schema version, run on every PR: valid docs, missing required, extra property, wrong enum, disallowed null, duplicate key, truncated object, refusal, content-filter stop, prose around JSON, two tool calls where one was expected, unknown tool name. Each asserts the outcome, the violation list, and that the consumer or tool stub saw nothing\n - Repair: stub returns invalid then valid → two calls, `repaired`, and the repair message contains paths and keywords but no fixture values. Stub returns invalid twice → two calls, typed failure, no third call\n - Truncation and refusal: no parse attempt, correct outcome, no repair call for the refusal\n - Tool authz: valid arguments naming another tenant's ID → `not_authorized`, zero tool stub calls\n - Schema and record agree; each schema passes the strict-subset check for every target that uses it\n - Live conformance (scheduled or when prompt, model, or schema changes): first-attempt `valid` rate, `repaired` rate, and failure rate per schema version, reported into the existing eval gate. Fail below the recorded floor or on any `unexpected_stop`. Do not build a second gate\n - Synthetic fixtures only\n\n11. Verification\n - Inventory table from step 1, updated\n - Schema list with version, mode per target, and the rules enforced only server-side\n - Outcome mapping table: provider stop reason → outcome → HTTP code or result type\n - Tests added and what each asserts\n\nConstraints:\n- Minimal diff. Match the module's config, error, and test style. No new HTTP client, no second JSON library, and no second validator if one is already present.\n- No real customer text, live endpoints, or secrets in fixtures. Stub providers for every test except the scheduled live conformance run.\n- Do not weaken validation, raise the repair limit, or loosen `additionalProperties` to make a test pass.\n- Leave prompt-injection trust maps and output-sink encoding, routing and fallback (including `fallbackOnBadRequest`), PII redaction, eval gate wiring, and price tables to their existing skills. Call their hooks where this stage sits next to them.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table and the parse sites that still trust raw output\n2. Schemas and config diff (mode per target, validator bean, outcome enum)\n3. Code diff (ordered checks, repair, failure contract, tool gate, counters)\n4. Tests added and what each asserts, including the repair and tool-authz cases\n5. Outcome mapping table and the conformance floor per schema version\n\nStart from {{APP_PATH}}. Land the stop-reason checks, the server-side validator, and the offline fixtures before turning on a new schema version or a new tool.\n" + "body": "Task: Make the LLM calls I specify return schema-valid JSON, or a typed failure, every time. Use provider-native schema mode or strict tools where the target supports them, and validate every document on the server against a versioned schema anyway. Check the stop reason before parsing. Allow one bounded repair, then fail closed. Treat tool-call arguments as untrusted input. Count outcomes without logging payloads, and add schema-conformance fixtures to CI. Finish with a minimal diff, the schemas, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service or gateway and module: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version and Jackson 2 or 3; Spring AI | LangChain4j | plain HTTP client | mixed)\n- Providers and targets: {{PROVIDERS}} (Azure OpenAI, OpenAI, Anthropic, Amazon Bedrock, OpenRouter, other OpenAI-compatible) and which support native schema mode or strict tools\n- Structured calls: {{CALLS}} (call site → schema name and version → consumer)\n- Tools: {{TOOLS}} (tool name → side effect → who may call it, or \"none\")\n- Schema location: {{SCHEMA_DIR}} (default `src/main/resources/llm-schemas/`)\n- Validator: {{VALIDATOR}} (networknt json-schema-validator 3.x for Jackson 3, 2.x for Jackson 2, or the one the repo already uses)\n- Failure contract: {{FAILURE_CONTRACT}} (HTTP status and problem+json codes, or the internal result type)\n- Budget: {{BUDGET}} (route deadline, max output tokens, and whether one repair fits)\n- Observability: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both)\n- Eval gate: {{EVAL_GATE}} (existing eval CI job and fixture path, or \"none\")\n- Pain: {{PAIN}} (parse exceptions | refusals parsed as data | truncated JSON | unbounded retries | unsafe tool calls | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}}: every place model output is parsed, every tool executor, every retry around a model call, and any regex that pulls `{...}` out of text\n - Table: call site | schema (or none) | mode (native | json_mode | prompt_only | tool) | stop reason checked? | server-side validator? | retry policy | consumer\n - Flag `readValue` on raw completion text in a broad catch, unbounded \"retry until it parses\" loops, brace-closing or quote-fixing helpers, `ScriptEngine`/SpEL/reflection/polymorphic typing driven by output, and tenant or user IDs taken from tool arguments\n\n2. Schemas in {{SCHEMA_DIR}}\n - One file per schema and version (`ticket_triage.v2.json`), Draft 2020-12, `$id` set, stored in the repo\n - Object root. `additionalProperties: false` on every object. Every property in `required`; use a nullable type where a value can be absent\n - Decisions are `enum`, each with an explicit escape value (`unknown`, `insufficient_input`). No free-form unions or \"any JSON\" fields. Real variants use a discriminator enum and one closed object per kind\n - Bounds on numbers, arrays, and ID-shaped strings\n - One source of truth: generate from the Java record or test that the record and the schema agree\n - Check each schema against the strict-mode subset of every target in {{PROVIDERS}}. When a keyword is rejected, enforce that rule in the server-side validator or in code. Do not delete the rule\n\n3. Request mode\n - Use native schema mode (OpenAI/Azure OpenAI `json_schema` with strict, Anthropic JSON outputs) or strict tool definitions where the target supports them. Choose per target from capability config, not from a model-name string\n - Targets without support stay explicit as `json_mode` or `prompt_only`, and get the same server-side checks\n - Disable parallel tool calls on a request where they conflict with strict schemas on that provider\n\n4. Ordered response checks (each failure is a typed outcome; nothing falls through to the parser)\n - Stop reason first. Normal completion continues. Truncation (`length`, `max_tokens`, `max_output_tokens`, incomplete status, context-window stop) → `truncated`. Refusal (a `refusal` field or item, `stop_reason: refusal`) → `refused`. Content filter or guardrail stop → `filtered`. Anything unmapped → `unexpected_stop`\n - Extract from the field the mode uses (message content, or the named tool call's arguments). Exactly one document where one is expected. No searching prose for `{`\n - Byte cap before parsing → `oversize`\n - Strict parse on a dedicated Jackson reader, not the shared mapper: `STRICT_DUPLICATE_DETECTION`, `FAIL_ON_TRAILING_TOKENS`, and `FAIL_ON_UNKNOWN_PROPERTIES` enabled explicitly (Jackson 3 and Spring Boot's default mapper leave unknown properties allowed), no comments or trailing commas → `parse_error`\n - Validate with {{VALIDATOR}} → `schema_invalid` with a list of `{path, keyword}` pairs. For `required`, add the missing property name to the path\n - Bind to the record, then run business rules the schema cannot express (cross-field totals, referenced ID exists and belongs to this tenant) → `business_rule_invalid`\n\n5. Validator setup\n - One registry bean with an explicit Draft 2020-12 dialect. Load schemas from the classpath at startup, compile once, preload validators so a broken `$ref` fails at boot, and fail startup when a configured schema is missing. No remote `$ref` fetching\n - Turn on format assertions if any field relies on `format`, or use `pattern`, and test a bad value\n - Validate in native mode too\n\n6. One repair, then fail closed\n - `parse_error`, `schema_invalid`, `business_rule_invalid`: re-ask once on the same target with the same schema and mode, adding a short system-authored message that lists the `{path, keyword}` violations. No field values or user text in that message\n - `truncated`: one retry with a higher output-token cap only if {{BUDGET}} allows; otherwise fail. Never stitch a \"continue\" onto a structured document\n - `refused`, `filtered`, `unexpected_stop`, `oversize`, or any second failure: no retry\n - The repair counts against the route deadline and token budget. It is not a provider fallback. Never relax the schema, drop strict mode, or switch to prompt-only on the retry\n - Remove guessing fixers. A deterministic normalizer is allowed only for a documented case (one Markdown code fence around otherwise valid JSON from a prompt-only target), and its use is counted\n - Return {{FAILURE_CONTRACT}}: problem+json codes such as `llm_output_invalid`, `llm_output_refused`, `llm_output_truncated`, or a sealed result type. Nothing downstream receives a partial or default-constructed record\n\n7. Never evaluate output\n - No ScriptEngine, SpEL, OGNL, Groovy, template evaluation, reflection on model-supplied names, or polymorphic Jackson typing on these records\n - Behavior-selecting fields are enums mapped in a `switch`. Strings that reach SQL, a shell, a URL, HTML, or a log are parameterized or encoded for that sink\n\n8. Tool calls ({{TOOLS}})\n - Tool name on this route's allowlist, checked before argument parsing\n - Arguments validated against the server's copy of the tool schema, then bound\n - Authorize as the end user. Tenant and user come from the authenticated context, never from arguments. Every ID is checked against what this caller may access\n - Allowlist target-selecting values (hosts, queues, tables, paths, domains). Bound amounts and limits\n - Side-effecting tools get a server-generated idempotency key and, where high impact, a confirmation step\n - A rejection goes back to the model as a short tool error and shares the single repair limit\n\n9. Metrics and logs ({{OBSERVABILITY}})\n - `llm_structured_output_total` labels: `route`, `schema`, `mode`, `outcome` (`valid`, `repaired`, `parse_error`, `schema_invalid`, `business_rule_invalid`, `refused`, `truncated`, `filtered`, `unexpected_stop`, `oversize`)\n - `llm_structured_output_violations_total` labels: `schema`, `keyword`. Paths go in log fields, not labels\n - `llm_tool_call_rejected_total` labels: `route`, `tool`, `reason` (`unknown_tool`, `schema_invalid`, `not_authorized`, `not_allowlisted`)\n - Log request ID, route, schema version, mode, target, stop reason, outcome, violation pairs, and whether repair ran. Never the completion, the arguments, the failing value, or a hash of it\n\n10. Tests and CI ({{EVAL_GATE}})\n - Offline fixtures per schema version, run on every PR: valid docs, missing required, extra property, wrong enum, disallowed null, duplicate key, truncated object, refusal, content-filter stop, prose around JSON, two tool calls where one was expected, unknown tool name. Each asserts the outcome, the violation list, and that the consumer or tool stub saw nothing\n - Repair: stub returns invalid then valid → two calls, `repaired`, and the repair message contains paths and keywords but no fixture values. Stub returns invalid twice → two calls, typed failure, no third call\n - Truncation and refusal: no parse attempt, correct outcome, no repair call for the refusal\n - Tool authz: valid arguments naming another tenant's ID → `not_authorized`, zero tool stub calls\n - Schema and record agree; each schema passes the strict-subset check for every target that uses it\n - Live conformance (scheduled or when prompt, model, or schema changes): first-attempt `valid` rate, `repaired` rate, and failure rate per schema version, reported into the existing eval gate. Fail below the recorded floor or on any `unexpected_stop`. Do not build a second gate\n - Synthetic fixtures only\n\n11. Verification\n - Inventory table from step 1, updated\n - Schema list with version, mode per target, and the rules enforced only server-side\n - Outcome mapping table: provider stop reason → outcome → HTTP code or result type\n - Tests added and what each asserts\n\nConstraints:\n- Minimal diff. Match the module's config, error, and test style. No new HTTP client, no second JSON library, and no second validator if one is already present.\n- No real customer text, live endpoints, or secrets in fixtures. Stub providers for every test except the scheduled live conformance run.\n- Do not weaken validation, raise the repair limit, or loosen `additionalProperties` to make a test pass.\n- Leave prompt-injection trust maps and output-sink encoding, routing and fallback (including `fallbackOnBadRequest`), PII redaction, eval gate wiring, and price tables to their existing skills. Call their hooks where this stage sits next to them.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table and the parse sites that still trust raw output\n2. Schemas and config diff (mode per target, validator bean, outcome enum)\n3. Code diff (ordered checks, repair, failure contract, tool gate, counters)\n4. Tests added and what each asserts, including the repair and tool-authz cases\n5. Outcome mapping table and the conformance floor per schema version\n\nStart from {{APP_PATH}}. Land the stop-reason checks, the server-side validator, and the offline fixtures before turning on a new schema version or a new tool.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index fe293d4..2a94ba8 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -1079,7 +1079,7 @@ "gateway" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-structured-output.instructions.md` with applyTo for `**/llm/**`, `**/*Schema*.java`, `**/*Tool*.java`, `**/gateway/**`, and `**/llm-schemas/**`. Optional on-demand procedure at `.github/skills/llm-structured-output-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-structured-output-guardrails/SKILL.md` plus a CLAUDE.md fact that model JSON and tool arguments are validated server-side against versioned schemas before use, with one repair and then a typed failure. Codex: a short \"LLM structured output\" brief in root `AGENTS.md` (schema location, validator bean, outcome enum, conformance test command) while the procedure stays in SKILL.md. Pair with llm-app-prompt-injection-guardrails for tool agency and output-sink encoding, llm-gateway-routing-fallback-guardrails for capability skips and fallbackOnBadRequest, llm-pii-redaction-guardrails for anything logged, llm-eval-ci-regression-gate for the gate that reads the conformance rate, and llm-cost-latency-budget-guardrails for the repair attempt's budget. This skill owns the schema contract, the check order, validation, repair, and the tool-argument gate.", - "body": "# Skill: LLM Structured Output Guardrails\n\n## Goal\n\nWhen a Java or Spring Boot service, or an LLM gateway, needs JSON from a model (an extraction record, a classification, a routing decision, or the arguments of a tool call), the code that consumes it gets either a document that passed the server's own schema check or a typed failure. It never gets \"probably JSON\", a half-finished object, or a refusal that was parsed as data.\n\nThis skill owns the output contract: the schema and its version, the provider mode that asks for it, the stop-reason checks before parsing, server-side validation, the single bounded repair attempt, the fail-closed result, tool-call arguments as untrusted input, counters for validation outcomes, and the conformance fixtures that keep the rate visible in CI.\n\nTrust boundaries, tool agency, and encoding output for HTML, SQL, or a shell stay in **llm-app-prompt-injection-guardrails**. This skill makes the payload well-formed. That skill decides what a well-formed payload is still not allowed to do. Capability-based target selection (`json_schema`, `tools`) and the `fallbackOnBadRequest` switch stay in **llm-gateway-routing-fallback-guardrails**. Redacting personal data before the call, and in anything logged after it, stays in **llm-pii-redaction-guardrails**. The CI gate wiring, golden-set versioning, and baselines stay in **llm-eval-ci-regression-gate**; this skill only adds the schema-conformance cases and the metric that gate reads. Token and cost accounting for the retry stays in **llm-cost-latency-budget-guardrails**. HTTP API contracts between services stay in **spring-boot-openapi-contract-guardrails**.\n\n\"Respond only with valid JSON\" in a prompt is a request, not a control. The control is this code path.\n\n## When to apply\n\n- A feature parses model output into a record, an enum, or a command, with Spring AI, LangChain4j, or a plain HTTP client\n- A tool-calling or agent loop where the model supplies arguments that the service executes\n- A gateway that forwards `response_format`, `output_config.format`, or tool definitions and has to behave the same across providers\n- A review that finds `objectMapper.readValue(...)` on raw completion text inside a broad `try/catch`, regex extraction of `{...}` from prose, or a retry loop with no limit\n- Moving from prompt-only JSON or legacy JSON mode to provider-native schema mode\n\n## Ask the provider for the schema, then still validate\n\nThere are three levels. Use the highest one the target supports, and validate on the server at every level.\n\n| Level | What it guarantees | Where it is set |\n|---|---|---|\n| Native schema mode (strict) | Output is generated against the supplied schema, except on refusal, truncation, or another stop condition | OpenAI and Azure OpenAI: `json_schema` response format or `strict` function tools. Anthropic: JSON outputs (`output_config.format`) and `strict: true` on tool definitions. Bedrock Converse and OpenAI-compatible routers: check the model's documented support and treat the rest as level 3 |\n| JSON mode | Syntactically valid JSON. No schema adherence | Legacy `json_object` response format and similar |\n| Prompt only | Nothing | Instructions plus examples |\n\nRules:\n\n- Pick the level per target from the gateway's capability list, not from the model name in a string. A target without `json_schema` is skipped or flagged by the routing skill; it is not sent the same request and expected to comply.\n- Strict modes accept a subset of JSON Schema, and the subset differs by provider. Public docs list which keywords are supported (typically `enum`, `anyOf`, `$defs`/`$ref`, numeric and array bounds, some `format` values) and which are rejected (often `allOf`, `not`, `if`/`then`/`else`, `dependentRequired`). When a keyword is rejected, move that rule into the server-side validator or into code. Do not delete it to get the request accepted.\n- Native mode does not make values correct. A well-formed record can still carry a wrong total, an invented ID, or a guess where the input had nothing to extract. Business rules are checked in code after the schema passes.\n- The first request with a new schema can be slower on some providers while the schema is compiled and cached. Warm it in a smoke test after deploy rather than on a user request.\n\n## Schema design\n\nDesign the schema for the consumer and for strict mode at the same time.\n\n- **Object root, closed objects.** The root is an object. Every object sets `additionalProperties: false`. Unknown keys are a validation error, not something Jackson silently drops.\n- **Required everything.** List every property in `required`. When a value can be absent, make it nullable (`\"type\": [\"string\", \"null\"]`) instead of optional, so \"missing\" and \"not known\" are the same explicit thing.\n- **Enums for decisions.** Labels, actions, statuses, and severities are `enum`. Add an explicit escape value (`unknown`, `insufficient_input`, `not_applicable`) so the model has a legal answer when the input does not fit. Without it, strict mode forces a guess.\n- **No free-form unions.** Avoid `anyOf` of unrelated shapes and \"any JSON\" fields. When variants are real, use a discriminator (`\"kind\": {\"enum\": [\"refund\", \"replacement\"]}`) with one closed object per kind, and keep it within the provider's nesting limits.\n- **Bounded values.** `minimum`/`maximum`, `maxItems`, and `pattern` or `maxLength` where the provider and your validator support them. A field the consumer uses as an ID matches the ID's shape.\n- **No reasoning fields you do not need.** A `reasoning` or `explanation` string is free text inside a structured result. Keep it short and bounded if the product needs it, and never feed it to another system as an instruction.\n- **Versioned.** Each schema has a stable name and a version (`invoice_extract.v3`) stored in the repo, for example `src/main/resources/llm-schemas/invoice_extract.v3.json`, with `$id` set. The version travels with the request metadata, the metric labels, and the eval fixtures. A breaking change is a new version, and both versions validate during the rollout.\n- **One source of truth.** Generate the schema from the Java record (Spring AI's bean output converter, LangChain4j's JSON schema support, or a schema generator in the build) or hand-write it and test that the record and the schema agree. Do not keep two drifting copies.\n\n```json\n{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.example.com/llm/ticket_triage.v2.json\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"schema_version\", \"category\", \"priority\", \"customer_ref\", \"summary\"],\n \"properties\": {\n \"schema_version\": { \"const\": \"ticket_triage.v2\" },\n \"category\": { \"enum\": [\"billing\", \"access\", \"outage\", \"other\", \"insufficient_input\"] },\n \"priority\": { \"enum\": [\"p1\", \"p2\", \"p3\", \"p4\"] },\n \"customer_ref\": { \"type\": [\"string\", \"null\"], \"pattern\": \"^CUS-[0-9]{8}$\" },\n \"summary\": { \"type\": \"string\", \"maxLength\": 400 }\n }\n}\n```\n\nCheck `const` and every other keyword against the target provider's strict subset before you rely on it in the request. The server-side validator enforces the full schema either way.\n\n## Order of checks on every response\n\nRun these in order. Each step that fails returns a typed outcome and stops; it never falls through to the parser.\n\n1. **Transport and provider error.** Owned by the routing skill. Nothing below runs on a non-2xx.\n2. **Stop reason.** Read it before touching the content.\n - Normal completion (`stop`, `end_turn`, `tool_use` / `tool_calls` when a tool call was expected): continue.\n - Truncation (`length`, `max_tokens`, `max_output_tokens`, an `incomplete` status, a context-window stop): outcome `truncated`. A cut-off object is not repaired by closing its braces.\n - Refusal (a separate `refusal` field or content item, `stop_reason: refusal`): outcome `refused`. The refusal text is not data and is not parsed against the schema.\n - Content filter or guardrail stop (`content_filter`, a guardrail intervention): outcome `filtered`.\n - Anything unrecognized: outcome `unexpected_stop`. Fail closed. Add the value to the mapping when you see it.\n3. **Extract.** Take the structured content from the field the mode uses (the message content in schema mode, the arguments of the named tool call in tool mode). Do not search prose for the first `{`. Exactly one document. Reject a response with zero or several when one was expected. When strict tool calling and parallel calls conflict on the provider, turn parallel calls off for that request.\n4. **Size.** Reject a document over the configured byte cap before parsing.\n5. **Parse.** Strict parser: no comments, no trailing commas, no single quotes, duplicate keys rejected. In Jackson, enable `STRICT_DUPLICATE_DETECTION` and keep `FAIL_ON_UNKNOWN_PROPERTIES` on for these records.\n6. **Validate** against the versioned schema with a JSON Schema validator (below). Collect all errors.\n7. **Bind** to the Java record, then run the business rules the schema cannot express (cross-field totals, a referenced ID exists and belongs to this tenant, a date is in range).\n8. **Use.** Only now does the value reach the caller, a tool, or a store.\n\n## Server-side validation in Java\n\nValidate even in native mode. The provider's guarantee does not cover refusal, truncation, a provider bug, a router that silently drops the schema parameter, a model swapped behind an alias, or a schema keyword the provider ignored.\n\n- **networknt json-schema-validator** is the common choice. The 3.x line targets Java 17+ and Jackson 3 (Spring Boot 4). The 2.x line targets Jackson 2 (Spring Boot 3). Its 2.x and later API uses a `SchemaRegistry` with an explicit dialect (Draft 2020-12) and returns a list of errors. Other maintained validators are fine if the repo already uses one; pick one, not two.\n- Load schemas from the classpath at startup, compile them once, and keep the registry as a singleton bean. Call `initializeValidators()` on each loaded schema so a broken `$ref` fails at boot instead of on the first request. Fail startup if a schema referenced in config is missing or does not compile. Do not fetch remote `$ref` targets at runtime (2.x and later leave remote fetching off by default; keep it off).\n- Since Draft 2019-09, `format` is an annotation unless assertion is turned on. If a field depends on `format` (`date`, `uuid`, `email`), enable format assertions in the validator's execution config or use a `pattern`, and test that a bad value fails.\n- Map each error to `{path, keyword}`, for example `{\"/priority\", \"enum\"}`. For `required`, the instance location is the parent object, so append the missing property name from the error. That pair goes into the repair message and the log; the keyword alone goes into the metric. The offending value goes nowhere.\n- Bean Validation on the bound record (`@NotNull`, `@Pattern`) is a useful second layer for business rules. It is not a substitute for schema validation, because binding has already dropped or coerced things by then.\n\n```java\n// Spring Boot 4 / Jackson 3 sketch using networknt 3.x\n@Bean\nSchemaRegistry llmSchemaRegistry() {\n return SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12);\n}\n\nValidationResult validate(String schemaId, JsonNode doc) {\n Schema schema = schemas.get(schemaId); // compiled once at startup from classpath\n List errors = schema.validate(doc);\n return errors.isEmpty()\n ? ValidationResult.ok()\n : ValidationResult.invalid(errors.stream()\n .map(e -> new SchemaViolation(String.valueOf(e.getInstanceLocation()), e.getKeyword()))\n .toList());\n}\n```\n\nTreat the sketch as shape only and check method names against the version in the build.\n\n## Bounded repair, then fail closed\n\nAt most one repair attempt per logical call, and only for outcomes repair can fix.\n\n- **Repairable:** `parse_error`, `schema_invalid`, `business_rule_invalid`. Re-ask once on the same target with the original messages, the model's previous output, and a short system-authored message listing the violations as `{path, keyword}` pairs (\"`/priority` must be one of p1, p2, p3, p4\"). Do not echo user content or field values in that message. Keep the same schema and the same mode.\n- **Truncated:** one retry with a higher output-token cap, only if the cap is still inside the route's token budget. Otherwise fail. Do not ask the model to \"continue\" a structured document and stitch the halves together.\n- **Not repairable:** `refused`, `filtered`, `unexpected_stop`, oversize, or a second failure of any kind. Return the typed failure.\n- The repair attempt counts against the route deadline and token budget (**llm-cost-latency-budget-guardrails**). It is not a routing fallback, and it does not move to another provider. Whether a provider 400 on the schema itself may fall back is the routing skill's `fallbackOnBadRequest` decision.\n- Never relax the schema, drop the strict flag, or switch to prompt-only JSON on the retry.\n- No local \"fixers\" that guess: no trimming to the last `}`, no regex quoting of keys, no defaulting a missing required field. A deterministic normalizer is allowed only for a documented, tested case (stripping a single Markdown code fence around otherwise valid JSON from a prompt-only target), and its use is counted.\n\nFail closed means the caller gets a typed error, not a partial record. For an HTTP API, problem+json with a stable code: `llm_output_invalid` (422 or 502, pick one per API and document it), `llm_output_refused`, `llm_output_truncated`. For an internal call, a sealed result type (`Valid | Invalid | Refused | Truncated | Filtered`) so the compiler forces every branch. Nothing downstream receives a default-constructed record.\n\n## Never evaluate model output\n\nStructured output is data. It is never code.\n\n- No `ScriptEngine`, SpEL, OGNL, MVEL, Groovy, JavaScript, or template evaluation of any field. No reflection on a class or method name the model supplied. No polymorphic Jackson typing (`@JsonTypeInfo` with class names, default typing) on these records.\n- A field that selects behavior is an enum mapped in a `switch` to code you wrote. A string is not a method name, a bean name, a URL, a file path, or a query fragment.\n- A field that ends up in SQL, a shell, a URL, HTML, or a log line is encoded or parameterized for that sink, as **llm-app-prompt-injection-guardrails** requires.\n\n## Tool-call arguments are untrusted input\n\nStrict tool calling guarantees the arguments match the tool's schema. It does not mean the caller is allowed to do what they describe.\n\n- The tool name must be on this route's allowlist. An unknown or disallowed name is rejected before argument parsing, even if the provider says it is valid.\n- Validate arguments against the server's copy of the tool schema, the same way as any structured output, then bind to a record.\n- Authorize as the end user (on-behalf-of or row-filtered access), not as the service. Every ID in the arguments is checked against what this caller may touch. Tenant and user come from the authenticated context, never from an argument.\n- Allowlist values that select targets: hosts, queues, table names, file roots, email domains. Bounded numbers for limits and amounts.\n- Side-effecting tools need an idempotency key from the server (not the model) and, where the action is high impact, a confirmation step. Loop limits and approval steps are in the prompt-injection skill.\n- A validation or authorization failure goes back to the model as a short tool error (\"argument `/account_id` not permitted\") so the loop can recover once, and it counts toward the same single repair limit.\n\n## Metrics and logs without payloads\n\nCount outcomes, not content.\n\n- `llm_structured_output_total`: counter. Labels: `route`, `schema` (name and version), `mode` (`native`, `json_mode`, `prompt_only`, `tool`), `outcome` (`valid`, `repaired`, `parse_error`, `schema_invalid`, `business_rule_invalid`, `refused`, `truncated`, `filtered`, `unexpected_stop`, `oversize`).\n- `llm_structured_output_violations_total`: counter. Labels: `schema`, `keyword` (`required`, `enum`, `additionalProperties`, `type`, `pattern`, ...). Use the keyword, not the instance path, so label cardinality stays fixed. Put the path in a log field if you need it.\n- `llm_tool_call_rejected_total`: counter. Labels: `route`, `tool`, `reason` (`unknown_tool`, `schema_invalid`, `not_authorized`, `not_allowlisted`).\n- Logs: request ID, route, schema version, mode, provider target, stop reason, outcome, violation `{path, keyword}` pairs, and whether repair ran. Not the completion, not the arguments, not the offending value, and not a hash of it. If a debug capture is truly needed, it goes through the redacted view from **llm-pii-redaction-guardrails** and stays off in shared environments.\n- Alert on a rise in `schema_invalid` or `refused` per schema version, and on any `unexpected_stop`. A jump after a model or alias change usually means the target lost native schema support.\n\n## Conformance fixtures in CI\n\nAdd schema conformance to the existing eval gate in **llm-eval-ci-regression-gate**. Do not build a second gate.\n\n- **Offline, deterministic (every PR).** A fixture directory per schema version with recorded or synthetic model outputs: valid documents, a missing required field, an extra property, a wrong enum, a null where not allowed, a duplicate key, a truncated object, a refusal response, a content-filter stop, a response with prose around the JSON, two tool calls where one was expected, and an unknown tool name. Each fixture asserts the outcome, the `{path, keyword}` list, and that nothing reached the consumer or the tool stub.\n- **Repair path.** A stub provider returns an invalid document, then a valid one. Assert exactly two provider calls, outcome `repaired`, and that the repair message lists keywords and paths but contains none of the fixture values. A second stub returns invalid twice: assert two calls, the typed failure, and no third call.\n- **Truncation and refusal.** The stub returns `finish_reason: length` with a half object, and a refusal. Assert no parse attempt, the right outcome, and no repair call for the refusal.\n- **Tool authz.** Valid arguments with another tenant's ID are rejected with `not_authorized`, and the tool stub sees zero calls.\n- **Schema and record agree.** A test generates or loads the schema and checks it against the Java record, and a test sends each schema to a strict-mode lint (or a recorded provider acceptance) so a rejected keyword is caught before deploy.\n- **Live conformance rate (scheduled or on prompt/model change).** Run the golden inputs against the real target and report the share of `valid` on first attempt, `repaired`, and failed, per schema version. The gate fails when first-attempt conformance drops below the agreed floor for that schema, or when `unexpected_stop` appears. Record the floor next to the schema version.\n\nFixtures are synthetic. No customer transcripts.\n\n## Workflow\n\n1. Inventory every place model output is parsed or a tool call is executed. Table: call site | schema (or none) | mode | stop reason checked? | validator? | retry policy | consumer.\n2. Write or generate versioned schemas, closed and fully required, with enums and an escape value.\n3. Turn on native schema mode or strict tools where the target supports it. Keep prompt-only targets explicit.\n4. Add the ordered checks: stop reason, extract, size, strict parse, validate, bind, business rules.\n5. Add the single repair attempt and the typed failure result. Remove unbounded loops and guessing fixers.\n6. Gate tool calls: allowlist, server-side schema, end-user authz, value allowlists.\n7. Add the counters and log fields. Check that no payload or value reaches a log, a label, or a span.\n8. Land the fixtures and wire the conformance rate into the eval gate before enabling a new schema version in production.\n\n## Tool-specific notes\n\n- **GitHub Copilot:** path-scoped `.github/instructions/llm-structured-output.instructions.md` with `applyTo` for `**/llm/**`, `**/*Schema*.java`, `**/*Tool*.java`, `**/gateway/**`, and `**/llm-schemas/**`. Put the check order, \"validate even in native mode\", and \"one repair, then fail closed\" at the top. Keep the procedure in an optional `.github/skills/llm-structured-output-guardrails/SKILL.md`. Ask for the inventory table before editing a parser.\n- **Claude Code:** `.claude/skills/llm-structured-output-guardrails/SKILL.md` holds the procedure. Add one `CLAUDE.md` fact: \"Model JSON and tool arguments are validated server-side against versioned schemas in `llm-schemas/` before use. One repair attempt, then a typed failure. Model output is never evaluated.\"\n- **Codex:** root `AGENTS.md` stays a short brief: where schemas live, the validator bean, the outcome enum, and the conformance test command. The procedure lives in `SKILL.md`, or in a nested `AGENTS.md` beside the gateway module when the repo already uses nested briefs. Do not paste this whole skill into `AGENTS.md`.\n\n## Anti-patterns\n\n- \"Return only JSON\" in the prompt as the only control\n- Trusting native schema mode and skipping server-side validation\n- Parsing before checking the stop reason, so a refusal or a truncated object reaches the parser\n- Regex-extracting the first `{...}` from prose, or closing braces on a truncated document\n- `additionalProperties` left open, optional fields with silent Jackson defaults, or free-form string fields for decisions\n- Deleting a schema rule the provider rejected instead of enforcing it in the validator\n- Unbounded \"try again until it parses\" loops, or a retry that relaxes the schema or drops strict mode\n- `ScriptEngine`, SpEL, reflection, or polymorphic typing driven by model output\n- Executing a tool because the arguments are schema-valid, without the allowlist and end-user authorization\n- Tenant or user IDs taken from tool arguments\n- Logging the completion, the arguments, or the failing value to debug a validation error\n- Instance paths or values as metric labels\n- A schema change with no version bump and no fixtures\n\n## Done when\n\n- [ ] Every parse site and tool executor is in the inventory table with its schema version and mode\n- [ ] Schemas are versioned files in the repo, closed (`additionalProperties: false`), fully required with nullable instead of optional, enums with an escape value, no free-form unions\n- [ ] Native schema mode or strict tools are used where the target supports them, and rules the provider rejects are enforced server-side\n- [ ] Stop reason is checked before parsing; refusal, truncation, filter, and unknown stops are typed outcomes\n- [ ] A JSON Schema validator compiled at startup validates every document, including in native mode, then business rules run on the bound record\n- [ ] At most one repair attempt, inside the route budget, with `{path, keyword}` feedback and no values; then a typed failure\n- [ ] Model output is never evaluated or used for reflection or polymorphic typing\n- [ ] Tool calls pass a name allowlist, server-side schema validation, end-user authorization, and value allowlists before execution\n- [ ] Counters by route, schema version, mode, outcome, and keyword; no payloads or values in logs, labels, or spans\n- [ ] Conformance fixtures run on every PR, and the first-attempt conformance rate per schema version is a gate in the existing eval pipeline\n\n## Copy-ready SKILL.md stub\n\n```markdown\n---\nname: llm-structured-output-guardrails\ndescription: Use when a Java or Spring service or LLM gateway parses JSON from a model or executes tool-call arguments. Covers provider-native schema mode vs JSON mode vs prompt-only, closed and versioned JSON Schemas (required fields, enums with an escape value, additionalProperties false, no free-form unions), checking the stop reason before parsing (refusal, truncation, filter), server-side validation with a JSON Schema validator such as networknt, one bounded repair then fail closed, never evaluating output, tool arguments as untrusted input (allowlist, end-user authz), outcome counters without payloads, and schema-conformance fixtures in CI.\n---\n\nFollow LLM Structured Output Guardrails: ask the provider for native schema mode or strict tools where supported, and still validate every document on the server. Keep schemas versioned in the repo, closed, fully required (nullable instead of optional), with enums and an explicit escape value. Check the stop reason before parsing; refusal, truncation, and filter stops are typed failures, not data. Parse strictly, validate with a compiled JSON Schema validator, bind, then check business rules. Allow one repair attempt with path and keyword feedback and no values, then fail closed. Never evaluate model output. Treat tool-call arguments as untrusted: allowlist the tool, validate, authorize as the end user. Count outcomes by schema version and keyword, never log payloads, and gate first-attempt conformance in CI.\n```\n" + "body": "# Skill: LLM Structured Output Guardrails\n\n## Goal\n\nWhen a Java or Spring Boot service, or an LLM gateway, needs JSON from a model (an extraction record, a classification, a routing decision, or the arguments of a tool call), the code that consumes it gets either a document that passed the server's own schema check or a typed failure. It never gets \"probably JSON\", a half-finished object, or a refusal that was parsed as data.\n\nThis skill owns the output contract: the schema and its version, the provider mode that asks for it, the stop-reason checks before parsing, server-side validation, the single bounded repair attempt, the fail-closed result, tool-call arguments as untrusted input, counters for validation outcomes, and the conformance fixtures that keep the rate visible in CI.\n\nTrust boundaries, tool agency, and encoding output for HTML, SQL, or a shell stay in **llm-app-prompt-injection-guardrails**. This skill makes the payload well-formed. That skill decides what a well-formed payload is still not allowed to do. Capability-based target selection (`json_schema`, `tools`) and the `fallbackOnBadRequest` switch stay in **llm-gateway-routing-fallback-guardrails**. Redacting personal data before the call, and in anything logged after it, stays in **llm-pii-redaction-guardrails**. The CI gate wiring, golden-set versioning, and baselines stay in **llm-eval-ci-regression-gate**; this skill only adds the schema-conformance cases and the metric that gate reads. Token and cost accounting for the retry stays in **llm-cost-latency-budget-guardrails**. HTTP API contracts between services stay in **spring-boot-openapi-contract-guardrails**.\n\n\"Respond only with valid JSON\" in a prompt is a request, not a control. The control is this code path.\n\n## When to apply\n\n- A feature parses model output into a record, an enum, or a command, with Spring AI, LangChain4j, or a plain HTTP client\n- A tool-calling or agent loop where the model supplies arguments that the service executes\n- A gateway that forwards `response_format`, `output_config.format`, or tool definitions and has to behave the same across providers\n- A review that finds `objectMapper.readValue(...)` on raw completion text inside a broad `try/catch`, regex extraction of `{...}` from prose, or a retry loop with no limit\n- Moving from prompt-only JSON or legacy JSON mode to provider-native schema mode\n\n## Ask the provider for the schema, then still validate\n\nThere are three levels. Use the highest one the target supports, and validate on the server at every level.\n\n| Level | What it guarantees | Where it is set |\n|---|---|---|\n| Native schema mode (strict) | Output is generated against the supplied schema, except on refusal, truncation, or another stop condition | OpenAI and Azure OpenAI: `json_schema` response format or `strict` function tools. Anthropic: JSON outputs (`output_config.format`) and `strict: true` on tool definitions. Bedrock Converse and OpenAI-compatible routers: check the model's documented support and treat the rest as level 3 |\n| JSON mode | Syntactically valid JSON. No schema adherence | Legacy `json_object` response format and similar |\n| Prompt only | Nothing | Instructions plus examples |\n\nRules:\n\n- Pick the level per target from the gateway's capability list, not from the model name in a string. A target without `json_schema` is skipped or flagged by the routing skill; it is not sent the same request and expected to comply.\n- Strict modes accept a subset of JSON Schema, and the subset differs by provider. Public docs list which keywords are supported (typically `enum`, `anyOf`, `$defs`/`$ref`, numeric and array bounds, some `format` values) and which are rejected (often `allOf`, `not`, `if`/`then`/`else`, `dependentRequired`). When a keyword is rejected, move that rule into the server-side validator or into code. Do not delete it to get the request accepted.\n- Native mode does not make values correct. A well-formed record can still carry a wrong total, an invented ID, or a guess where the input had nothing to extract. Business rules are checked in code after the schema passes.\n- The first request with a new schema can be slower on some providers while the schema is compiled and cached. Warm it in a smoke test after deploy rather than on a user request.\n\n## Schema design\n\nDesign the schema for the consumer and for strict mode at the same time.\n\n- **Object root, closed objects.** The root is an object. Every object sets `additionalProperties: false`. Unknown keys are a validation error, not something Jackson silently drops.\n- **Required everything.** List every property in `required`. When a value can be absent, make it nullable (`\"type\": [\"string\", \"null\"]`) instead of optional, so \"missing\" and \"not known\" are the same explicit thing.\n- **Enums for decisions.** Labels, actions, statuses, and severities are `enum`. Add an explicit escape value (`unknown`, `insufficient_input`, `not_applicable`) so the model has a legal answer when the input does not fit. Without it, strict mode forces a guess.\n- **No free-form unions.** Avoid `anyOf` of unrelated shapes and \"any JSON\" fields. When variants are real, use a discriminator (`\"kind\": {\"enum\": [\"refund\", \"replacement\"]}`) with one closed object per kind, and keep it within the provider's nesting limits.\n- **Bounded values.** `minimum`/`maximum`, `maxItems`, and `pattern` or `maxLength` where the provider and your validator support them. A field the consumer uses as an ID matches the ID's shape.\n- **No reasoning fields you do not need.** A `reasoning` or `explanation` string is free text inside a structured result. Keep it short and bounded if the product needs it, and never feed it to another system as an instruction.\n- **Versioned.** Each schema has a stable name and a version (`invoice_extract.v3`) stored in the repo, for example `src/main/resources/llm-schemas/invoice_extract.v3.json`, with `$id` set. The version travels with the request metadata, the metric labels, and the eval fixtures. A breaking change is a new version, and both versions validate during the rollout.\n- **One source of truth.** Generate the schema from the Java record (Spring AI's bean output converter, LangChain4j's JSON schema support, or a schema generator in the build) or hand-write it and test that the record and the schema agree. Do not keep two drifting copies.\n\n```json\n{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.example.com/llm/ticket_triage.v2.json\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"schema_version\", \"category\", \"priority\", \"customer_ref\", \"summary\"],\n \"properties\": {\n \"schema_version\": { \"const\": \"ticket_triage.v2\" },\n \"category\": { \"enum\": [\"billing\", \"access\", \"outage\", \"other\", \"insufficient_input\"] },\n \"priority\": { \"enum\": [\"p1\", \"p2\", \"p3\", \"p4\"] },\n \"customer_ref\": { \"type\": [\"string\", \"null\"], \"pattern\": \"^CUS-[0-9]{8}$\" },\n \"summary\": { \"type\": \"string\", \"maxLength\": 400 }\n }\n}\n```\n\nCheck `const` and every other keyword against the target provider's strict subset before you rely on it in the request. The server-side validator enforces the full schema either way.\n\n## Order of checks on every response\n\nRun these in order. Each step that fails returns a typed outcome and stops; it never falls through to the parser.\n\n1. **Transport and provider error.** Owned by the routing skill. Nothing below runs on a non-2xx.\n2. **Stop reason.** Read it before touching the content.\n - Normal completion (`stop`, `end_turn`, `tool_use` / `tool_calls` when a tool call was expected): continue.\n - Truncation (`length`, `max_tokens`, `max_output_tokens`, an `incomplete` status, a context-window stop): outcome `truncated`. A cut-off object is not repaired by closing its braces.\n - Refusal (a separate `refusal` field or content item, `stop_reason: refusal`): outcome `refused`. The refusal text is not data and is not parsed against the schema.\n - Content filter or guardrail stop (`content_filter`, a guardrail intervention): outcome `filtered`.\n - Anything unrecognized: outcome `unexpected_stop`. Fail closed. Add the value to the mapping when you see it.\n3. **Extract.** Take the structured content from the field the mode uses (the message content in schema mode, the arguments of the named tool call in tool mode). Do not search prose for the first `{`. Exactly one document. Reject a response with zero or several when one was expected. When strict tool calling and parallel calls conflict on the provider, turn parallel calls off for that request.\n4. **Size.** Reject a document over the configured byte cap before parsing.\n5. **Parse.** Strict parser: no comments, no trailing commas, no single quotes, duplicate keys rejected, nothing after the document. Use a dedicated Jackson reader for these records and enable `STRICT_DUPLICATE_DETECTION`, `FAIL_ON_TRAILING_TOKENS`, and `FAIL_ON_UNKNOWN_PROPERTIES` on it explicitly. Jackson 3 turns unknown-property failure off by default, and Spring Boot's auto-configured mapper turns it off on Jackson 2, so do not rely on the shared mapper.\n6. **Validate** against the versioned schema with a JSON Schema validator (below). Collect all errors.\n7. **Bind** to the Java record, then run the business rules the schema cannot express (cross-field totals, a referenced ID exists and belongs to this tenant, a date is in range).\n8. **Use.** Only now does the value reach the caller, a tool, or a store.\n\n## Server-side validation in Java\n\nValidate even in native mode. The provider's guarantee does not cover refusal, truncation, a provider bug, a router that silently drops the schema parameter, a model swapped behind an alias, or a schema keyword the provider ignored.\n\n- **networknt json-schema-validator** is the common choice. The 3.x line targets Java 17+ and Jackson 3 (Spring Boot 4). The 2.x line targets Jackson 2 (Spring Boot 3). Its 2.x and later API uses a `SchemaRegistry` with an explicit dialect (Draft 2020-12) and returns a list of errors. Other maintained validators are fine if the repo already uses one; pick one, not two.\n- Load schemas from the classpath at startup, compile them once, and keep the registry as a singleton bean. Call `initializeValidators()` on each loaded schema so a broken `$ref` fails at boot instead of on the first request. Fail startup if a schema referenced in config is missing or does not compile. Do not fetch remote `$ref` targets at runtime (2.x and later leave remote fetching off by default; keep it off).\n- Since Draft 2019-09, `format` is an annotation unless assertion is turned on. If a field depends on `format` (`date`, `uuid`, `email`), enable format assertions in the validator's execution config or use a `pattern`, and test that a bad value fails.\n- Map each error to `{path, keyword}`, for example `{\"/priority\", \"enum\"}`. For `required`, the instance location is the parent object, so append the missing property name from the error. That pair goes into the repair message and the log; the keyword alone goes into the metric. The offending value goes nowhere.\n- Bean Validation on the bound record (`@NotNull`, `@Pattern`) is a useful second layer for business rules. It is not a substitute for schema validation, because binding has already dropped or coerced things by then.\n\n```java\n// Spring Boot 4 / Jackson 3 sketch using networknt 3.x\n@Bean\nSchemaRegistry llmSchemaRegistry() {\n return SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12);\n}\n\nValidationResult validate(String schemaId, JsonNode doc) {\n Schema schema = schemas.get(schemaId); // compiled once at startup from classpath\n List errors = schema.validate(doc);\n return errors.isEmpty()\n ? ValidationResult.ok()\n : ValidationResult.invalid(errors.stream()\n .map(e -> new SchemaViolation(String.valueOf(e.getInstanceLocation()), e.getKeyword()))\n .toList());\n}\n```\n\nTreat the sketch as shape only and check method names against the version in the build.\n\n## Bounded repair, then fail closed\n\nAt most one repair attempt per logical call, and only for outcomes repair can fix.\n\n- **Repairable:** `parse_error`, `schema_invalid`, `business_rule_invalid`. Re-ask once on the same target with the original messages, the model's previous output, and a short system-authored message listing the violations as `{path, keyword}` pairs (\"`/priority` must be one of p1, p2, p3, p4\"). Do not echo user content or field values in that message. Keep the same schema and the same mode.\n- **Truncated:** one retry with a higher output-token cap, only if the cap is still inside the route's token budget. Otherwise fail. Do not ask the model to \"continue\" a structured document and stitch the halves together.\n- **Not repairable:** `refused`, `filtered`, `unexpected_stop`, oversize, or a second failure of any kind. Return the typed failure.\n- The repair attempt counts against the route deadline and token budget (**llm-cost-latency-budget-guardrails**). It is not a routing fallback, and it does not move to another provider. Whether a provider 400 on the schema itself may fall back is the routing skill's `fallbackOnBadRequest` decision.\n- Never relax the schema, drop the strict flag, or switch to prompt-only JSON on the retry.\n- No local \"fixers\" that guess: no trimming to the last `}`, no regex quoting of keys, no defaulting a missing required field. A deterministic normalizer is allowed only for a documented, tested case (stripping a single Markdown code fence around otherwise valid JSON from a prompt-only target), and its use is counted.\n\nFail closed means the caller gets a typed error, not a partial record. For an HTTP API, problem+json with a stable code: `llm_output_invalid` (422 or 502, pick one per API and document it), `llm_output_refused`, `llm_output_truncated`. For an internal call, a sealed result type (`Valid | Invalid | Refused | Truncated | Filtered`) so the compiler forces every branch. Nothing downstream receives a default-constructed record.\n\n## Never evaluate model output\n\nStructured output is data. It is never code.\n\n- No `ScriptEngine`, SpEL, OGNL, MVEL, Groovy, JavaScript, or template evaluation of any field. No reflection on a class or method name the model supplied. No polymorphic Jackson typing (`@JsonTypeInfo` with class names, default typing) on these records.\n- A field that selects behavior is an enum mapped in a `switch` to code you wrote. A string is not a method name, a bean name, a URL, a file path, or a query fragment.\n- A field that ends up in SQL, a shell, a URL, HTML, or a log line is encoded or parameterized for that sink, as **llm-app-prompt-injection-guardrails** requires.\n\n## Tool-call arguments are untrusted input\n\nStrict tool calling guarantees the arguments match the tool's schema. It does not mean the caller is allowed to do what they describe.\n\n- The tool name must be on this route's allowlist. An unknown or disallowed name is rejected before argument parsing, even if the provider says it is valid.\n- Validate arguments against the server's copy of the tool schema, the same way as any structured output, then bind to a record.\n- Authorize as the end user (on-behalf-of or row-filtered access), not as the service. Every ID in the arguments is checked against what this caller may touch. Tenant and user come from the authenticated context, never from an argument.\n- Allowlist values that select targets: hosts, queues, table names, file roots, email domains. Bounded numbers for limits and amounts.\n- Side-effecting tools need an idempotency key from the server (not the model) and, where the action is high impact, a confirmation step. Loop limits and approval steps are in the prompt-injection skill.\n- A validation or authorization failure goes back to the model as a short tool error (\"argument `/account_id` not permitted\") so the loop can recover once, and it counts toward the same single repair limit.\n\n## Metrics and logs without payloads\n\nCount outcomes, not content.\n\n- `llm_structured_output_total`: counter. Labels: `route`, `schema` (name and version), `mode` (`native`, `json_mode`, `prompt_only`, `tool`), `outcome` (`valid`, `repaired`, `parse_error`, `schema_invalid`, `business_rule_invalid`, `refused`, `truncated`, `filtered`, `unexpected_stop`, `oversize`).\n- `llm_structured_output_violations_total`: counter. Labels: `schema`, `keyword` (`required`, `enum`, `additionalProperties`, `type`, `pattern`, ...). Use the keyword, not the instance path, so label cardinality stays fixed. Put the path in a log field if you need it.\n- `llm_tool_call_rejected_total`: counter. Labels: `route`, `tool`, `reason` (`unknown_tool`, `schema_invalid`, `not_authorized`, `not_allowlisted`).\n- Logs: request ID, route, schema version, mode, provider target, stop reason, outcome, violation `{path, keyword}` pairs, and whether repair ran. Not the completion, not the arguments, not the offending value, and not a hash of it. If a debug capture is truly needed, it goes through the redacted view from **llm-pii-redaction-guardrails** and stays off in shared environments.\n- Alert on a rise in `schema_invalid` or `refused` per schema version, and on any `unexpected_stop`. A jump after a model or alias change usually means the target lost native schema support.\n\n## Conformance fixtures in CI\n\nAdd schema conformance to the existing eval gate in **llm-eval-ci-regression-gate**. Do not build a second gate.\n\n- **Offline, deterministic (every PR).** A fixture directory per schema version with recorded or synthetic model outputs: valid documents, a missing required field, an extra property, a wrong enum, a null where not allowed, a duplicate key, a truncated object, a refusal response, a content-filter stop, a response with prose around the JSON, two tool calls where one was expected, and an unknown tool name. Each fixture asserts the outcome, the `{path, keyword}` list, and that nothing reached the consumer or the tool stub.\n- **Repair path.** A stub provider returns an invalid document, then a valid one. Assert exactly two provider calls, outcome `repaired`, and that the repair message lists keywords and paths but contains none of the fixture values. A second stub returns invalid twice: assert two calls, the typed failure, and no third call.\n- **Truncation and refusal.** The stub returns `finish_reason: length` with a half object, and a refusal. Assert no parse attempt, the right outcome, and no repair call for the refusal.\n- **Tool authz.** Valid arguments with another tenant's ID are rejected with `not_authorized`, and the tool stub sees zero calls.\n- **Schema and record agree.** A test generates or loads the schema and checks it against the Java record, and a test sends each schema to a strict-mode lint (or a recorded provider acceptance) so a rejected keyword is caught before deploy.\n- **Live conformance rate (scheduled or on prompt/model change).** Run the golden inputs against the real target and report the share of `valid` on first attempt, `repaired`, and failed, per schema version. The gate fails when first-attempt conformance drops below the agreed floor for that schema, or when `unexpected_stop` appears. Record the floor next to the schema version.\n\nFixtures are synthetic. No customer transcripts.\n\n## Workflow\n\n1. Inventory every place model output is parsed or a tool call is executed. Table: call site | schema (or none) | mode | stop reason checked? | validator? | retry policy | consumer.\n2. Write or generate versioned schemas, closed and fully required, with enums and an escape value.\n3. Turn on native schema mode or strict tools where the target supports it. Keep prompt-only targets explicit.\n4. Add the ordered checks: stop reason, extract, size, strict parse, validate, bind, business rules.\n5. Add the single repair attempt and the typed failure result. Remove unbounded loops and guessing fixers.\n6. Gate tool calls: allowlist, server-side schema, end-user authz, value allowlists.\n7. Add the counters and log fields. Check that no payload or value reaches a log, a label, or a span.\n8. Land the fixtures and wire the conformance rate into the eval gate before enabling a new schema version in production.\n\n## Tool-specific notes\n\n- **GitHub Copilot:** path-scoped `.github/instructions/llm-structured-output.instructions.md` with `applyTo` for `**/llm/**`, `**/*Schema*.java`, `**/*Tool*.java`, `**/gateway/**`, and `**/llm-schemas/**`. Put the check order, \"validate even in native mode\", and \"one repair, then fail closed\" at the top. Keep the procedure in an optional `.github/skills/llm-structured-output-guardrails/SKILL.md`. Ask for the inventory table before editing a parser.\n- **Claude Code:** `.claude/skills/llm-structured-output-guardrails/SKILL.md` holds the procedure. Add one `CLAUDE.md` fact: \"Model JSON and tool arguments are validated server-side against versioned schemas in `llm-schemas/` before use. One repair attempt, then a typed failure. Model output is never evaluated.\"\n- **Codex:** root `AGENTS.md` stays a short brief: where schemas live, the validator bean, the outcome enum, and the conformance test command. The procedure lives in `SKILL.md`, or in a nested `AGENTS.md` beside the gateway module when the repo already uses nested briefs. Do not paste this whole skill into `AGENTS.md`.\n\n## Anti-patterns\n\n- \"Return only JSON\" in the prompt as the only control\n- Trusting native schema mode and skipping server-side validation\n- Parsing before checking the stop reason, so a refusal or a truncated object reaches the parser\n- Regex-extracting the first `{...}` from prose, or closing braces on a truncated document\n- `additionalProperties` left open, optional fields with silent Jackson defaults, or free-form string fields for decisions\n- Deleting a schema rule the provider rejected instead of enforcing it in the validator\n- Unbounded \"try again until it parses\" loops, or a retry that relaxes the schema or drops strict mode\n- `ScriptEngine`, SpEL, reflection, or polymorphic typing driven by model output\n- Executing a tool because the arguments are schema-valid, without the allowlist and end-user authorization\n- Tenant or user IDs taken from tool arguments\n- Logging the completion, the arguments, or the failing value to debug a validation error\n- Instance paths or values as metric labels\n- A schema change with no version bump and no fixtures\n\n## Done when\n\n- [ ] Every parse site and tool executor is in the inventory table with its schema version and mode\n- [ ] Schemas are versioned files in the repo, closed (`additionalProperties: false`), fully required with nullable instead of optional, enums with an escape value, no free-form unions\n- [ ] Native schema mode or strict tools are used where the target supports them, and rules the provider rejects are enforced server-side\n- [ ] Stop reason is checked before parsing; refusal, truncation, filter, and unknown stops are typed outcomes\n- [ ] A JSON Schema validator compiled at startup validates every document, including in native mode, then business rules run on the bound record\n- [ ] At most one repair attempt, inside the route budget, with `{path, keyword}` feedback and no values; then a typed failure\n- [ ] Model output is never evaluated or used for reflection or polymorphic typing\n- [ ] Tool calls pass a name allowlist, server-side schema validation, end-user authorization, and value allowlists before execution\n- [ ] Counters by route, schema version, mode, outcome, and keyword; no payloads or values in logs, labels, or spans\n- [ ] Conformance fixtures run on every PR, and the first-attempt conformance rate per schema version is a gate in the existing eval pipeline\n\n## Copy-ready SKILL.md stub\n\n```markdown\n---\nname: llm-structured-output-guardrails\ndescription: Use when a Java or Spring service or LLM gateway parses JSON from a model or executes tool-call arguments. Covers provider-native schema mode vs JSON mode vs prompt-only, closed and versioned JSON Schemas (required fields, enums with an escape value, additionalProperties false, no free-form unions), checking the stop reason before parsing (refusal, truncation, filter), server-side validation with a JSON Schema validator such as networknt, one bounded repair then fail closed, never evaluating output, tool arguments as untrusted input (allowlist, end-user authz), outcome counters without payloads, and schema-conformance fixtures in CI.\n---\n\nFollow LLM Structured Output Guardrails: ask the provider for native schema mode or strict tools where supported, and still validate every document on the server. Keep schemas versioned in the repo, closed, fully required (nullable instead of optional), with enums and an explicit escape value. Check the stop reason before parsing; refusal, truncation, and filter stops are typed failures, not data. Parse strictly, validate with a compiled JSON Schema validator, bind, then check business rules. Allow one repair attempt with path and keyword feedback and no values, then fail closed. Never evaluate model output. Treat tool-call arguments as untrusted: allowlist the tool, validate, authorize as the end user. Count outcomes by schema version and keyword, never log payloads, and gate first-attempt conformance in CI.\n```\n" } ] }