Repository navigation
Description
Mirrors s-and-p-team/cortex#154, kept open there for active implementation tracking.
Problem Statement
A policy author onboarding a service today only discovers a grant/prohibit contradiction in their policy prose at commit time, and only one contradiction at a time. The live /apply path runs the Policy Rules Builder (PRB), and the first genuine contradiction the auditor confirms raises PolicyContradictionError → HTTP 422 and aborts the run — so any further contradictions in the same policy are never surfaced. The author fixes one, re-commits, hits the next, and repeats. Worse, the 422 error narrates the collision but never quotes the exact colliding sentences, so the author is left hunting through their prose for statements that "the policy says X" — when the phrasing they're looking for may not literally exist.
There is no way to ask, before committing, "does this candidate policy contradict itself for this service, and if so, show me all the collisions at once, each with the exact sentences that collide?"
Solution
Add a separate, read-only pre-commit diagnostic that a caller invokes before onboarding/committing a policy. Given candidate policy prose and a target service, it surveys that service's focal entities against the live IdP catalog, runs the same proposer → precheck → audit machinery the live path uses, and — instead of aborting on the first genuine contradiction — records every genuine contradiction and continues. It returns a single ConflictReport listing all conflicts at once, each with:
- the colliding
(role, scope)pair (name + id), - the conflict
kind(direct conflict, or coarse-scope granularity mismatch), - verbatim, validated quotations of the granting statement(s) and the prohibiting statement(s) from the policy text,
- a plain-language explanation.
If there are no conflicts, it reports "No conflict." (the rendered form of status: no_conflict).
This is a diagnostic gate, not the commit. It never mutates policy state, never blocks anything by itself, and does not replace or modify the live /apply → 422 path. The caller decides what to do with the report.
User Stories
- As a policy author, I want to check my candidate policy for contradictions before I commit it, so that I don't discover problems only after triggering an onboarding.
- As a policy author, I want every grant/prohibit contradiction for the service reported in a single response, so that I can fix them all in one pass instead of one-commit-per-conflict.
- As a policy author, I want each reported conflict to quote the exact granting and prohibiting sentences from my policy, so that I can find and edit the offending prose without guessing.
- As a policy author, I want the quotes to be literally present in my policy text (validated as substrings), so that a near-quote never sends me hunting for a sentence that isn't there.
- As a policy author, I want a plain-language explanation of why two statements collide, so that I understand the contradiction without re-deriving the rule logic.
- As a policy author, I want the diagnostic to catch coarse-scope contradictions (e.g. "management granted" while "writing forbidden"), not just direct same-name collisions, so that the more insidious granularity mismatches don't slip through.
- As a policy author, I want an explicit "No conflict." result when my policy is clean, so that I have positive confirmation rather than an ambiguous empty response.
- As a policy author, I want the diagnostic to resolve roles and scopes from the live IdP catalog for my service, so that reported conflicts are about real, typed entities and hallucinated entity names are dropped.
- As a policy author, I want to supply my candidate policy text directly to the check, so that I can evaluate prose I haven't committed to
AIAC_POLICY_FILEyet. - As a policy author, I want the check scoped to the single service I'm onboarding, so that "all conflicts" means all conflicts involving that service's focal entities — matching the unit I actually commit.
- As a policy author, I want an entity that the diagnostic could not evaluate (e.g. the proposer/auditor never converged) to be listed explicitly as
unevaluatedwith a reason, so that a partial survey never masquerades as a clean one. - As a policy author, I want a diagnostic run where zero entities could be evaluated to report
incomplete, notno_conflict, so that an upstream outage never looks identical to a conflict-free policy. - As a caller/integrator, I want a found conflict to return HTTP 200 (a successful diagnosis), not 422, so that I can distinguish "I successfully found conflicts" from "the request itself failed."
- As a caller/integrator, I want a pre-survey failure (IdP unreachable, unknown service, missing policy text) to return a non-2xx with no report, so that I never mistake an infrastructure failure for a diagnosis.
- As a caller/integrator, I want the report to document that
no_conflictmeans "no conflict introduced by this service's rules," not "the global policy is conflict-free," so that I don't over-read a per-service result. - As a platform maintainer, I want the diagnostic built on a testable plain function behind a thin route, so that the LLM-heavy logic is drivable by the
-m llmsuite without HTTP. - As a platform maintainer, I want the live
/applyconflict path and its 422 contract to remain byte-for-byte unchanged, so that this diagnostic can never silently downgrade a commit-blocking contradiction into a recorded-and-ignored report. - As a policy author, I want clean (non-conflicting) rules to carry no citation, so that the diagnostic doesn't manufacture quotes for rules that have no quotable source statement (description-derived grants, exclusivity-complement denies, deny-by-default).
- As a policy author, I want a conflict whose quotes fail substring validation to still be reported (with
quotes_verified=falseand a description fallback), so that a quoting failure never hides a real contradiction. - As a caller/integrator, I want the report to be a stable structured object (
conflicts,unevaluated,status), so that I can render it or gate on it programmatically.
Implementation Decisions
Layer / module. New capability in the Policy Rules Builder (agent layer). A separate diagnostic assembly is introduced alongside the existing live graph and the onboarding ServicePolicyBuilder fan-out. The safety-critical live /apply graph is not modified.
Reuse, don't rebuild. The following already exist and are reused unchanged: per-entity rule building (one run per own-scope and one per own-role), ALLOW+DENY PolicyRule emission, the proposer, the precheck overlap/hallucination filter, the auditor's genuine-contradiction-vs-proposer-slip adjudication, and the two recognized conflict kinds (direct + coarse-scope). The real deltas are: report all conflicts globally (today the first genuine one aborts); verbatim quotation (today the description narrates but doesn't quote); "No conflict" as an explicit outcome; and candidate-text input (today the source reads the configured AIAC_POLICY_FILE).
Public interface. A new Controller route (path decided at implementation, e.g. POST /policy/check or /policy/conflicts) is a thin serialization shell over a testable plain function check_policy_conflicts(...) -> ConflictReport. Inputs: candidate policy_text (supplied directly) + a service identifier.
- Catalog resolution is live from the IdP for the target service — the same own-scope / candidate-role / other-scope resolution the onboarding builder already performs. This is deliberately not a text-only endpoint: conflicts are structural (same role + same scope), which only means something against the real typed entity set, and reusing the resolution +
precheck's hallucination filtering guarantees every reported entity is real. - Policy text source is the candidate argument, not
AIAC_POLICY_FILE. The diagnostic's first node injects the supplied text in place of the live graph's file-reading fetch. - Scope of one check is per-service — "all conflicts" = all conflicts involving that service's focal entities, matching the commit unit (you onboard one service at a time).
Diagnostic pipeline (per focal entity).
inject candidate policy_text (replaces the file-reading fetch)
→ propose (reused unchanged)
→ precheck (reused unchanged; flags candidates in both the grant and prohibit lists)
→ audit_diagnostic:
genuine contradiction → RECORD (do NOT raise), continue
proposer slip → ordinary rejection → re-propose (≤ MAX_AUDIT_RETRIES)
retry budget exhausted → mark entity UNEVALUATED (do NOT raise)
→ explain (terminal; runs only if this entity has recorded genuine conflicts):
one LLM call per (role, scope) pair
→ granting_quotes[], prohibiting_quotes[] (verbatim, validated substrings)
→ explanation, kind
→ quotes_verified (false ⇒ fall back to the auditor description)
A survey orchestrator (alongside the onboarding builder's loop) runs every focal entity to completion — the first conflict never aborts — then assembles the report.
Assembly is separate, not a flag. The diagnostic reuses the proposer / precheck / prompts unchanged, but swaps in a record-not-raise audit node and adds a new terminal explain node, driven by a separate survey orchestrator. A diagnostic: bool flag inside the live audit node was rejected: it risks a contradiction that should 422 a commit silently becoming a recorded-and-ignored report.
Provenance is conflict-only. Clean rules carry no citation. Only auditor-confirmed genuine conflicts get quotes, produced by a dedicated explanation prompt. Rationale: many rules have no quotable statement (description-derived grants, exclusivity-complement denies, deny-by-default), so forcing per-rule citations would maximize hallucination where there's nothing to cite.
Explain only auditor-confirmed genuine conflicts — not every precheck overlap. The auditor's genuine-vs-slip adjudication is the machinery that keeps proposer noise out of the report; slips still trigger the normal retry (which usually erases the bogus overlap).
Explanation prompt: one call per conflict pair. Inputs = policy text + the one (role, scope) pair + the auditor's kind label. It does not receive the proposer's free-form reasoning (LLM narration that could anchor extraction onto a hallucinated justification). Per-pair isolation gives the cleanest verbatim extraction with no cross-pair contamination and matches the per-pair report row and per-pair validation/fallback.
Verbatim + validated quotes. The explanation prompt returns exact substrings of the policy text; the tool checks each is a substring (whitespace-normalized). Each side is a list of spans ("one or more" statements). On validation failure the conflict is kept, quotes_verified is set false, and the tool falls back to the auditor description.
Report both conflict kinds — direct and coarse-scope granularity. The machinery already distinguishes the two, so it is nearly free, and a coarse-scope contradiction is the more insidious of the two.
Identity by entity id; no cross-run reconciliation. The fan-out is disjoint (scope-focal = candidate role × own scope; role-focal = own role × other-service scope; own vs. other split by service id), so the same pair is never decided twice. A conflict is always a within-single-run overlap.
Report + status contract.
ConflictReport:
conflicts: [{ focal, role (name+id), scope (name+id), kind, # kind ∈ {direct, coarse_scope}
granting_quotes[], prohibiting_quotes[],
explanation, quotes_verified }]
unevaluated: [{ focal, reason }]
status: "no_conflict" | "conflicts_found" | "incomplete"
no_conflict⇔ ≥1 entity evaluated ANDconflicts == []ANDunevaluated == []. The literal string "No conflict" is the rendered form of this status — never a bare string that could mask an incomplete run.conflicts_found⇔conflictsnon-empty.incomplete⇔ zero entities were successfully evaluated (all failed, or none existed). Guards against an outage looking identical to a clean policy.
HTTP status boundary.
- Pre-survey failure (can't build the entity set: IdP unreachable, unknown service, missing
policy_text) ⇒ non-2xx (502 for upstream IdP; 400/422 for bad input). No report produced. - Per-entity failure during the survey (an entity won't converge / exhausts retries) ⇒ 200, entity listed under
unevaluated, status ≠no_conflict. - Any completed survey (conflicts or clean, possibly partial) ⇒ 200. A found conflict is a successful diagnosis, not an error — unlike the live
/apply, this tool does not 422 on conflict.
Report boundary note. status == no_conflict means "no conflict introduced by this service's rules," not "the global policy is conflict-free." This must be documented in the report so callers don't over-read it.
Testing Decisions
A good test here asserts external behavior — the shape and status of the returned ConflictReport, and the substring-validity of quotes — never the internal node wiring or exact LLM wording. Model output is nondeterministic, so the live tier asserts structural properties (containment, substring-validity), not exact strings.
Three tiers, mirroring the repo's existing split (deterministic unit tests patch the _structured_call seam; the opt-in -m llm suite runs the real model):
- Deterministic unit (patch
_structured_call) — the bulk. The shared_structured_callLLM seam covers proposer, auditor, and the new per-pair explanation call (aside_effectlist drives all three), so no new patch seam is introduced. Cover: survey orchestration (all entities run; first conflict does not abort), conflict → report assembly, theunevaluatedpath on retry exhaustion, the zero-evaluated guard,statusderivation, and the verbatim-quote validator as a pure function (substring match, whitespace normalization,quotes_verified=falsefallback to the description). Prior art:test/agent/policy_rules_builder/test_graph.py(mocks_structured_call, stubsget_policy_source). - Live-LLM (
-m llm) — small, blatant planted fixtures: one direct conflict, one coarse-scope conflict, and one clean policy. Assert structural properties only: clean ⇒no_conflict; planted ⇒ the confirmed set contains the planted pair(s), and every returned quote is a verbatim substring of the policy text. Do not assert exact quote strings or explanation wording. Prior art:test/agent/policy_rules_builder/test_graph_live_llm.py. - Route — one thin test that the endpoint calls the survey function and serializes the report + status codes (function patched, no LLM). Prior art:
test/agent/controller/test_routes.py.
Out of Scope
- Whole-policy audit (survey every already-onboarded service). Desired later as a loop over the per-service check — a separate effort, not this work.
- Survey concurrency. Assume sequential (matches the onboarding builder); parallelize only if latency demands.
- Route path name. Decide at implementation (
/policy/checkvs/policy/conflicts). - Subtle-prose robustness / PRB precedence tuning (explicit prohibition vs description-derived grant). A separate PRB-quality concern, tracked distinctly; not a correctness gate for this feature.
- ALLOW-vs-DENY precedence / tie-break resolution at enforcement time. That is a distinct PCE/Rego concern (tracked in Follow-up: ALLOW/DENY conflict + precedence resolution s-and-p-team/cortex#124), not this diagnostic. This tool reports contradictions; it does not resolve them.
- No change to the live
/applypath or its 422 contradiction contract. - Provenance on non-conflicting rules. Descoped — clean rules carry no citation.
Further Notes
- Relationship to existing work. This sits next to the existing PRB contradiction path (the live
/apply→PolicyContradictionError→ HTTP 422 flow), which is not modified. Design predecessor: the two-sided ALLOW/DENY model and the PRB deny-extraction work (PRD: PRB deny-extraction from natural-language policy text s-and-p-team/cortex#123, closed). Sibling but distinct concern: enforcement-time precedence resolution (Follow-up: ALLOW/DENY conflict + precedence resolution s-and-p-team/cortex#124). - Design origin. This PRD is synthesized from the self-contained design handoff
aiac/docs/handoffs/04-policy-conflict-diagnostic.md(design agreed 2026-08-17, not yet implemented). All ten settled design decisions (D1–D10) and the acceptance criteria are captured above.
Implementation Decisions — code-contact addendum (D11–D14)
These resolve four points where the "reuse unchanged" framing meets the current PRB code. They do not change the design; they make it plannable for a fresh implementing agent.
- D11 — The structured
kindis produced by the newexplainnode, not read from the auditor. In the current code the conflict kind is not a typed value — it exists only as prose insideContradiction.description(graph.py:66-69);_precheckcollapses both kinds into one overlap signal (graph.py:192). Therefore theexplaincall classifieskind ∈ {direct, coarse_scope}itself, from the policy text + the(role, scope)pair, with the auditor's owndescriptionpassed in as a hint. Chosen over adding akindfield to the sharedContradiction/AuditVerdictmodels, which would touch the live/applypath that D1/D8 require to stay byte-for-byte unchanged. Passing the auditor'sdescription— the adjudicator's own conclusion, not the proposer's reasoning D9 excludes — is a safe hint. - D12 — Name→id join is the diagnostic's responsibility. Audit output carries only name strings (
Contradiction.candidate_name+PolicyContradictionError.focal,graph.py:88), never ids or typed objects. The survey orchestrator re-joins each name to the resolved entity set (D13) to recover the id, and tags each recorded conflict with its run direction at record time — scope-focal run ⇒ focal is the scope, candidate is the role; role-focal run ⇒ focal is the role, candidate is the scope — which is how the report'srole(name+id)/scope(name+id)sides are assigned. - D13 — Prerequisite refactor: extract a standalone resolver. Focal-entity resolution is currently inlined in
ServicePolicyBuilder.build()(builder.py:55-109) and entangled with the fan-out loop. Extract it intoresolve_focal_entities(service_id, service_type) -> FocalEntitySet(typed:own_scopes,own_roles,candidate_roles,other_scopes), and have both the livebuild()and the diagnostic call it. This is a pure extraction — no behavior change to the live path (covered by existing builder tests). The existingHTTPException(502/404)on IdP-unreachable/unknown-service moves into the resolver and directly satisfies this feature's pre-survey HTTP boundary. - D14 — "Separate assembly" = fork the audit node + build a parallel graph; there is no swap seam. The raise is hard-coded in
_audit(graph.py:211) with no strategy seam, and_fetchis the START node that calls the hard-codedget_policy_source()and overwrites any inputpolicy_text(graph.py:151). The diagnostic therefore uses: (i) a START node that seedspolicy_textfrom input state (no file read); (ii)_propose/_precheckreused unchanged; (iii) a forked_audit_diagnosticthat records contradictions into state instead of raising; (iv) a terminal_explainnode (D11). Livegraph.py_auditand thebuild_*entry points stay untouched. A new sequential survey orchestrator drives the per-entity units (concurrency remains deferred per Out of Scope).
Report contract — pinned details
granting_quotes/prohibiting_quotes:list[str]of verbatim substrings (not offset spans — nothing consumes offsets).- Quote validator: whitespace-normalization only (collapse all whitespace runs incl. newlines to a single space, trim ends) before the substring check. Deliberately no case-folding and no smart-quote/punctuation normalization: the quote must be findable as written in the author's prose; normalizing punctuation would let a non-findable near-quote pass. Smart-quote mismatches are allowed to fail →
quotes_verified=false+ description fallback, never a silent "fix." focal:{ name, id, type: "role" | "scope" }— in a conflict row it records which side drove the run; inunevaluatedit identifies the entity that failed.unevaluated[].reason: enum{ "nonconvergence" }(retry-budget exhaustion — the only per-entity failure mode in scope) + optional free-textdetail.- Service identifier = Keycloak internal UUID (
s.id == service_id), matchingPOST /apply/service/{service_id}. The new route is the controller's first JSON response body (existing routes return bare status codes).
Acceptance criteria
POSTwith a clean candidate policy + a real service ⇒ 200,status: no_conflict.POSTwith a candidate policy containing a direct and a coarse-scope conflict ⇒ 200,status: conflicts_found, both reported in a single response, each with validated verbatimgranting_quotes/prohibiting_quotes(orquotes_verified=false+ description fallback).- An entity that cannot converge appears under
unevaluatedwith a reason; the run still returns 200 and does not reportno_conflict. - IdP unreachable / unknown service / missing
policy_text⇒ non-2xx, no report. - Zero entities evaluated ⇒
status: incomplete, neverno_conflict. - The live
/applypath and its 422 behavior are unchanged (regression check). - Deterministic unit tests cover orchestration, report assembly,
unevaluated, the zero-evaluated guard, and the quote validator/fallback; the-m llmsuite asserts containment + substring-validity on planted/clean fixtures.
Assisted-By: Claude (Anthropic AI) [email protected]
Parent Epic: #2405
Sub-issues
Collapse Sub-issuesSub-issues
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity