Documentation

Docs / Proofs

Derived.lean

Lean 4 source (Lean 4 core, no Mathlib). 59 theorems. Download Derived.lean.

Theorems in this file
  • all_congr'
  • all_mono'
  • any_congr'
  • filter_congr'
  • eval_reading_free
  • deps_sub_closure
  • guardRF_lit
  • gEval_rf
  • guardRF_lit'
  • atom_eval_rf
  • evalProg_mono
  • ok_guard
  • ok_lifts
  • ok_neg
  • checkN_rules
  • checkN_clauses
  • checkN_trusted
  • trusted_deps_rf
  • lift_rf
  • lt_iff
  • lt_asymm
  • lt_trans
  • lt_total
  • choose_none
  • choose_mem
  • choose_max
  • choose_congr
  • foldr_perm
  • appK_rf
  • appK_rf_guarded
  • forbids_rf
  • permits_rf
  • caps_rf
  • prot_rf
  • factasks_rf
  • unlifted_rf
  • failed_rf
  • capped_rf
  • offers_rf
  • chosen_offer_reading_free
  • decide_shape
  • finish_tail_released
  • release_reading_free_of_check
  • reading_never_opens
  • noninterference_of_check
  • protective_duties_reading_free
  • owed_mono
  • perm_isEmpty
  • decide_perm
  • meet_glb
  • meet_comm'
  • meet_assoc'
  • rank_inj'
  • first_max_depends_on_order
  • check_is_needed_derived
  • ask_withholds_default
  • trusted_check_is_needed
  • protective_check_is_needed
  • negation_check_is_needed
