"""Deterministic AST-, NEC-, and coordinator-driven contrastive J4 synthesis. Eliminates scenario-specific hand-authored refusal strings in Experiment E5/E5b by deriving structured contrastive J4 judgments directly from: 1. Compiled NIR AST (`spec.mandates`, `spec.hard_policies`, `spec.obligations`), 2. Deterministic Strong Kleene `Harness.preflight` envelopes, 3. Authoritative coordinator budget accounting (`LocalRestart.budget_status`), 4. Live `ObligationAutomaton` active duty state, and 5. M7 `ReasoningLedger.reuse` verification statuses. Zero scenario-ID branching or hand-written per-scenario strings appear in this module. """ from __future__ import annotations from typing import Any def _selector_matches(selector: Any, principal: str, action: str, resource: str, scope: str) -> bool: def _hit(values: Any, item: str) -> bool: return "*" in values or item in values return ( _hit(selector.principals, principal) and _hit(selector.actions, action) and _hit(selector.resources, resource) and _hit(selector.scopes, scope) ) def format_nir_expr(expr: Any) -> str: """Render a compiled KedgeSpec NIR Expression AST deterministically.""" op = expr.op if op == "literal": if isinstance(expr.operand, bool): return "true" if expr.operand else "false" return repr(expr.operand) if op == "fact": return str(expr.operand) if op == "not": return f"NOT {format_nir_expr(expr.args[0])}" if op in ("and", "or"): joiner = " AND " if op == "and" else " OR " return "(" + joiner.join(format_nir_expr(a) for a in expr.args) + ")" if op in ("eq", "ne", "lt", "le", "gt", "ge", "in"): sym = {"eq": "==", "ne": "!=", "lt": "<", "le": "<=", "gt": ">", "ge": ">=", "in": "IN"}[op] return f"({format_nir_expr(expr.args[0])} {sym} {format_nir_expr(expr.args[1])})" return f"{op}({', '.join(format_nir_expr(a) for a in expr.args)})" def eval_nir_expr_k3( expr: Any, facts: dict[str, Any], ) -> tuple[bool | None, list[str], list[str]]: """Evaluate a compiled NIR Expression AST under Strong Kleene 3-valued logic. Returns (value, unsatisfied_atoms, missing_atoms) where: - value is True, False, or None (UNDETERMINED), - unsatisfied_atoms records fact/predicate literals that evaluated False when needed for satisfaction, and - missing_atoms records fact names absent from `facts`. """ op = expr.op if op == "literal": val = expr.operand return (val if isinstance(val, bool) else bool(val), [], []) if op == "fact": name = str(expr.operand) if name not in facts or facts[name] is None: return (None, [], [name]) val = bool(facts[name]) return (val, ([] if val else [f"{name}=false"]), []) if op == "not": sub_val, sub_unsat, sub_miss = eval_nir_expr_k3(expr.args[0], facts) if sub_val is None: return (None, [], sub_miss) if sub_val is True: inner = format_nir_expr(expr.args[0]) return (False, [f"{inner}=true (negated)"], []) return (True, [], []) if op == "and": vals: list[bool | None] = [] unsat: list[str] = [] miss: list[str] = [] for arg in expr.args: v, u, m = eval_nir_expr_k3(arg, facts) vals.append(v) if v is False: unsat.extend(u) elif v is None: miss.extend(m) if any(v is False for v in vals): return (False, _dedup(unsat), _dedup(miss)) if any(v is None for v in vals): return (None, [], _dedup(miss)) return (True, [], []) if op == "or": vals = [] unsat = [] miss = [] for arg in expr.args: v, u, m = eval_nir_expr_k3(arg, facts) vals.append(v) if v is False: unsat.extend(u) elif v is None: miss.extend(m) if any(v is True for v in vals): return (True, [], []) if any(v is None for v in vals): return (None, [], _dedup(miss)) return (False, _dedup(unsat), []) if op in ("eq", "ne", "lt", "le", "gt", "ge", "in"): lhs = _eval_scalar(expr.args[0], facts) rhs = _eval_scalar(expr.args[1], facts) missing = _collect_missing_facts(expr, facts) if lhs is None or rhs is None: return (None, [], missing) res = { "eq": lhs == rhs, "ne": lhs != rhs, "lt": lhs < rhs, "le": lhs <= rhs, "gt": lhs > rhs, "ge": lhs >= rhs, "in": lhs in rhs, }[op] return (res, ([] if res else [f"{format_nir_expr(expr)} (observed {lhs!r} vs {rhs!r})"]), []) return (None, [], _collect_missing_facts(expr, facts)) def _eval_scalar(expr: Any, facts: dict[str, Any]) -> Any: if expr.op == "literal": return expr.operand if expr.op == "fact": return facts.get(str(expr.operand)) return None def _collect_missing_facts(expr: Any, facts: dict[str, Any]) -> list[str]: if expr.op == "fact": name = str(expr.operand) return [name] if (name not in facts or facts[name] is None) else [] out: list[str] = [] for arg in getattr(expr, "args", ()): out.extend(_collect_missing_facts(arg, facts)) return _dedup(out) def _dedup(items: list[str]) -> list[str]: seen: set[str] = set() out: list[str] = [] for x in items: if x not in seen: seen.add(x) out.append(x) return out def render_complete_compiled_guidance(spec: Any) -> str: """Deterministically compile full mandate and hard-policy guidance directly from NIR AST. Used by equal-information baseline configurations (`C1_equal_info`, `C2_equal_info`) so no mandates or prohibitions are omitted from prose guidance. """ parts = [f"Compiled KedgeSpec Governance (digest {spec.digest[:18]}):"] for m in spec.mandates: acts = ", ".join(sorted(m.selector.actions)) parts.append(f"{m.id} MAY [{acts}] WHEN {format_nir_expr(m.when)}.") for hp in spec.hard_policies: acts = ", ".join(sorted(hp.selector.actions)) mod = hp.modality.value if hasattr(hp.modality, "value") else str(hp.modality) parts.append(f"{hp.id} {mod} [{acts}] CONDITION {format_nir_expr(hp.condition)}.") for t in getattr(spec, "tenets", ()): parts.append(f"{t.id} SHOULD (defeasible preference; deviation within admissible mandates is permitted).") for o in getattr(spec, "obligations", ()): parts.append(f"{o.id} AFTER trigger MUST fulfill post-commit duty within deadline.") return " ".join(parts) def synthesize_static_refusal_j4( spec: Any, *, principal: str, action: str, resource: str, scope: str, facts: dict[str, Any], preflight_envelopes: dict[str, dict[str, Any]], verdict_code: str = "DENIED", nrl_statuses: dict[str, dict[str, Any]] | None = None, evidence_actions: tuple[str, ...] = (), ) -> dict[str, Any]: """Synthesize a contrastive J4 record directly from NIR AST + Strong Kleene preflight.""" triggered_forbids: list[str] = [] forbid_reasons: list[str] = [] failed_musts: list[str] = [] failed_mandates: list[str] = [] unsat_atoms: list[str] = [] missing_atoms: list[str] = [] for hp in spec.hard_policies: if not _selector_matches(hp.selector, principal, action, resource, scope): continue mod = hp.modality.value if hasattr(hp.modality, "value") else str(hp.modality) val, unsat, miss = eval_nir_expr_k3(hp.condition, facts) if mod == "MUST_NOT" and val is True: triggered_forbids.append(hp.id) forbid_reasons.append(f"{hp.id} ({format_nir_expr(hp.condition)}=true)") elif mod == "MUST" and val is not True: failed_musts.append(hp.id) unsat_atoms.extend(unsat) missing_atoms.extend(miss) matching_mandates = [ m for m in spec.mandates if _selector_matches(m.selector, principal, action, resource, scope) ] any_mandate_satisfied = False for m in matching_mandates: val, unsat, miss = eval_nir_expr_k3(m.when, facts) if val is True: any_mandate_satisfied = True else: failed_mandates.append(m.id) unsat_atoms.extend(unsat) missing_atoms.extend(miss) unsat_atoms = _dedup(unsat_atoms) missing_atoms = _dedup(missing_atoms) feasible_alts = [ act for act, info in preflight_envelopes.items() if act != action and info.get("envelope") == "FEASIBLE_AT_SNAPSHOT" ] reusable_nrl = [ act for act, info in (nrl_statuses or {}).items() if info.get("m7_reuse_status") == "REUSABLE" ] if triggered_forbids: kind = "HARD_PROHIBITION" failed_ids = triggered_forbids cause = f"Blocked by MUST_NOT {', '.join(forbid_reasons)} on {action} ({verdict_code})." elif failed_musts: kind = "HARD_MUST_UNSATISFIED" failed_ids = failed_musts detail = ", ".join(unsat_atoms + [f"missing:{m}" for m in missing_atoms]) or verdict_code cause = f"Blocked by MUST {', '.join(failed_musts)} on {action}: {detail}." elif not matching_mandates: kind = "NO_MATCHING_MANDATE" failed_ids = [] cause = f"Blocked ({verdict_code}): no active MAY mandate authorizes {action} for {principal}." elif not any_mandate_satisfied and missing_atoms: kind = "MISSING_MANDATORY_FACT" failed_ids = failed_mandates cause = ( f"Fail-closed denial ({verdict_code}) on {action}: mandate(s) {', '.join(failed_mandates)} " f"lack mandatory fact(s) {', '.join(missing_atoms)}." ) elif not any_mandate_satisfied: kind = "MANDATE_GUARD_UNSATISFIED" failed_ids = failed_mandates detail = ", ".join(unsat_atoms) or "guard false" cause = ( f"Blocked by mandate guard {', '.join(failed_mandates)} on {action}: {detail}." ) else: kind = "RUNTIME_PRECONDITION_UNMET" failed_ids = [] cause = f"Blocked ({verdict_code}) on {action}: runtime prerequisite not yet discharged." next_clauses: list[str] = [] if reusable_nrl: next_clauses.append( f"Verified M7 NRL reusable observation action(s): {', '.join(reusable_nrl)}." ) if evidence_actions and (kind in ("MISSING_MANDATORY_FACT", "RUNTIME_PRECONDITION_UNMET")): next_clauses.append( f"Evidence acquisition action(s): {', '.join(evidence_actions)}." ) if feasible_alts: next_clauses.append( f"Snapshot-feasible admissible alternative(s): {', '.join(feasible_alts)}." ) elif not reusable_nrl and not evidence_actions: next_clauses.append("No snapshot-feasible alternative remains; escalate.") rendered = " ".join([cause, *next_clauses]) return { "kind": kind, "failed_rule_ids": failed_ids, "failed_atoms": unsat_atoms, "missing_atoms": missing_atoms, "admissible_alternatives": feasible_alts, "reusable_nrl_actions": reusable_nrl, "rendered": rendered, } def synthesize_capacity_refusal_j4( *, rule_id: str, code: str, action: str, requested_units: int, budget_entry: dict[str, Any], candidate_costs: dict[str, int], feasible_actions: list[str], ) -> dict[str, Any]: """Synthesize contrastive J4 directly from coordinator budget_status accounting.""" limit = int(budget_entry["limit"]) available = int(budget_entry["available"]) admissible_within_budget = sorted( [ act for act in feasible_actions if act != action and act in candidate_costs and candidate_costs[act] <= available ], key=lambda a: (-candidate_costs[a], a), ) if admissible_within_budget: alt_str = ", ".join(f"{a} (cost={candidate_costs[a]})" for a in admissible_within_budget) alt_clause = f"Admissible candidate(s) within remaining budget: {alt_str}." else: alt_clause = "No admissible candidate fits within remaining budget; escalate." rendered = ( f"Blocked by {rule_id} ({code}): {action} requires {requested_units} unit(s), " f"but only {available}/{limit} remain. {alt_clause}" ) return { "kind": "CAPACITY_REFUSAL", "failed_rule_ids": [rule_id], "code": code, "requested_units": requested_units, "remaining_units": available, "budget_limit": limit, "admissible_alternatives": admissible_within_budget, "rendered": rendered, } def synthesize_revocation_refusal_j4( *, code: str, principal: str, action: str, ) -> dict[str, Any]: """Synthesize contrastive J4 directly from authoritative epoch revocation refusal.""" rendered = ( f"Blocked by {code}: principal {principal!r} authority epoch is revoked for {action}; " "admissible remediation set is empty; call escalate." ) return { "kind": "AUTHORITY_REVOKED", "failed_rule_ids": [code], "principal": principal, "admissible_alternatives": [], "rendered": rendered, } def synthesize_obligation_refusal_j4( *, action: str, active_duties: list[dict[str, str]], trigger_actions: list[str], trigger_already_committed: bool, ) -> dict[str, Any]: """Synthesize contrastive J4 directly from ObligationAutomaton pending duty state.""" if trigger_already_committed and active_duties: duty_str = ", ".join(f"{d['rule_id']} ({d['required_outcome']})" for d in active_duties) rendered = ( f"Trigger action {action} already committed; fulfill active post-commit duties: " f"{duty_str} before finishing." ) return { "kind": "OBLIGATION_PENDING", "failed_rule_ids": [d["rule_id"] for d in active_duties], "admissible_alternatives": [d["required_outcome"] for d in active_duties], "rendered": rendered, } trig_str = ", ".join(trigger_actions) rendered = ( f"No active post-commit duty requires {action} yet; commit trigger action(s) " f"{trig_str} first." ) return { "kind": "OBLIGATION_PRE_TRIGGER", "failed_rule_ids": [], "admissible_alternatives": list(trigger_actions), "rendered": rendered, } def synthesize_nrl_refusal_j4( *, action: str, verdict_code: str, nrl_statuses: dict[str, dict[str, Any]], ) -> dict[str, Any]: """Synthesize contrastive J4 directly from M7 Ledger.reuse verification statuses.""" reusable = [ act for act, info in nrl_statuses.items() if info.get("m7_reuse_status") == "REUSABLE" ] rejected = [ f"{act}:{info.get('m7_reuse_status')}" for act, info in nrl_statuses.items() if info.get("m7_reuse_status") != "REUSABLE" ] if reusable: alt_clause = ( f"M7 Ledger.reuse verifies REUSABLE record(s): {', '.join(reusable)} " f"(rejected: {', '.join(rejected) or 'none'})." ) else: alt_clause = "No M7 Ledger.reuse record is REUSABLE; acquire fresh evidence or escalate." rendered = f"Blocked ({verdict_code}) on {action}. {alt_clause}" return { "kind": "NRL_OR_SENSOR_REFUSAL", "failed_rule_ids": [verdict_code], "admissible_alternatives": reusable, "rendered": rendered, } def synthesize_unknown_action_j4(*, action: str, allowed_actions: list[str]) -> dict[str, Any]: """Synthesize contrastive J4 for an action outside the declared tool menu.""" rendered = f"Unknown action {action!r}; choose strictly from {allowed_actions}." return { "kind": "UNKNOWN_ACTION", "failed_rule_ids": [], "admissible_alternatives": list(allowed_actions), "rendered": rendered, }