/-
  Restriction N over DERIVED predicates, the choice of one released form, and protective
  duties (25 November 2026). Answers open item 1 and part of item 3 of the internal review of the paper draft.

  `Strict.lean` checks guards that are Boolean formulas over facts and readings. The
  interpreter (`experiments/kernel/core.py`) does more: guards are conjunctions of literals
  over facts, readings and DERIVED predicates, defined by non-recursive Datalog clauses; the
  check (`check_restrictions`) follows the dependency graph (`depends_on`); and when several
  permits apply, ONE offer is chosen by the key (height, form name, rule id). This file models
  that arrangement and proves:

  * `eval_reading_free`: a derived predicate whose dependencies contain no reading has the same
    value under every assignment of readings (induction over the clause list);
  * `deps_sub_closure`: the structural dependency set used in that proof is contained in the
    order-free, core.py-style closure that the check computes, so the check is sound;
  * `chosen_offer_reading_free`, `release_reading_free_of_check`, `reading_never_opens`: for
    every rule set that passes the check, the chosen offer (form AND rule) is the same under
    every reading; what is finally released is the same under every reading, for ANY default
    (with core.py's fix of 25 November: a reading-guarded ask no longer withholds a release);
    and a reading can change an allow only into a question (`ask`);
  * `trusted_deps_rf`, `lift_rf`: trusted predicates (declared, grant, …) defined by clauses
    that pass the check never depend on a reading, so boundary lifting ignores readings;
  * `choose_congr`, `decide_perm`: the canonical choice depends only on the SET of offers, so
    the whole decision is independent of rule order;
  * `protective_duties_reading_free`, `owed_mono`: owed protective duties never depend on a
    reading; more readings only add duties;
  * counterexamples, all by `decide`: `first_max_depends_on_order` (without the tie-break the
    form depends on rule order), `check_is_needed_derived` (a derived predicate that hides a
    reading opens data when only the guard's own atoms are checked), `trusted_check_is_needed`,
    `ask_withholds_default` (what the semantics before 25 November did), `protective_check_is_needed`,
    `negation_check_is_needed`.

  Ground (propositional) model: atoms carry no variables. See ../DERIVED.md for every
  departure from core.py. Lean 4 core only, no Mathlib, no `sorry`, no new axioms.
  Check with: lean Derived.lean
-/

namespace AccessDerived

/-! ## 1. Atoms, literals, clauses -/

/-- Ground atoms: facts, readings and derived predicates are three disjoint kinds. -/
inductive Atom (F Rd D : Type) where
  | fact : F → Atom F Rd D
  | read : Rd → Atom F Rd D
  | der : D → Atom F Rd D
  deriving DecidableEq, Repr

structure Lit (F Rd D : Type) where
  atom : Atom F Rd D
  neg : Bool := false
  deriving DecidableEq, Repr

/-- A clause `head :- body` (a conjunction of literals). -/
structure Clause (F Rd D : Type) where
  head : D
  body : List (Lit F Rd D)
  deriving Repr

variable {F Rd D A Fm : Type} [DecidableEq D]

def Atom.isRead : Atom F Rd D → Bool
  | .read _ => true
  | _ => false

def Atom.eval (φ : F → Bool) (ρ : Rd → Bool) (v : D → Bool) : Atom F Rd D → Bool
  | .fact a => φ a
  | .read b => ρ b
  | .der d => v d

def Lit.eval (φ : F → Bool) (ρ : Rd → Bool) (v : D → Bool) (l : Lit F Rd D) : Bool :=
  if l.neg then !l.atom.eval φ ρ v else l.atom.eval φ ρ v

/-- Evaluation by strata. The program is a list of clauses, LATEST FIRST: a clause sees the
    derived atoms computed by the clauses after it in the list (the earlier strata). This is
    core.py's `Model.__init__` over `topo_clauses` read from the other end. -/
def evalProg (φ : F → Bool) (ρ : Rd → Bool) : List (Clause F Rd D) → D → Bool
  | [] => fun _ => false
  | c :: P => fun d =>
      evalProg φ ρ P d || (decide (c.head = d) && c.body.all (Lit.eval φ ρ (evalProg φ ρ P)))

/-- A guard is a conjunction of literals, evaluated in the least model of the program. -/
def gEval (φ : F → Bool) (ρ : Rd → Bool) (P : List (Clause F Rd D)) (g : List (Lit F Rd D)) : Bool :=
  g.all (Lit.eval φ ρ (evalProg φ ρ P))

/-! ## 2. Dependencies -/

/-- An atom and, for a derived atom, what it depends on (given a dependency function). -/
def adeps (dp : D → List (Atom F Rd D)) (a : Atom F Rd D) : List (Atom F Rd D) :=
  a :: match a with
    | .der e => dp e
    | _ => []

/-- Structural dependency set: follows a clause body only into the strata below it. -/
def deps : List (Clause F Rd D) → D → List (Atom F Rd D)
  | [] => fun _ => []
  | c :: P => fun d =>
      (if c.head = d then c.body.flatMap (fun l => adeps (deps P) l.atom) else []) ++ deps P d

/-- The order-free closure with `n` steps, as core.py's `depends_on` computes it: every clause
    of the whole program whose head is `d`, whatever its position. -/
def clo (P : List (Clause F Rd D)) : Nat → D → List (Atom F Rd D)
  | 0 => fun _ => []
  | n + 1 => fun d =>
      P.flatMap (fun c => if c.head = d then c.body.flatMap (fun l => adeps (clo P n) l.atom) else [])

/-- core.py's `depends_on(clauses, preds)`: the atoms and everything reachable from them.
    `P.length` steps reach every predicate of a non-recursive program. -/
def dependsOn (P : List (Clause F Rd D)) (S : List (Atom F Rd D)) : List (Atom F Rd D) :=
  S.flatMap (adeps (clo P P.length))

/-- No reading among the dependencies. -/
def RF (L : List (Atom F Rd D)) : Prop := ∀ x ∈ L, x.isRead = false

/-! ### Small list lemmas -/

theorem all_congr' {α : Type} {f g : α → Bool} :
    ∀ l : List α, (∀ x ∈ l, f x = g x) → l.all f = l.all g
  | [], _ => rfl
  | x :: l, h => by
      simp only [List.all_cons]
      rw [h x (by simp), all_congr' l (fun y hy => h y (by simp [hy]))]

theorem all_mono' {α : Type} {f g : α → Bool} :
    ∀ l : List α, (∀ x ∈ l, f x = true → g x = true) → l.all f = true → l.all g = true
  | [], _, _ => rfl
  | x :: l, h, hl => by
      simp only [List.all_cons, Bool.and_eq_true] at hl ⊢
      exact ⟨h x (by simp) hl.1, all_mono' l (fun y hy => h y (by simp [hy])) hl.2⟩

theorem any_congr' {α : Type} {f g : α → Bool} :
    ∀ l : List α, (∀ x ∈ l, f x = g x) → l.any f = l.any g
  | [], _ => rfl
  | x :: l, h => by
      simp only [List.any_cons]
      rw [h x (by simp), any_congr' l (fun y hy => h y (by simp [hy]))]

theorem filter_congr' {α : Type} {f g : α → Bool} :
    ∀ l : List α, (∀ x ∈ l, f x = g x) → l.filter f = l.filter g
  | [], _ => rfl
  | x :: l, h => by
      have ih := filter_congr' l (fun y hy => h y (by simp [hy]))
      simp only [List.filter_cons, h x (by simp), ih]

/-! ### Soundness of the derived layer -/

/-- **Derived predicates that do not depend on readings ignore the readings.** If no reading is
    among the dependencies of `d`, then `d` has the same value under every assignment of readings. -/
theorem eval_reading_free (φ : F → Bool) (ρ ρ' : Rd → Bool) :
    ∀ (P : List (Clause F Rd D)) (d : D), RF (deps P d) → evalProg φ ρ P d = evalProg φ ρ' P d
  | [], _, _ => rfl
  | c :: P, d, h => by
      have hP : RF (deps P d) := fun x hx => h x (by simp [deps, hx])
      simp only [evalProg]
      rw [eval_reading_free φ ρ ρ' P d hP]
      by_cases hc : c.head = d
      · congr 1
        simp only [hc, decide_true, Bool.true_and]
        apply all_congr'
        intro l hl
        have hl' : RF (adeps (deps P) l.atom) := fun x hx =>
          h x (by simp only [deps, hc, ite_true, List.mem_append, List.mem_flatMap]; exact Or.inl ⟨l, hl, hx⟩)
        unfold Lit.eval
        have ha : l.atom.eval φ ρ (evalProg φ ρ P) = l.atom.eval φ ρ' (evalProg φ ρ' P) := by
          cases hla : l.atom with
          | fact a => rfl
          | read b =>
              have := hl' l.atom (by simp [adeps]); rw [hla] at this; simp [Atom.isRead] at this
          | der e =>
              simp only [Atom.eval]
              apply eval_reading_free φ ρ ρ' P e
              intro x hx; exact hl' x (by rw [hla]; simp [adeps, hx])
        rw [ha]
      · simp [hc]

/-- **The check is sound for derived predicates.** Everything the structural dependency set of
    any tail `Q` of the program reaches is also reached by the order-free closure over the whole
    program, given at least `Q.length` steps. So a guard that core.py's `depends_on` finds free
    of readings is also free of readings in the sense used by `eval_reading_free`. -/
theorem deps_sub_closure (P : List (Clause F Rd D)) :
    ∀ (Q : List (Clause F Rd D)), (∀ c ∈ Q, c ∈ P) → ∀ n, Q.length ≤ n →
      ∀ d x, x ∈ deps Q d → x ∈ clo P n d
  | [], _, _, _, _, _, hx => by simp [deps] at hx
  | c :: Q, hQ, n, hn, d, x, hx => by
      have hQ' : ∀ c' ∈ Q, c' ∈ P := fun c' h => hQ c' (by simp [h])
      obtain ⟨m, rfl⟩ : ∃ m, n = m + 1 := ⟨n - 1, by simp at hn; omega⟩
      have hm : Q.length ≤ m := by simp at hn; omega
      simp only [deps, List.mem_append] at hx
      cases hx with
      | inr hx => exact deps_sub_closure P Q hQ' (m + 1) (by omega) d x hx
      | inl hx =>
          by_cases hc : c.head = d
          · simp only [hc, ite_true, List.mem_flatMap] at hx
            obtain ⟨l, hl, hxl⟩ := hx
            simp only [clo, List.mem_flatMap]
            refine ⟨c, hQ c (by simp), ?_⟩
            simp only [hc, ite_true, List.mem_flatMap]
            refine ⟨l, hl, ?_⟩
            unfold adeps at hxl ⊢
            cases hla : l.atom with
            | fact a => rw [hla] at hxl; simpa using hxl
            | read b => rw [hla] at hxl; simpa using hxl
            | der e =>
                rw [hla] at hxl
                simp only [List.mem_cons] at hxl ⊢
                cases hxl with
                | inl h => exact Or.inl h
                | inr h => exact Or.inr (deps_sub_closure P Q hQ' m hm e x h)
          · simp [hc] at hx

/-- What a guard depends on is free of readings under the checked closure. -/
def guardRF (P : List (Clause F Rd D)) (g : List (Lit F Rd D)) : Bool :=
  (dependsOn P (g.map Lit.atom)).all (fun a => !a.isRead)

/-- Negated literals never depend on a reading (Restriction D's stratified negation, and the
    positivity half of Restriction N, since a reading is in its own dependency set). -/
def negOK (P : List (Clause F Rd D)) (g : List (Lit F Rd D)) : Bool :=
  g.all (fun l => !l.neg || guardRF P [l])

theorem guardRF_lit (P : List (Clause F Rd D)) (g : List (Lit F Rd D)) (h : guardRF P g = true) :
    ∀ l ∈ g, RF (adeps (deps P) l.atom) := by
  intro l hl x hx
  simp only [guardRF, dependsOn, List.all_eq_true, List.mem_flatMap, List.mem_map] at h
  have key : x ∈ adeps (clo P P.length) l.atom := by
    unfold adeps at hx ⊢
    cases hla : l.atom with
    | fact a => rw [hla] at hx; simpa using hx
    | read b => rw [hla] at hx; simpa using hx
    | der e =>
        rw [hla] at hx
        simp only [List.mem_cons] at hx ⊢
        cases hx with
        | inl h => exact Or.inl h
        | inr h => exact Or.inr (deps_sub_closure P P (fun _ h => h) _ (Nat.le_refl _) e x h)
  have := h x ⟨l.atom, ⟨l, hl, rfl⟩, key⟩
  simpa using this

/-- A guard that passes the check means the same under every reading. -/
theorem gEval_rf (φ : F → Bool) (ρ ρ' : Rd → Bool) (P : List (Clause F Rd D))
    (g : List (Lit F Rd D)) (h : guardRF P g = true) : gEval φ ρ P g = gEval φ ρ' P g := by
  unfold gEval
  apply all_congr'
  intro l hl
  have hrf := guardRF_lit P g h l hl
  unfold Lit.eval
  have ha : l.atom.eval φ ρ (evalProg φ ρ P) = l.atom.eval φ ρ' (evalProg φ ρ' P) := by
    cases hla : l.atom with
    | fact a => rfl
    | read b => have := hrf l.atom (by simp [adeps]); rw [hla] at this; simp [Atom.isRead] at this
    | der e =>
        simp only [Atom.eval]
        apply eval_reading_free φ ρ ρ' P e
        intro x hx; exact hrf x (by rw [hla]; simp [adeps, hx])
  rw [ha]


/-- The same, for a literal of the guard of any tail `Q` of the checked program. -/
theorem guardRF_lit' (P Q : List (Clause F Rd D)) (hQ : ∀ c ∈ Q, c ∈ P) (hn : Q.length ≤ P.length)
    (g : List (Lit F Rd D)) (h : guardRF P g = true) : ∀ l ∈ g, RF (adeps (deps Q) l.atom) := by
  intro l hl x hx
  simp only [guardRF, dependsOn, List.all_eq_true, List.mem_flatMap, List.mem_map] at h
  have key : x ∈ adeps (clo P P.length) l.atom := by
    unfold adeps at hx ⊢
    cases hla : l.atom with
    | fact a => rw [hla] at hx; simpa using hx
    | read b => rw [hla] at hx; simpa using hx
    | der e =>
        rw [hla] at hx
        simp only [List.mem_cons] at hx ⊢
        cases hx with
        | inl h => exact Or.inl h
        | inr h => exact Or.inr (deps_sub_closure P Q hQ _ hn e x h)
  have := h x ⟨l.atom, ⟨l, hl, rfl⟩, key⟩
  simpa using this

theorem atom_eval_rf (φ : F → Bool) (ρ ρ' : Rd → Bool) (Q : List (Clause F Rd D)) (a : Atom F Rd D)
    (h : RF (adeps (deps Q) a)) : a.eval φ ρ (evalProg φ ρ Q) = a.eval φ ρ' (evalProg φ ρ' Q) := by
  cases a with
  | fact _ => rfl
  | read b => have := h (.read b) (by simp [adeps]); simp [Atom.isRead] at this
  | der e =>
      simp only [Atom.eval]
      exact eval_reading_free φ ρ ρ' Q e (fun x hx => h x (by simp [adeps, hx]))

/-- With negation only on reading-free atoms, more readings make every derived atom only truer. -/
theorem evalProg_mono (φ : F → Bool) {ρ ρ' : Rd → Bool} (hle : ∀ b, ρ b = true → ρ' b = true)
    (P0 : List (Clause F Rd D)) (hneg : ∀ c ∈ P0, negOK P0 c.body = true) :
    ∀ Q : List (Clause F Rd D), (∀ c ∈ Q, c ∈ P0) → Q.length ≤ P0.length →
      ∀ d, evalProg φ ρ Q d = true → evalProg φ ρ' Q d = true
  | [], _, _, _, h => h
  | c :: Q, hQ, hn, d, h => by
      have hQ' : ∀ c' ∈ Q, c' ∈ P0 := fun c' h => hQ c' (by simp [h])
      have hn' : Q.length ≤ P0.length := by simp at hn; omega
      have ih := evalProg_mono φ hle P0 hneg Q hQ' hn'
      simp only [evalProg, Bool.or_eq_true, Bool.and_eq_true] at h ⊢
      cases h with
      | inl h => exact Or.inl (ih d h)
      | inr h =>
          refine Or.inr ⟨h.1, ?_⟩
          refine all_mono' c.body ?_ h.2
          intro l hl hlv
          have hc := hneg c (hQ c (by simp))
          simp only [negOK, List.all_eq_true] at hc
          have hcl := hc l hl
          unfold Lit.eval at hlv ⊢
          cases hneg' : l.neg
          · simp only [hneg', Bool.false_eq_true, ite_false] at hlv ⊢
            cases hla : l.atom with
            | fact a => rw [hla] at hlv; exact hlv
            | read b => rw [hla] at hlv; exact hle b hlv
            | der e => rw [hla] at hlv; exact ih e hlv
          · simp only [hneg', Bool.not_true, Bool.false_or] at hcl
            have hrf := guardRF_lit' P0 Q hQ' hn' [l] hcl l (by simp)
            simp only [hneg', ite_true] at hlv ⊢
            rw [← atom_eval_rf φ ρ ρ' Q l.atom hrf]; exact hlv

/-! ## 3. Rules and the check (core.py `check_restrictions`) -/

inductive Effect (Fm : Type) where
  | permit : Fm → Effect Fm
  | forbid : Effect Fm
  | cap : Fm → Effect Fm
  | boundary : Effect Fm
  | ask : Effect Fm
  | duty : Nat → Bool → Effect Fm    -- duty name, protective?
  deriving DecidableEq, Repr

/-- A rule. `lifts` (boundaries only) is a disjunction of conjunctions: core.py lifts a boundary
    when, for some use case `u` of the rule, `declared(r, u)` and a current `grant(s, u, …, owner)`
    are in the model. Here each disjunct is a positive conjunction of facts and TRUSTED derived
    atoms (`liftShape`); core.py reads those atoms from the model, where a clause may define them. -/
structure Rule (F Rd D A Fm : Type) where
  id : Nat
  anchors : List A
  eff : Effect Fm
  guard : List (Lit F Rd D)
  lifts : List (List (Lit F Rd D)) := []

/-- What a lifting condition may mention: positive facts and trusted derived atoms (core.py
    reads `declared` and `grant` from the model directly). `T` marks the trusted predicates:
    core.py's `TRUSTED_PREDS` (declared, grant, acts_for, holds, member, reaffirmed, …). -/
def liftShape (T : D → Bool) (b : List (Lit F Rd D)) : Bool :=
  b.all (fun l => !l.neg && match l.atom with
    | .fact _ => true
    | .der e => T e
    | .read _ => false)

def Rule.ok (T : D → Bool) (P : List (Clause F Rd D)) (r : Rule F Rd D A Fm) : Bool :=
  negOK P r.guard && match r.eff with
    | .permit _ => guardRF P r.guard
    | .forbid => guardRF P r.guard
    | .cap _ => guardRF P r.guard
    | .boundary => guardRF P r.guard && r.lifts.all (liftShape T)
    | .duty _ true => guardRF P r.guard        -- core.py PROTECTIVE_DUTIES may not read (D)
    | .duty _ false => true
    | .ask => true

/-- Finding A, fixed in core.py on 25 November: a clause whose head is trusted may not depend on
    a reading (`check_restrictions`, last loop). -/
def trustedOK (T : D → Bool) (P : List (Clause F Rd D)) : Bool :=
  P.all (fun c => !T c.head || guardRF P c.body)

/-- Restriction N over derived predicates: every rule passes, no clause negates anything that
    depends on a reading, and no trusted predicate is defined from a reading. -/
def checkN (T : D → Bool) (P : List (Clause F Rd D)) (R : List (Rule F Rd D A Fm)) : Bool :=
  R.all (Rule.ok T P) && P.all (fun c => negOK P c.body) && trustedOK T P

/-- The check before the fixes of 25 November: lifts and trusted clauses are not checked. -/
def Rule.okOld (P : List (Clause F Rd D)) (r : Rule F Rd D A Fm) : Bool :=
  negOK P r.guard && match r.eff with
    | .permit _ => guardRF P r.guard
    | .forbid => guardRF P r.guard
    | .cap _ => guardRF P r.guard
    | .boundary => guardRF P r.guard
    | _ => true
def checkOld (P : List (Clause F Rd D)) (R : List (Rule F Rd D A Fm)) : Bool :=
  R.all (Rule.okOld P) && P.all (fun c => negOK P c.body)

def isPermit (r : Rule F Rd D A Fm) : Bool := match r.eff with | .permit _ => true | _ => false
def isForbid (r : Rule F Rd D A Fm) : Bool := match r.eff with | .forbid => true | _ => false
def isCap (r : Rule F Rd D A Fm) : Bool := match r.eff with | .cap _ => true | _ => false
def isBoundary (r : Rule F Rd D A Fm) : Bool := match r.eff with | .boundary => true | _ => false
def isAsk (r : Rule F Rd D A Fm) : Bool := match r.eff with | .ask => true | _ => false
def isDuty (r : Rule F Rd D A Fm) : Bool := match r.eff with | .duty _ _ => true | _ => false
def isProt (r : Rule F Rd D A Fm) : Bool := match r.eff with | .duty _ p => p | _ => false
def dutyName (r : Rule F Rd D A Fm) : Nat := match r.eff with | .duty n _ => n | _ => 0
/-- core.py's `fact_asks` (finding F1): an ask whose guard depends on no reading. -/
def isFactAsk (P : List (Clause F Rd D)) (r : Rule F Rd D A Fm) : Bool := isAsk r && guardRF P r.guard

/-- The kinds whose guard the check requires reading-free. -/
def guarded (r : Rule F Rd D A Fm) : Bool :=
  isPermit r || isForbid r || isCap r || isBoundary r || isProt r

theorem ok_guard {T : D → Bool} (P : List (Clause F Rd D)) (r : Rule F Rd D A Fm) (h : r.ok T P = true)
    (hk : guarded r = true) : guardRF P r.guard = true := by
  unfold Rule.ok at h
  unfold guarded isPermit isForbid isCap isBoundary isProt at hk
  revert h hk
  cases r.eff with
  | duty n p => cases p <;> simp_all
  | _ => simp_all

theorem ok_lifts {T : D → Bool} (P : List (Clause F Rd D)) (r : Rule F Rd D A Fm) (h : r.ok T P = true)
    (hk : isBoundary r = true) : ∀ b ∈ r.lifts, liftShape T b = true := by
  unfold Rule.ok at h
  unfold isBoundary at hk
  revert h hk
  cases r.eff <;> simp_all [List.all_eq_true]

theorem ok_neg {T : D → Bool} (P : List (Clause F Rd D)) (r : Rule F Rd D A Fm) (h : r.ok T P = true) :
    negOK P r.guard = true := by
  unfold Rule.ok at h; simp only [Bool.and_eq_true] at h; exact h.1

theorem checkN_rules {T : D → Bool} {P : List (Clause F Rd D)} {R : List (Rule F Rd D A Fm)}
    (h : checkN T P R = true) : ∀ r ∈ R, r.ok T P = true := by
  simp only [checkN, Bool.and_eq_true, List.all_eq_true] at h; exact h.1.1

theorem checkN_clauses {T : D → Bool} {P : List (Clause F Rd D)} {R : List (Rule F Rd D A Fm)}
    (h : checkN T P R = true) : ∀ c ∈ P, negOK P c.body = true := by
  simp only [checkN, Bool.and_eq_true, List.all_eq_true] at h; exact h.1.2

theorem checkN_trusted {T : D → Bool} {P : List (Clause F Rd D)} {R : List (Rule F Rd D A Fm)}
    (h : checkN T P R = true) : ∀ c ∈ P, T c.head = true → guardRF P c.body = true := by
  simp only [checkN, trustedOK, Bool.and_eq_true, List.all_eq_true, Bool.or_eq_true] at h
  intro c hc ht
  cases h.2 c hc with
  | inl h' => simp [ht] at h'
  | inr h' => exact h'

/-- **Trusted predicates never depend on a reading** (finding A). If every clause defining a
    trusted predicate passes the check, a trusted predicate's dependencies hold no reading, in
    every tail of the program. -/
theorem trusted_deps_rf (T : D → Bool) (P : List (Clause F Rd D))
    (hT : ∀ c ∈ P, T c.head = true → guardRF P c.body = true) :
    ∀ Q : List (Clause F Rd D), (∀ c ∈ Q, c ∈ P) → Q.length ≤ P.length →
      ∀ d, T d = true → RF (deps Q d)
  | [], _, _, _, _ => by intro x hx; simp [deps] at hx
  | c :: Q, hQ, hn, d, hd => by
      intro x hx
      have hQ' : ∀ c' ∈ Q, c' ∈ P := fun c' h => hQ c' (by simp [h])
      have hn' : Q.length ≤ P.length := by simp at hn; omega
      simp only [deps, List.mem_append] at hx
      cases hx with
      | inr hx => exact trusted_deps_rf T P hT Q hQ' hn' d hd x hx
      | inl hx =>
          by_cases hc : c.head = d
          · simp only [hc, ite_true, List.mem_flatMap] at hx
            obtain ⟨l, hl, hxl⟩ := hx
            have hg := hT c (hQ c (by simp)) (by rw [hc]; exact hd)
            exact guardRF_lit' P Q hQ' hn' c.body hg l hl x hxl
          · simp [hc] at hx

/-- A lifting condition of the allowed shape means the same under every reading. -/
theorem lift_rf (φ : F → Bool) (ρ ρ' : Rd → Bool) (T : D → Bool) (P : List (Clause F Rd D))
    (hT : ∀ c ∈ P, T c.head = true → guardRF P c.body = true) (b : List (Lit F Rd D))
    (hb : liftShape T b = true) : gEval φ ρ P b = gEval φ ρ' P b := by
  unfold gEval
  apply all_congr'
  intro l hl
  simp only [liftShape, List.all_eq_true, Bool.and_eq_true] at hb
  have h := (hb l hl).2
  unfold Lit.eval
  rw [atom_eval_rf φ ρ ρ' P l.atom ?_]
  revert h
  generalize l.atom = a
  intro h x hx
  cases a with
  | fact _ => simp [adeps] at hx; subst hx; rfl
  | read _ => simp at h
  | der e =>
      simp only [adeps, List.mem_cons] at hx
      cases hx with
      | inl hx => subst hx; rfl
      | inr hx => exact trusted_deps_rf T P hT P (fun _ h => h) (Nat.le_refl _) e h x hx

/-! ## 4. The decision of one side (core.py `_one_side`), with the canonical choice -/

def touches (m : A → Bool) (r : Rule F Rd D A Fm) : Bool := r.anchors.all m

/-- The touching rules of one kind whose guard holds. -/
def appK (k : Rule F Rd D A Fm → Bool) (m : A → Bool) (φ : F → Bool) (ρ : Rd → Bool)
    (P : List (Clause F Rd D)) (R : List (Rule F Rd D A Fm)) : List (Rule F Rd D A Fm) :=
  R.filter (fun r => touches m r && k r && gEval φ ρ P r.guard)

/-- A finite lattice of forms, with a rank that orders forms totally: core.py's key
    (height, form name) is `rank = 8 · height + alphabetical index` for the seven forms. -/
structure FormLat (Fm : Type) where
  meet : Fm → Fm → Fm
  top : Fm
  rank : Fm → Nat
  rank_inj : ∀ a b, rank a = rank b → a = b
  meet_comm : ∀ a b, meet a b = meet b a
  meet_assoc : ∀ a b c, meet (meet a b) c = meet a (meet b c)

namespace FormLat
variable (L : FormLat Fm)

/-- The canonical key (height, form name, rule id), lexicographic. -/
def lt (a b : Fm × Nat) : Bool :=
  decide (L.rank a.1 < L.rank b.1) || (decide (L.rank a.1 = L.rank b.1) && decide (a.2 < b.2))

def pick (a b : Fm × Nat) : Fm × Nat := if L.lt a b then b else a

/-- `max(offers, key=…)`: Python's `max` keeps the first of equal keys; the key is injective on
    (form, rule id) pairs, so equal keys mean equal pairs. -/
def choose : List (Fm × Nat) → Option (Fm × Nat)
  | [] => none
  | o :: os => some (match choose os with
      | none => o
      | some b => L.pick o b)

theorem lt_iff (a b : Fm × Nat) :
    L.lt a b = true ↔ L.rank a.1 < L.rank b.1 ∨ (L.rank a.1 = L.rank b.1 ∧ a.2 < b.2) := by
  simp [lt]

theorem lt_asymm (a b : Fm × Nat) (h : L.lt a b = true) : ¬ L.lt b a = true := by
  rw [lt_iff] at h ⊢; omega

theorem lt_trans (a b c : Fm × Nat) (h1 : L.lt a b = true) (h2 : L.lt b c = true) : L.lt a c = true := by
  rw [lt_iff] at h1 h2 ⊢; omega

theorem lt_total (a b : Fm × Nat) (h : a ≠ b) : L.lt a b = true ∨ L.lt b a = true := by
  rw [lt_iff, lt_iff]
  by_cases hr : L.rank a.1 = L.rank b.1
  · have h1 : a.1 = b.1 := L.rank_inj _ _ hr
    have h2 : a.2 ≠ b.2 := fun h2 => h (Prod.ext h1 h2)
    omega
  · omega

theorem choose_none (l : List (Fm × Nat)) : L.choose l = none → l = [] := by
  cases l with
  | nil => intro; rfl
  | cons _ _ => simp [choose]

theorem choose_mem : ∀ (l : List (Fm × Nat)) (x : Fm × Nat), L.choose l = some x → x ∈ l
  | [], _, h => by simp [choose] at h
  | o :: os, x, h => by
      simp only [choose, Option.some.injEq] at h
      cases hc : L.choose os with
      | none => rw [hc] at h; simp [← h]
      | some b =>
          rw [hc] at h
          simp only [pick] at h
          split at h
          · have := choose_mem os b hc; subst h; simp [this]
          · subst h; simp

/-- The chosen offer is maximal: no offer has a larger key. -/
theorem choose_max : ∀ (l : List (Fm × Nat)) (x : Fm × Nat), L.choose l = some x →
    ∀ y ∈ l, ¬ L.lt x y = true
  | [], _, h => by simp [choose] at h
  | o :: os, x, h => by
      simp only [choose, Option.some.injEq] at h
      cases hc : L.choose os with
      | none =>
          rw [hc] at h
          have : os = [] := L.choose_none os hc
          subst this; subst h
          intro y hy; simp at hy; subst hy
          intro hl; exact L.lt_asymm _ _ hl hl
      | some b =>
          rw [hc] at h
          have ih := choose_max os b hc
          simp only [pick] at h
          split at h
          · rename_i hob
            subst h
            intro y hy
            simp only [List.mem_cons] at hy
            cases hy with
            | inl hy => subst hy; exact L.lt_asymm _ _ hob
            | inr hy => exact ih y hy
          · rename_i hob
            subst h
            intro y hy
            simp only [List.mem_cons] at hy
            cases hy with
            | inl hy => subst hy; intro hl; exact L.lt_asymm _ _ hl hl
            | inr hy =>
                intro hxy
                have hby := ih y hy
                by_cases hyb : y = b
                · subst hyb; exact hob hxy
                · cases L.lt_total y b hyb with
                  | inl hyb' => exact hob (L.lt_trans _ _ _ hxy hyb')
                  | inr hby' => exact hby hby'

/-- **The canonical choice depends only on the SET of offers**: not on their order, nor on
    repetition. This is what the tie-break (form name, rule id) buys. -/
theorem choose_congr (l l' : List (Fm × Nat)) (h : ∀ y, y ∈ l ↔ y ∈ l') : L.choose l = L.choose l' := by
  cases h1 : L.choose l with
  | none =>
      have := L.choose_none l h1; subst this
      cases h2 : L.choose l' with
      | none => rfl
      | some x' => have := (h x').2 (L.choose_mem l' x' h2); simp at this
  | some x =>
      cases h2 : L.choose l' with
      | none =>
          have := L.choose_none l' h2; subst this
          have := (h x).1 (L.choose_mem l x h1); simp at this
      | some x' =>
          have hx : x ∈ l' := (h x).1 (L.choose_mem l x h1)
          have hx' : x' ∈ l := (h x').2 (L.choose_mem l' x' h2)
          have m1 := L.choose_max l x h1 x' hx'
          have m2 := L.choose_max l' x' h2 x hx
          by_cases he : x = x'
          · rw [he]
          · cases L.lt_total x x' he with
            | inl h3 => exact absurd h3 m1
            | inr h3 => exact absurd h3 m2

theorem foldr_perm {l l' : List Fm} (h : l.Perm l') (t : Fm) : l.foldr L.meet t = l'.foldr L.meet t := by
  induction h with
  | nil => rfl
  | cons x _ ih => simp only [List.foldr, ih]
  | swap x y l => simp only [List.foldr]; rw [← L.meet_assoc, L.meet_comm y x, L.meet_assoc]
  | trans _ _ ih1 ih2 => exact ih1.trans ih2

end FormLat

inductive Decision (Fm : Type) where
  | deny
  | ask
  | allow (f : Fm)
  deriving DecidableEq, Repr

/-- What leaves the system: a form, or nothing. -/
def Decision.rel : Decision Fm → Option Fm
  | .allow f => some f
  | _ => none

def capForm (L : FormLat Fm) (r : Rule F Rd D A Fm) : Fm := match r.eff with | .cap f => f | _ => L.top
def pForm (L : FormLat Fm) (r : Rule F Rd D A Fm) : Fm := match r.eff with | .permit f => f | _ => L.top

def lifted (φ : F → Bool) (ρ : Rd → Bool) (P : List (Clause F Rd D)) (r : Rule F Rd D A Fm) : Bool :=
  r.lifts.any (gEval φ ρ P)

def unlifted (m : A → Bool) (φ : F → Bool) (ρ : Rd → Bool) (P : List (Clause F Rd D))
    (R : List (Rule F Rd D A Fm)) : List (Rule F Rd D A Fm) :=
  (appK isBoundary m φ ρ P R).filter (fun r => !lifted φ ρ P r)

/-- Decision 5: touching permits whose condition fails. -/
def failed (m : A → Bool) (φ : F → Bool) (ρ : Rd → Bool) (P : List (Clause F Rd D))
    (R : List (Rule F Rd D A Fm)) : List (Rule F Rd D A Fm) :=
  R.filter (fun r => touches m r && isPermit r && !gEval φ ρ P r.guard)

def capped (L : FormLat Fm) (m : A → Bool) (φ : F → Bool) (ρ : Rd → Bool) (P : List (Clause F Rd D))
    (R : List (Rule F Rd D A Fm)) : Fm :=
  ((appK isCap m φ ρ P R).map (capForm L)).foldr L.meet L.top

/-- Each applicable permit offers meet(asked, permit, caps), tagged with its rule id. -/
def offers (L : FormLat Fm) (m : A → Bool) (φ : F → Bool) (ρ : Rd → Bool) (P : List (Clause F Rd D))
    (R : List (Rule F Rd D A Fm)) (q : Fm) : List (Fm × Nat) :=
  (appK isPermit m φ ρ P R).map (fun r => (L.meet q (L.meet (pForm L r) (capped L m φ ρ P R)), r.id))

/-- core.py `_tail`: a failed permit condition (decision 5), then the default. -/
def tail (L : FormLat Fm) (fails : Bool) (dflt : Decision Fm) (cap q : Fm) : Decision Fm :=
  if fails then .deny
  else match dflt with
    | .allow f => .allow (L.meet q (L.meet f cap))
    | d => d

/-- After protection, as core.py does it since 25 November (finding B): the chosen offer; else
    ask if a fact-only ask applies; else, if only reading-guarded asks apply, the tail's allow
    when it is useful (`useful f` is `min_useful ⊑ f`), otherwise ask; else the tail. -/
def finish (L : FormLat Fm) (useful : Fm → Bool) (o : Option (Fm × Nat)) (factAsks asks fails : Bool)
    (dflt : Decision Fm) (cap q : Fm) : Decision Fm :=
  match o with
  | some o => .allow o.1
  | none =>
      if factAsks then .ask
      else if asks then
        (match tail L fails dflt cap q with
          | .allow f => if useful f then .allow f else .ask
          | _ => .ask)
      else tail L fails dflt cap q

/-- core.py `_one_side`: forbid, then boundaries (ask if a fact-only ask applies, F1), then the
    canonical choice among offers, then asks, then the tail. -/
def decideSide (L : FormLat Fm) (useful : Fm → Bool) (m : A → Bool) (φ : F → Bool) (ρ : Rd → Bool)
    (P : List (Clause F Rd D)) (R : List (Rule F Rd D A Fm)) (q : Fm) (dflt : Decision Fm) :
    Decision Fm :=
  if !(appK isForbid m φ ρ P R).isEmpty then .deny
  else if !(unlifted m φ ρ P R).isEmpty then
    (if (appK (isFactAsk P) m φ ρ P R).isEmpty then .deny else .ask)
  else finish L useful (L.choose (offers L m φ ρ P R q)) (!(appK (isFactAsk P) m φ ρ P R).isEmpty)
    (!(appK isAsk m φ ρ P R).isEmpty) (!(failed m φ ρ P R).isEmpty) dflt (capped L m φ ρ P R) q

/-- The semantics before 25 November: any applicable ask, even one that reads, wins over the tail. -/
def decideSideOld (L : FormLat Fm) (m : A → Bool) (φ : F → Bool) (ρ : Rd → Bool)
    (P : List (Clause F Rd D)) (R : List (Rule F Rd D A Fm)) (q : Fm) (dflt : Decision Fm) :
    Decision Fm :=
  if !(appK isForbid m φ ρ P R).isEmpty then .deny
  else if !(unlifted m φ ρ P R).isEmpty then
    (if (appK (isFactAsk P) m φ ρ P R).isEmpty then .deny else .ask)
  else match L.choose (offers L m φ ρ P R q) with
    | some o => .allow o.1
    | none => if !(appK isAsk m φ ρ P R).isEmpty then .ask
              else tail L (!(failed m φ ρ P R).isEmpty) dflt (capped L m φ ρ P R) q

/-- What finally leaves: an allow at a useful form (core.py `_decide_inner` denies an allow
    below `min_useful`). -/
def released (useful : Fm → Bool) : Decision Fm → Option Fm
  | .allow f => if useful f then some f else none
  | _ => none

/-- Owed duties, and the protective ones among them (attached to every allow, §2.7). -/
def owed (m : A → Bool) (φ : F → Bool) (ρ : Rd → Bool) (P : List (Clause F Rd D))
    (R : List (Rule F Rd D A Fm)) : List Nat := (appK isDuty m φ ρ P R).map dutyName
def protOwed (m : A → Bool) (φ : F → Bool) (ρ : Rd → Bool) (P : List (Clause F Rd D))
    (R : List (Rule F Rd D A Fm)) : List Nat := (appK isProt m φ ρ P R).map dutyName

/-! ## 5. Readings under the check -/

section Readings
variable (L : FormLat Fm) (useful : Fm → Bool) (m : A → Bool) (φ : F → Bool) (ρ ρ' : Rd → Bool)
  (P : List (Clause F Rd D)) (R : List (Rule F Rd D A Fm)) {T : D → Bool}

theorem appK_rf (k : Rule F Rd D A Fm → Bool) (hk : ∀ r ∈ R, k r = true → guardRF P r.guard = true) :
    appK k m φ ρ P R = appK k m φ ρ' P R := by
  unfold appK
  apply filter_congr'
  intro r hr
  by_cases h : k r = true
  · rw [gEval_rf φ ρ ρ' P _ (hk r hr h)]
  · simp only [Bool.not_eq_true] at h; simp [h]

theorem appK_rf_guarded (hR : checkN T P R = true) (k : Rule F Rd D A Fm → Bool)
    (hk : ∀ r, k r = true → guarded r = true) : appK k m φ ρ P R = appK k m φ ρ' P R :=
  appK_rf m φ ρ ρ' P R k (fun r hr h => ok_guard P r (checkN_rules hR r hr) (hk r h))

theorem forbids_rf (hR : checkN T P R = true) : appK isForbid m φ ρ P R = appK isForbid m φ ρ' P R :=
  appK_rf_guarded m φ ρ ρ' P R hR _ (fun r h => by simp [guarded, h])
theorem permits_rf (hR : checkN T P R = true) : appK isPermit m φ ρ P R = appK isPermit m φ ρ' P R :=
  appK_rf_guarded m φ ρ ρ' P R hR _ (fun r h => by simp [guarded, h])
theorem caps_rf (hR : checkN T P R = true) : appK isCap m φ ρ P R = appK isCap m φ ρ' P R :=
  appK_rf_guarded m φ ρ ρ' P R hR _ (fun r h => by simp [guarded, h])
theorem prot_rf (hR : checkN T P R = true) : appK isProt m φ ρ P R = appK isProt m φ ρ' P R :=
  appK_rf_guarded m φ ρ ρ' P R hR _ (fun r h => by simp [guarded, h])
theorem factasks_rf : appK (isFactAsk P) m φ ρ P R = appK (isFactAsk P) m φ ρ' P R :=
  appK_rf m φ ρ ρ' P R _ (fun r _ h => by simp only [isFactAsk, Bool.and_eq_true] at h; exact h.2)

theorem unlifted_rf (hR : checkN T P R = true) : unlifted m φ ρ P R = unlifted m φ ρ' P R := by
  unfold unlifted
  rw [appK_rf_guarded m φ ρ ρ' P R hR isBoundary (fun r h => by simp [guarded, h])]
  apply filter_congr'
  intro r hr
  have hmem : r ∈ R := (List.mem_filter.1 hr).1
  have hb : isBoundary r = true := by
    simp only [appK, List.mem_filter, Bool.and_eq_true] at hr; exact hr.2.1.2
  have hl := ok_lifts P r (checkN_rules hR r hmem) hb
  unfold lifted
  rw [any_congr' r.lifts (fun b hb' => lift_rf φ ρ ρ' T P (checkN_trusted hR) b (hl b hb'))]

theorem failed_rf (hR : checkN T P R = true) : failed m φ ρ P R = failed m φ ρ' P R := by
  unfold failed
  apply filter_congr'
  intro r hr
  by_cases h : isPermit r = true
  · rw [gEval_rf φ ρ ρ' P _ (ok_guard P r (checkN_rules hR r hr) (by simp [guarded, h]))]
  · simp only [Bool.not_eq_true] at h; simp [h]

theorem capped_rf (hR : checkN T P R = true) : capped L m φ ρ P R = capped L m φ ρ' P R := by
  unfold capped; rw [caps_rf m φ ρ ρ' P R hR]

theorem offers_rf (hR : checkN T P R = true) (q : Fm) : offers L m φ ρ P R q = offers L m φ ρ' P R q := by
  unfold offers; rw [permits_rf m φ ρ ρ' P R hR, capped_rf L m φ ρ ρ' P R hR]

/-- **The chosen offer does not depend on readings.** For every rule set that passes the check,
    the offer chosen by (height, form name, rule id), form and rule, is the same under every
    assignment of readings. -/
theorem chosen_offer_reading_free (hR : checkN T P R = true) (q : Fm) :
    L.choose (offers L m φ ρ P R q) = L.choose (offers L m φ ρ' P R q) := by
  rw [offers_rf L m φ ρ ρ' P R hR]

/-- Everything but the reading-guarded ask rules is the same under any two readings. -/
theorem decide_shape (hR : checkN T P R = true) (q : Fm) (dflt : Decision Fm) :
    decideSide L useful m φ ρ P R q dflt =
      (if !(appK isForbid m φ ρ' P R).isEmpty then .deny
       else if !(unlifted m φ ρ' P R).isEmpty then
         (if (appK (isFactAsk P) m φ ρ' P R).isEmpty then .deny else .ask)
       else finish L useful (L.choose (offers L m φ ρ' P R q)) (!(appK (isFactAsk P) m φ ρ' P R).isEmpty)
         (!(appK isAsk m φ ρ P R).isEmpty) (!(failed m φ ρ' P R).isEmpty) dflt (capped L m φ ρ' P R) q) := by
  unfold decideSide
  rw [forbids_rf m φ ρ ρ' P R hR, unlifted_rf m φ ρ ρ' P R hR, factasks_rf m φ ρ ρ' P R,
    offers_rf L m φ ρ ρ' P R hR, failed_rf m φ ρ ρ' P R hR, capped_rf L m φ ρ ρ' P R hR]

/-- Whether a reading-guarded ask applies does not change what is finally released. -/
theorem finish_tail_released (t : Decision Fm) (fa a1 a2 : Bool) :
    released useful (if fa then .ask else if a1 then
        (match t with | .allow f => if useful f then .allow f else .ask | _ => .ask) else t) =
    released useful (if fa then .ask else if a2 then
        (match t with | .allow f => if useful f then .allow f else .ask | _ => .ask) else t) := by
  cases t with
  | deny => cases fa <;> cases a1 <;> cases a2 <;> rfl
  | ask => cases fa <;> cases a1 <;> cases a2 <;> rfl
  | allow f => cases fa <;> cases a1 <;> cases a2 <;> cases hu : useful f <;> simp [released, hu]

/-- **Headline: Restriction N over derived predicates, for ANY default.** For every rule set and
    program that pass the check, what is finally released, including the ONE form chosen among
    the offers, is the same under every assignment of readings. -/
theorem release_reading_free_of_check (hR : checkN T P R = true) (q : Fm) (dflt : Decision Fm) :
    released useful (decideSide L useful m φ ρ P R q dflt) =
      released useful (decideSide L useful m φ ρ' P R q dflt) := by
  rw [decide_shape L useful m φ ρ ρ' P R hR q dflt, decide_shape L useful m φ ρ' ρ' P R hR q dflt]
  split
  · rfl
  · split
    · rfl
    · unfold finish
      split
      · rfl
      · exact finish_tail_released useful _ _ _ _

/-- **A reading never opens anything and never changes the form** (before `min_useful`): if
    something is allowed under one assignment of readings, then under any other the same form is
    allowed, or the verdict is a question (`ask`). -/
theorem reading_never_opens (hR : checkN T P R = true) (q : Fm) (dflt : Decision Fm) (f : Fm)
    (h : (decideSide L useful m φ ρ P R q dflt).rel = some f) :
    (decideSide L useful m φ ρ' P R q dflt).rel = some f ∨ decideSide L useful m φ ρ' P R q dflt = .ask := by
  rw [decide_shape L useful m φ ρ ρ' P R hR q dflt] at h
  rw [decide_shape L useful m φ ρ' ρ' P R hR q dflt]
  revert h
  split
  · simp [Decision.rel]
  · split
    · split <;> simp [Decision.rel]
    · unfold finish
      split
      · exact fun h => Or.inl h
      · generalize tail L (!(failed m φ ρ' P R).isEmpty) dflt (capped L m φ ρ' P R) q = t
        cases (appK (isFactAsk P) m φ ρ' P R).isEmpty <;> cases (appK isAsk m φ ρ P R).isEmpty <;>
          cases (appK isAsk m φ ρ' P R).isEmpty <;> cases t <;> simp only [Bool.not_true, Bool.not_false,
            ite_true, ite_false, Bool.false_eq_true] <;> (try split) <;> (try split) <;> simp_all [Decision.rel]

/-- Non-interference: once a forbid applies under the facts, every reading gives deny. -/
theorem noninterference_of_check (hR : checkN T P R = true) (q : Fm) (dflt : Decision Fm)
    (h : (appK isForbid m φ ρ P R).isEmpty = false) : decideSide L useful m φ ρ' P R q dflt = .deny := by
  unfold decideSide
  rw [← forbids_rf m φ ρ ρ' P R hR, h]; rfl

/-- **Protective duties never depend on a reading.** -/
theorem protective_duties_reading_free (hR : checkN T P R = true) :
    protOwed m φ ρ P R = protOwed m φ ρ' P R := by
  unfold protOwed; rw [prot_rf m φ ρ ρ' P R hR]

/-- More readings only add duties, never remove one (the derived-predicate twin of Core's `owed_mono`). -/
theorem owed_mono (hR : checkN T P R = true) (hle : ∀ b, ρ b = true → ρ' b = true) :
    ∀ n ∈ owed m φ ρ P R, n ∈ owed m φ ρ' P R := by
  intro n hn
  simp only [owed, appK, List.mem_map, List.mem_filter, Bool.and_eq_true] at hn ⊢
  obtain ⟨r, ⟨hr, ⟨ht, hk⟩, hg⟩, rfl⟩ := hn
  refine ⟨r, ⟨hr, ⟨ht, hk⟩, ?_⟩, rfl⟩
  have hneg := ok_neg P r (checkN_rules hR r hr)
  unfold gEval at hg ⊢
  refine all_mono' r.guard ?_ hg
  intro l hl hlv
  simp only [negOK, List.all_eq_true] at hneg
  have hcl := hneg l hl
  unfold Lit.eval at hlv ⊢
  cases hn' : l.neg
  · simp only [hn', Bool.false_eq_true, ite_false] at hlv ⊢
    cases hla : l.atom with
    | fact a => rw [hla] at hlv; exact hlv
    | read b => rw [hla] at hlv; exact hle b hlv
    | der e =>
        rw [hla] at hlv
        exact evalProg_mono φ hle P (checkN_clauses hR) P (fun _ h => h) (Nat.le_refl _) e hlv
  · simp only [hn', Bool.not_true, Bool.false_or] at hcl
    have hrf := guardRF_lit' P P (fun _ h => h) (Nat.le_refl _) [l] hcl l (by simp)
    simp only [hn', ite_true] at hlv ⊢
    rw [← atom_eval_rf φ ρ ρ' P l.atom hrf]; exact hlv

end Readings

/-! ## 6. Rule order does not matter (thanks to the tie-break) -/

theorem perm_isEmpty {α : Type} {l l' : List α} (h : l.Perm l') : l.isEmpty = l'.isEmpty := by
  have := h.length_eq
  cases l <;> cases l' <;> simp_all

/-- **The decision is independent of rule order.** Any permutation of the rule list gives the
    same decision, including the same chosen form. -/
theorem decide_perm (L : FormLat Fm) (useful : Fm → Bool) (m : A → Bool) (φ : F → Bool) (ρ : Rd → Bool)
    (P : List (Clause F Rd D)) {R R' : List (Rule F Rd D A Fm)} (h : R.Perm R') (q : Fm)
    (dflt : Decision Fm) : decideSide L useful m φ ρ P R q dflt = decideSide L useful m φ ρ P R' q dflt := by
  have hk : ∀ k : Rule F Rd D A Fm → Bool, (appK k m φ ρ P R).Perm (appK k m φ ρ P R') :=
    fun k => h.filter _
  have hcap : capped L m φ ρ P R = capped L m φ ρ P R' :=
    L.foldr_perm ((hk isCap).map _) L.top
  have hoff : L.choose (offers L m φ ρ P R q) = L.choose (offers L m φ ρ P R' q) := by
    apply L.choose_congr
    intro y
    unfold offers
    rw [hcap]
    exact ((hk isPermit).map _).mem_iff
  have hunl : (unlifted m φ ρ P R).isEmpty = (unlifted m φ ρ P R').isEmpty :=
    perm_isEmpty ((hk isBoundary).filter _)
  have hfail : (failed m φ ρ P R).isEmpty = (failed m φ ρ P R').isEmpty := perm_isEmpty (h.filter _)
  unfold decideSide
  rw [perm_isEmpty (hk isForbid), hunl, perm_isEmpty (hk (isFactAsk P)), hoff,
    perm_isEmpty (hk isAsk), hfail, hcap]

/-! ## 7. The seven forms of the language -/

inductive Form7 where
  | metadata | count | aggregated | anonymised | pseudonymised | summarised | raw
  deriving DecidableEq, Repr

namespace Form7

/-- core.py `FORM_LE`: metadata ⊑ count ⊑ aggregated ⊑ anonymised ⊑ pseudonymised ⊑ raw,
    aggregated ⊑ summarised ⊑ raw. -/
def le : Form7 → Form7 → Bool
  | metadata, _ => true
  | count, b => match b with | metadata => false | _ => true
  | aggregated, b => match b with | metadata | count => false | _ => true
  | anonymised, b => match b with | anonymised | pseudonymised | raw => true | _ => false
  | pseudonymised, b => match b with | pseudonymised | raw => true | _ => false
  | summarised, b => match b with | summarised | raw => true | _ => false
  | raw, b => match b with | raw => true | _ => false

/-- The only incomparable pairs are a row form against `summarised`; their meet is aggregated. -/
def meet (a b : Form7) : Form7 := if le a b then a else if le b a then b else aggregated

/-- core.py `f_height`: the number of forms below. -/
def height : Form7 → Nat
  | metadata => 1 | count => 2 | aggregated => 3 | anonymised => 4
  | pseudonymised => 5 | summarised => 4 | raw => 7

/-- Position of the form's name in alphabetical order (Python compares the names as strings). -/
def alpha : Form7 → Nat
  | aggregated => 0 | anonymised => 1 | count => 2 | metadata => 3
  | pseudonymised => 4 | raw => 5 | summarised => 6

def rank (f : Form7) : Nat := 8 * height f + alpha f

theorem meet_glb : ∀ a b c : Form7, le (meet a b) a = true ∧ le (meet a b) b = true ∧
    (le c a = true → le c b = true → le c (meet a b) = true) := by
  intro a b c; cases a <;> cases b <;> cases c <;> decide

theorem meet_comm' (a b : Form7) : meet a b = meet b a := by cases a <;> cases b <;> rfl
theorem meet_assoc' (a b c : Form7) : meet (meet a b) c = meet a (meet b c) := by
  cases a <;> cases b <;> cases c <;> rfl
theorem rank_inj' (a b : Form7) (h : rank a = rank b) : a = b := by
  cases a <;> cases b <;> simp_all [rank, height, alpha]

end Form7

def Lat7 : FormLat Form7 :=
  { meet := Form7.meet, top := .raw, rank := Form7.rank, rank_inj := Form7.rank_inj',
    meet_comm := Form7.meet_comm', meet_assoc := Form7.meet_assoc' }

/-! ## 8. Counterexamples (all by `decide`) -/

abbrev R7 := Rule Unit Unit Nat Unit Form7
abbrev P7 := List (Clause Unit Unit Nat)

def noFacts : Unit → Bool := fun _ => false
def allAnchors : Unit → Bool := fun _ => true
def readYes : Unit → Bool := fun _ => true
def readNo : Unit → Bool := fun _ => false
def useAll : Form7 → Bool := fun _ => true
def noTrust : Nat → Bool := fun _ => false

/-- The rule before the review (SEMANTICS §2.3 still says so): the tallest offer, the first in
    the rule book on a tie. -/
def chooseFirst : List (Form7 × Nat) → Option (Form7 × Nat)
  | [] => none
  | o :: os => some (match chooseFirst os with
      | none => o
      | some b => if Form7.height o.1 < Form7.height b.1 then b else o)

def pAnon : R7 := { id := 1, anchors := [], eff := .permit .anonymised, guard := [] }
def pSumm : R7 := { id := 2, anchors := [], eff := .permit .summarised, guard := [] }

/-- **Without the tie-break the form depends on rule order**: two permits whose offers have the
    same height (anonymised rows, a summary) release anonymised in one order and summarised in the
    other. With the canonical key both orders release summarised. -/
theorem first_max_depends_on_order :
    (chooseFirst (offers Lat7 allAnchors noFacts readNo ([] : P7) [pAnon, pSumm] .raw)).map Prod.fst
      = some .anonymised ∧
    (chooseFirst (offers Lat7 allAnchors noFacts readNo ([] : P7) [pSumm, pAnon] .raw)).map Prod.fst
      = some .summarised ∧
    decideSide Lat7 useAll allAnchors noFacts readNo ([] : P7) [pAnon, pSumm] .raw .deny = .allow .summarised ∧
    decideSide Lat7 useAll allAnchors noFacts readNo ([] : P7) [pSumm, pAnon] .raw .deny = .allow .summarised := by
  decide

/-- A derived predicate `d0 :- reading`. -/
def hideRead : P7 := [{ head := 0, body := [{ atom := .read () }] }]
def pViaDerived : R7 := { id := 1, anchors := [], eff := .permit .raw, guard := [{ atom := .der 0 }] }

/-- The check of `Strict.lean`, applied to literal guards: it looks only at the guard's own atoms. -/
def shallowOK (r : R7) : Bool := !guarded r || r.guard.all (fun l => !l.atom.isRead)

/-- **The dependency check is needed for derived predicates.** A permit guarded by a derived
    predicate that hides a reading passes a check on the guard's own atoms, fails `checkN`, and
    releases raw data under one reading and nothing under another. -/
theorem check_is_needed_derived :
    shallowOK pViaDerived = true ∧ checkN noTrust hideRead [pViaDerived] = false ∧
    decideSide Lat7 useAll allAnchors noFacts readYes hideRead [pViaDerived] .raw .deny = .allow .raw ∧
    decideSide Lat7 useAll allAnchors noFacts readNo hideRead [pViaDerived] .raw .deny = .deny := by
  decide

def askReads : R7 := { id := 1, anchors := [], eff := .ask, guard := [{ atom := .read () }] }

/-- **What the old semantics did (finding B, fixed in core.py on 25 November).** An ask rule may
    read (Restriction N allows it). Before the fix, core.py tried every ask before the default, so
    a reading turned a default allow into a question. Now a reading-guarded ask falls through to
    the tail, and the default allow is released under both readings. -/
theorem ask_withholds_default :
    checkN noTrust ([] : P7) [askReads] = true ∧
    decideSideOld Lat7 allAnchors noFacts readNo ([] : P7) [askReads] .raw (.allow .raw) = .allow .raw ∧
    decideSideOld Lat7 allAnchors noFacts readYes ([] : P7) [askReads] .raw (.allow .raw) = .ask ∧
    decideSide Lat7 useAll allAnchors noFacts readNo ([] : P7) [askReads] .raw (.allow .raw) = .allow .raw ∧
    decideSide Lat7 useAll allAnchors noFacts readYes ([] : P7) [askReads] .raw (.allow .raw) = .allow .raw := by
  decide

/-- `declared(0)` is trusted; `hideRead` defines `d0 :- reading`. -/
def trust0 : Nat → Bool := fun d => d == 0
def bLift : R7 := { id := 1, anchors := [], eff := .boundary, guard := [], lifts := [[{ atom := .der 0 }]] }
def pRaw2 : R7 := { id := 2, anchors := [], eff := .permit .raw, guard := [] }

/-- **The trusted-predicate check is needed (finding A, fixed in core.py on 25 November).** A
    clause that defines the trusted `declared` from a reading passed the old check and lifted a
    boundary: raw data under one reading, nothing under the other. The new check rejects the clause;
    the same rule set without it passes. -/
theorem trusted_check_is_needed :
    checkOld hideRead [bLift, pRaw2] = true ∧
    checkN trust0 hideRead [bLift, pRaw2] = false ∧
    checkN trust0 ([] : P7) [bLift, pRaw2] = true ∧
    decideSide Lat7 useAll allAnchors noFacts readYes hideRead [bLift, pRaw2] .raw .deny = .allow .raw ∧
    decideSide Lat7 useAll allAnchors noFacts readNo hideRead [bLift, pRaw2] .raw .deny = .deny := by
  decide

def pRaw : R7 := { id := 1, anchors := [], eff := .permit .raw, guard := [] }
def minCell (prot : Bool) : R7 :=
  { id := 2, anchors := [], eff := .duty 5 prot, guard := [{ atom := .der 0 }] }

/-- **The protective-duty check is needed.** A `min_cell` duty guarded through a derived reading
    is accepted when not marked protective, rejected when marked protective; unchecked, a reading
    decides whether the protection is owed. -/
theorem protective_check_is_needed :
    checkN noTrust hideRead [pRaw, minCell false] = true ∧
    checkN noTrust hideRead [pRaw, minCell true] = false ∧
    protOwed allAnchors noFacts readYes hideRead [pRaw, minCell true] = [5] ∧
    protOwed allAnchors noFacts readNo hideRead [pRaw, minCell true] = [] := by
  decide

def dutyUnlessRead : R7 :=
  { id := 1, anchors := [], eff := .duty 7 false, guard := [{ atom := .der 0, neg := true }] }

/-- **The negation check is needed.** A duty guarded by a negated derived predicate that depends
    on a reading fails the check; unchecked, MORE readings remove the duty. -/
theorem negation_check_is_needed :
    checkN noTrust hideRead [dutyUnlessRead] = false ∧
    owed allAnchors noFacts readNo hideRead [dutyUnlessRead] = [7] ∧
    owed allAnchors noFacts readYes hideRead [dutyUnlessRead] = [] := by
  decide

/-- Differential check of the form order and the key against core.py (printed table). -/
def allForms : List Form7 := [.metadata, .count, .aggregated, .anonymised, .pseudonymised, .summarised, .raw]
#eval allForms.flatMap (fun a => allForms.filterMap (fun b => if Form7.le a b then some (repr a, repr b) else none)) |>.length
#eval (allForms.map fun f => (repr f, Form7.height f, Form7.rank f))

end AccessDerived

#print axioms AccessDerived.eval_reading_free
#print axioms AccessDerived.deps_sub_closure
#print axioms AccessDerived.chosen_offer_reading_free
#print axioms AccessDerived.release_reading_free_of_check
#print axioms AccessDerived.reading_never_opens
#print axioms AccessDerived.FormLat.choose_congr
#print axioms AccessDerived.decide_perm
#print axioms AccessDerived.protective_duties_reading_free
#print axioms AccessDerived.owed_mono
#print axioms AccessDerived.first_max_depends_on_order
#print axioms AccessDerived.check_is_needed_derived
#print axioms AccessDerived.ask_withholds_default
#print axioms AccessDerived.trusted_check_is_needed
#print axioms AccessDerived.trusted_deps_rf
#print axioms AccessDerived.protective_check_is_needed
#print axioms AccessDerived.negation_check_is_needed

Last built 2026-11-25