A user tells your assistant: Anna and Lena met in Berlin on day 2001, from 10:00 to 12:00. The model turns the sentence into a fact and writes it to memory. It writes day 2000.

It is an easy slip. Day 2000 is all over the context, because that is the day of the Lisbon kickoff, where Anna sat with Marco from 10:00 to 11:00. Now the memory holds two facts that cannot both be true, and nothing in the pipeline noticed. Tomorrow, asked where Anna was that morning, the agent will answer with whichever note retrieval ranks first, and it will sound equally sure either way.

A chatbot that hallucinates says something false once. An agent that hallucinates into its memory says it again tomorrow, and builds on it.

This post is about a memory that refuses. We will model an agent’s memory of people, places, and events as a provable ontology in Lean 4: types for the things the agent knows about, propositions for the rules of its world, and a store that cannot exist without a proof that it is consistent. Then we add λProlog, running inside Lean through lean-elpi, for the jobs logic programming does well: rules, search, and “what if” questions.

Every snippet below comes from one Lean file of about 400 lines, and every output and error message shown is the one Lean actually prints. You do not need to know Lean to follow along. Each piece of code comes with a plain reading.

Why the usual fixes leave a gap

Three remedies come up every time agent memory goes wrong. None of them closes this gap.

Retrieval brings back the relevant notes, both of them. It ranks; it does not decide which of two contradictory notes is right.

An LLM as judge (”is this fact consistent with memory?”) produces a plausible verdict. The hallucination moves from the fact to the verdict.

Schema validation with Pydantic or JSON Schema checks the shape of one record. “Anna, Lena, Berlin, 10:00 to 12:00” is a perfectly well-formed record. Bilocation is a property of two facts together, and a per-record validator never sees both.

What is missing is a checker: a small, fixed program that decides, with evidence, whether the memory after a write still obeys the rules of the world. Databases have one for constraints, compilers have one for types, and proof assistants have one for mathematics. The pattern for agents is the same: the LLM proposes, the checker decides, and memory changes only on a yes.

The ontology is a set of types

The domain is the memory of an assistant agent: people, cities, countries, and events in time. In Lean, an ontology’s classes become types, its individuals become values of those types, and its properties become functions.

inductive Person where
  | anna | marco | lena | taras | sofia
  deriving DecidableEq, Repr

inductive City where
  | lisbon | porto | berlin | kyiv
  deriving DecidableEq, Repr

inductive Country where
  | portugal | germany | ukraine
  deriving DecidableEq, Repr

inductive EventKind where
  | meeting | call
  deriving DecidableEq, Repr

/-- Every city lies in exactly one country. -/
def City.country : City → Country
  | .lisbon | .porto => .portugal
  | .berlin => .germany
  | .kyiv   => .ukraine

/-- A call needs no physical presence. -/
def EventKind.physical : EventKind → Bool
  | .call    => false
  | .meeting => true

Two things are already happening. First, the world is closed: the agent knows exactly these five people and four cities, and so does the type checker. Second, City.country is a total function, so “every city lies in exactly one country” is not a rule someone has to remember to check. It is the signature. In OWL it would be an exact-cardinality restriction that a reasoner has to check.

Time that cannot run backwards

/-- Minutes since the agent's epoch. The field `valid`
    is a proof: no span ends before it starts. -/
structure Span where
  start : Nat
  stop  : Nat
  valid : start ≤ stop
  deriving DecidableEq, Repr

def Span.mk! (a b : Nat)
    (h : a ≤ b := by decide) : Span := ⟨a, b, h⟩

def Span.Overlaps (i j : Span) : Prop :=
  i.start < j.stop ∧ j.start < i.stop

Plain reading: a Span is two numbers and a proof that the first is not larger than the second. mk! lets Lean find that proof by computation when the numbers are concrete.

This is a dependent type: the type of the third field mentions the values of the first two. The practical effect is that a backwards span (the classic extraction slip of reading “4:30 pm” as 04:30) is not a runtime bug to catch. It cannot be written down:

example : Span :=
  .mk! (day 2000 + hour 12) (day 2000 + hour 10)
error: Tactic `decide` proved that the proposition
  day 2000 + hour 12 ≤ day 2000 + hour 10
is false

(day and hour convert to minutes.) Compare a Pydantic validator. It runs when you construct the object, but nothing downstream knows that it ran, and nothing stops a later model_copy from bypassing it. Here the proof is part of the value. Every function that receives a Span knows it is well formed, because a Span without the proof does not exist.

Facts are typed records

An event records who was where and when. The memory is the agent’s background knowledge (birth times) plus the events it has recorded.

structure Event where
  id    : Nat
  kind  : EventKind
  who   : List Person
  place : City
  span  : Span
  deriving DecidableEq, Repr

structure Memory where
  born   : Person → Nat
  events : List Event

/-- What a naive agent does: append, check nothing. -/
def Memory.record (m : Memory) (e : Event) : Memory :=
  { m with events := e :: m.events }

The first payoff is that a fact of the wrong kind does not compile. Here a city lands in the attendee list:

example : Event :=
  { id := 9, kind := .meeting, who := [.lisbon]
    place := .lisbon, span := .mk! 0 60 }
error: Unknown constant `Mem.Person.lisbon`

Note: Inferred this name from the expected resulting type of `.lisbon`:
  Person

Domain and range checking, done before anything runs. But a well-typed fact can still be impossible, and that is the hallucination we care about.

The rules of the world are propositions

Now the rules. These are the ontology’s axioms, written as ordinary Lean propositions over a whole memory:

/-- Nobody attends an event before they are born. -/
def BornBefore (m : Memory) : Prop :=
  ∀ e ∈ m.events, ∀ p ∈ e.who, m.born p ≤ e.span.start

/-- Nobody is physically in two cities at once. -/
def NoBilocation (m : Memory) : Prop :=
  ∀ e₁ ∈ m.events, ∀ e₂ ∈ m.events,
    e₁.kind.physical = true →
    e₂.kind.physical = true →
    e₁.place ≠ e₂.place →
    e₁.span.Overlaps e₂.span →
    ∀ p ∈ e₁.who, p ∉ e₂.who

structure Consistent (m : Memory) : Prop where
  bornBefore   : BornBefore m
  noBilocation : NoBilocation m

Plain reading of NoBilocation: for any two recorded events that both need physical presence, take place in different cities, and overlap in time, nobody attends both.

Because the world is closed and the memory is finite, both axioms are decidable: Lean can compute whether they hold. Making that official takes one line per axiom in the companion file.

A memory that carries its own proof

inductive Violation where
  | bornBefore | noBilocation
  deriving Repr

/-- A memory together with a proof that it is
    consistent. There is no other way to build one. -/
structure Certified where
  mem : Memory
  ok  : Consistent mem

def Certified.insert (c : Certified) (e : Event) :
    Except Violation Certified :=
  let m := c.mem.record e
  if h : Consistent m then .ok ⟨m, h⟩
  else if BornBefore m then .error .noBilocation
  else .error .bornBefore

Plain reading: “given a certified memory and an event, either return a new certified memory with a new proof, or return the name of the axiom the event would break.”

Certified is the whole trick. To hold a value of this type you must hold a proof of Consistent, and the only way to grow one is insert. There is no back door where the agent “just appends”. The proof field is a Prop, so the compiler erases it: the check runs, and the proof costs nothing at run time.

Here is the small world:

def born : Person → Nat
  | .sofia => day 1000   -- joins the world late
  | _      => 0

def kickoff : Event :=
  { id := 1, kind := .meeting, who := [.anna, .marco]
    place := .lisbon
    span := .mk! (day 2000 + hour 10) (day 2000 + hour 11) }

def review : Event :=
  { id := 2, kind := .call, who := [.anna, .taras]
    place := .kyiv
    span := .mk! (day 2000 + hour 10) (day 2000 + hour 11) }

def store : Memory := { born, events := [review, kickoff] }

/-- The kernel evaluates both axioms on the store. -/
theorem store_ok : Consistent store := by decide

def memory : Certified := ⟨store, store_ok⟩

Anna is in Lisbon for the kickoff and, at the same hour, on a call “in” Kyiv with Taras. That is fine: a call is not physical, so NoBilocation does not apply to it. The ontology knows the difference between being somewhere and dialing in.

Watching hallucinations bounce

The phantom meeting from the opening:

/-- The LLM "remembers" Anna in Berlin that morning. -/
def phantom : Event :=
  { id := 3, kind := .meeting, who := [.anna, .lena]
    place := .berlin
    span := .mk! (day 2000 + hour 10) (day 2000 + hour 12) }

#eval (memory.insert phantom).map (·.mem.events.length)
Except.error (Mem.Violation.noBilocation)

A different slip: a sentence mentions Sofia, and the model makes her a participant in a meeting long before she exists in this world.

def tooEarly : Event :=
  { id := 4, kind := .meeting, who := [.marco, .sofia]
    place := .porto
    span := .mk! (day 500) (day 500 + hour 1) }

#eval (memory.insert tooEarly).map (·.mem.events.length)
Except.error (Mem.Violation.bornBefore)

And the meeting on the day the user actually said:

def corrected : Event :=
  { phantom with
    span := .mk! (day 2001 + hour 10) (day 2001 + hour 12) }

#eval (memory.insert corrected).map (·.mem.events.length)
Except.ok 3

A rejection names the rule, and that name is useful. In the book’s complete agent, it turns into feedback for the model, with the clashing event as evidence:

llm    #3 meeting in berlin, day 2000 10:00-12:00: anna, lena
check  REJECTED. Fact 1 (#3 meeting in berlin, day 2000
       10:00-12:00: anna, lena) violates the axiom NoBilocation:
       nobody is physically in two cities at overlapping times.
       Evidence: anna already at #1 meeting in lisbon, day 2000
       10:00-11:00: anna, marco.
llm    #3 meeting in berlin, day 2001 10:00-12:00: anna, lena
check  ACCEPTED. The store now has 3 events and a new proof of
       Consistent.

The explanation text is ordinary, untrusted code. If it had a bug, memory would be exactly as safe, because the decision was already made by Certified.insert. We spend proof effort only on the part that decides.

From certified to provable: theorems about every memory

So far every check ran on concrete values. That makes the memory certified: each state carries a proof. A provable ontology goes one step further. Because the axioms are propositions, we can prove theorems about the ontology itself, for every memory and every fact that will ever exist.

Here is one that matters to an agent: recording a call can never create a bilocation.

/-- Recording a call can never create a bilocation,
    in any memory, for any call. -/
theorem call_safe (m : Memory) (e : Event)
    (hk : e.kind = .call) (h : NoBilocation m) :
    NoBilocation (m.record e) := by
  intro e₁ h₁ e₂ h₂ p₁ p₂ hne hov
  have hk' : e.kind.physical = false := by
    rw [hk]; rfl
  cases List.mem_cons.mp h₁ with
  | inl h => subst h; rw [hk'] at p₁; contradiction
  | inr h₁ =>
    cases List.mem_cons.mp h₂ with
    | inl h => subst h; rw [hk'] at p₂; contradiction
    | inr h₂ => exact h e₁ h₁ e₂ h₂ p₁ p₂ hne hov

Plain reading: “for any memory without bilocations and any event that is a call, the memory with that call added still has no bilocations.”

The proof is a short case split. If either of the two events under comparison is the new call, it is not physical, so the axiom’s precondition is false. Otherwise both events were already in the old memory, which had no bilocations. Lean’s kernel checks every step.

A test checks the examples you thought of. This holds for all of them. That buys an agent builder some concrete things:

  • Safe shortcuts. An ingestion pipeline can skip the bilocation check for calls, and the theorem says that is not a gamble.

  • Schema changes with a map. Add an event kind or an axiom, and the proofs that stop compiling are exactly the places the change affects. The book uses this for invariants, safe updates, and schema migrations.

  • A shared language with your ontologist. A theorem is a sentence about the domain that a domain expert can read and dispute, and a machine can check.

Put side by side, here is what each approach gives you for agent memory.

Pydantic or JSON Schema catches a malformed single fact. It does not see contradictions across facts, cannot say which domain rule broke, and makes no promises about future states.

An LLM judge sometimes notices contradictions and sometimes names a rule, but its verdict is another prediction that needs checking.

A provable ontology rejects malformed facts at compile time, decides cross-fact consistency on every write, names the broken axiom, proves properties for all memories, and, as the next section shows, requires every answer to carry evidence.

Answers are proofs, too

Writes are half the problem. Ask the agent: Did Anna meet Taras on day 2000? A model reading the memory sees Anna and Taras together on event 2 and says yes. But event 2 was a call.

/-- `p` and `q` were both at the physical event `i`. -/
def MetAt (m : Memory) (p q : Person) (i : Nat) : Prop :=
  ∃ e ∈ m.events, e.id = i ∧ e.kind.physical = true ∧
    p ∈ e.who ∧ q ∈ e.who ∧ p ≠ q

theorem anna_met_marco : MetAt store .anna .marco 1 := by
  decide

The claim that she met Marco is a theorem. The claim that she met Taras is refused:

example : MetAt store .anna .taras 2 := by decide
error: Tactic `decide` proved that the proposition
  MetAt store Person.anna Person.taras 2
is false

This is the second half of the formal definition of hallucination the book works with: a claimed answer with no proof from the store. The agent states a claim only when the decision procedure returns a proof.

Where λProlog comes in

Lean is the checker. But much of what an agent wants from its memory is naturally search: whom did Anna meet, who sits above Marco in the reporting chain, which of these people were ever in Portugal, and what would change if Lena had joined the kickoff. You can write each of those as a Lean function. Logic programming has a better habit: write the rules once and let an engine search for answers.

λProlog is Prolog with types, higher-order rules, and scoped assumptions. ELPI is a modern dialect of it, best known as the extension language of the Rocq (formerly Coq) proof assistant. lean-elpi is a clean-room implementation of ELPI that runs inside Lean 4, in the same process, with Lean types bridged into the engine. The division of labor is simple: ELPI searches, Lean checks.

The bridge: one source of truth

deriving instance Elpi for Person
deriving instance Elpi for City
deriving instance Elpi for Country
deriving instance Elpi for EventKind

-- Lean's functions become ELPI predicates:
-- one source of truth for geography.
elpi_extern Mem.City.country as "country"
elpi_extern Mem.EventKind.physical as "physical"

The engine sees the same people and cities as the type checker. elpi_extern makes Lean’s own City.country callable as an ELPI predicate, so there is no second geography table in the rules that could drift from the first.

Rules

elpi_program memRules
elpi_accumulate memRules lp%{
  pred event o:int, o:eventKind, o:city.
  pred attends o:int, o:person.

  % P and Q met in person at event E.
  pred met i:person, o:person, o:int.
  met P Q E :-
    attends E P, event E K _, physical K tt,
    attends E Q, not (P = Q).

  % A sloppy rule: forgets that calls are not meetings.
  pred met_sloppy i:person, o:person, o:int.
  met_sloppy P Q E :-
    attends E P, attends E Q, not (P = Q).

  % P was in country C during event E.
  pred was_in i:person, o:country, o:int.
  was_in P C E :-
    attends E P, event E K X, physical K tt,
    country X C.
}%

Note met_sloppy. It is the kind of rule a tired engineer writes on a Friday, or an LLM writes when asked for “a rule for who met whom”. We will keep it on purpose.

Feeding the engine only certified facts

/-- The certified memory as ELPI clauses. -/
def clauses (m : Memory) : List String :=
  m.events.flatMap fun e =>
    s!"event {e.id} {e.kind.name} {e.place.name}" ::
    e.who.map fun p => s!"attends {e.id} {p.name}"

/-- `[facts] => goal`: the facts hold for one query
    only. Nothing persists in the engine. -/
def ask (m : Memory) (goal : String) :
    MetaM (List (Person × Nat)) := do
  let q := "[" ++ ", ".intercalate (clauses m) ++
    "] => " ++ goal
  let sols ← Elpi.query memRules q (fuel := 100000)
  return (sols.take 20).filterMap fun
    | .ok s => do
      let p : Person ← s.get? "Q"
      let i : Nat ← s.get? "E"
      pure (p, i)
    | .error _ => none

The memory goes to ELPI as hypothetical clauses (facts => goal), one query at a time. The rules never see a fact Lean did not accept, and nothing is left behind in the engine between queries. The fuel budget means a rule that loops (say, over a cyclic reporting line) returns an error value instead of hanging the agent. Solutions come back as typed Lean values: s.get? "Q" returns a Person, not a string.

Search proposes, Lean disposes

#eval ask store "met anna Q E"
#eval ask store "met_sloppy anna Q E"
[(Mem.Person.marco, 1)]
[(Mem.Person.taras, 2), (Mem.Person.marco, 1)]

The sloppy rule claims Anna met Taras, because it forgot that the review was a call. Now put Lean between the rules and the user:

/-- ELPI proposes, Lean disposes: keep a candidate only
    if the kernel's decision procedure says yes. -/
def certified (m : Memory) (p : Person) (goal : String) :
    MetaM (List (Person × Nat)) := do
  let cands ← ask m goal
  return cands.filter fun (q, i) => decide (MetAt m p q i)

#eval certified store .anna "met_sloppy anna Q E"
[(Mem.Person.marco, 1)]

This is the ELPI use case in one paragraph. You can write rules fast, write them wrong, or let a model write them, and the agent still says only what it can prove. The rules are a proposer, like the LLM. The checker is the same small piece of Lean in both cases.

“What if” without writing anything

Agents plan, and planning means asking questions about memories that do not exist yet. λProlog’s => adds an assumption for the length of one query:

-- What if Lena had joined the kickoff?
#eval ask store "(attends 1 lena => met lena Q E)"
#eval ask store "met lena Q E"
[(Mem.Person.anna, 1), (Mem.Person.marco, 1)]
[]

Under the assumption, Lena meets Anna and Marco at event 1. Without it, she has met nobody. There is no transaction to roll back and no copy of the memory to discard. The assumption simply goes out of scope.

Search results as kernel-checked proof terms

lean-elpi has one more layer, and it is the one that closes the loop between search and proof. In its LF layer you state judgments as types and rules as constructors. ELPI searches for a derivation, records it as a proof term, and hands the term to Lean’s kernel.

lf_signature org lp%{
  #lf
  person : type.
  anna : person. marco : person. lena : person.
  reports : person -> person -> type.
  r_marco : reports marco anna.
  r_anna  : reports anna lena.
  under : person -> person -> type.
  under_one  : under X Y <- reports X Y.
  under_step : under X Z <- reports X Y <- under Y Z.
}%

lf_export org

lf_certify org marco_under_lena lp%{ under marco lena }%

#print marco_under_lena
#print axioms marco_under_lena
theorem marco_under_lena : Org.Under Org.Person.marco Org.Person.lena :=
Org.Under.under_step (Org.Under.under_one Org.Reports.r_anna) Org.Reports.r_marco

'marco_under_lena' does not depend on any axioms

Plain reading: “Marco is under Lena, because Marco reports to Anna and Anna reports to Lena.” The engine found that chain. It is now a Lean theorem, checked by the kernel, that depends on no axioms at all. The search engine is untrusted; the certificate is not. In the book, a soundness theorem proved once carries every such certificate over to the memory’s own reporting relation.

What this does not give you

The promise is narrow on purpose, and it is worth stating plainly.

  • Consistency, not truth. If the model “fixes” the phantom by moving the meeting to an hour when nobody is busy, the result is consistent and it gets in. The checker narrows what can go wrong; it does not read the user’s mind. Provenance and confirmation handle the rest.

  • Your axioms, no more. Put Sofia’s phantom meeting on day 1900 instead of day 500 and BornBefore is silent. A checker is exactly as good as the rules you write down.

  • A closed vocabulary. A person the memory does not know is a parse error for a write and an honest “I don’t know” for a question. Growing the vocabulary is a schema change, which is precisely where provable ontologies help.

  • Soundness, not completeness. Lean filters out wrong answers from a sloppy rule. It does not notice answers a rule fails to find. Claims like “Anna met nobody else” need their own decidable propositions, and the book’s agent has them.

  • A precise trust base. At build time you trust Lean’s small kernel. At run time the agent’s checks are compiled code, so you also trust the compiler and runtime. The book’s agent can export its certificates as a Lean file that anyone can recheck with the kernel alone.

  • Scale. Deciding axioms over lists compares every pair of events. That is fine for a personal assistant’s memory and needs indexing for millions of events.

The book: Bulletproof Knowledge

This post is a compressed tour of my new book, Bulletproof Knowledge: Building Hallucination-Resistant Neurosymbolic Agents with Lean and Logic Programming. It takes the same memory, the same five people, and the same phantom meeting much further.

Part I, Why Provable Knowledge. Neurosymbolic integration patterns, why LLMs hallucinate in the mechanistic sense, the ladder from propositional to higher-order logic, knowledge graphs and metagraphs, ontologies as types, and a balanced case for the closed world in agent memory.

Part II, Certified Ontologies in Pure Lean 4. Lean taught from zero, the certified store, place and event hierarchies with type classes and subtypes, and proving the ontology itself: invariants, safe updates, and schema evolution.

Part III, Reasoning with lean-elpi. λProlog inside Lean, rules over the memory, relations as arguments, hypothetical queries, reasoning over a metagraph, and certificates from search. It ends with a complete agent written entirely in Lean, with a write loop and a read loop, that talks to an LLM. In a replayed session the model makes seven mistakes of seven different kinds over six turns: a bilocation, a meeting before birth, a second manager, a duplicate id, malformed JSON, a backwards span, and an unknown person. The checker catches every one and names the rule it broke.

It is written for agent engineers, not mathematicians. If you know Python and have built with LLMs, you have the background. Lean and λProlog are taught from zero, only as far as the book needs, with code first, then a picture, then notation.

What you get:

  • 12 chapters in three parts, 33 diagrams, exercises with compiled solutions, and a 60-term glossary

  • Apache-2.0 companion code at github.com/Volland/bulletproof-knowledge: Lean 4 v4.35.0, lean-elpi v0.3.3, no Mathlib, one lake build

  • Every snippet in the book is cut from that repository, and every output and error is the one Lean prints

The complete first draft is on Leanpub now, and Leanpub readers get every update free as the book moves through technical review. The free sample includes Chapter 1 and Chapter 4, Ontologies as Types, the long version of the modeling section above.

Read the sample and get the book on Leanpub →

If you have read Metagraph for AI Agents or Temporal Aware AI Memory, this is the book where the memory starts proving things.

The LLM proposes. Lean decides. No proof, no entry; no proof, no answer.


Full memory

import Elpi

/-!
# Provable agent memory in one file

Companion code for the Substack article "Your Agent's Memory
Should Be Able to Say No". A compact, self-contained version
of the running example from *Bulletproof Knowledge*.

Check it from the book's companion repository:

    cd code && lake env lean ../article/AgentMemory.lean

Every `#guard_msgs` below is the output Lean actually prints.
-/

namespace Mem

/-! ## 1. The ontology is a set of types -/

-- ANCHOR: entities
inductive Person where
  | anna | marco | lena | taras | sofia
  deriving DecidableEq, Repr

inductive City where
  | lisbon | porto | berlin | kyiv
  deriving DecidableEq, Repr

inductive Country where
  | portugal | germany | ukraine
  deriving DecidableEq, Repr

inductive EventKind where
  | meeting | call
  deriving DecidableEq, Repr

/-- Every city lies in exactly one country. -/
def City.country : City → Country
  | .lisbon | .porto => .portugal
  | .berlin => .germany
  | .kyiv   => .ukraine

/-- A call needs no physical presence. -/
def EventKind.physical : EventKind → Bool
  | .call    => false
  | .meeting => true
-- ANCHOR_END: entities

-- ANCHOR: span
/-- Minutes since the agent's epoch. The field `valid`
    is a proof: no span ends before it starts. -/
structure Span where
  start : Nat
  stop  : Nat
  valid : start ≤ stop
  deriving DecidableEq, Repr

def Span.mk! (a b : Nat)
    (h : a ≤ b := by decide) : Span := ⟨a, b, h⟩

def Span.Overlaps (i j : Span) : Prop :=
  i.start < j.stop ∧ j.start < i.stop

instance (i j : Span) : Decidable (i.Overlaps j) :=
  inferInstanceAs (Decidable (_ ∧ _))
-- ANCHOR_END: span

-- ANCHOR: event
structure Event where
  id    : Nat
  kind  : EventKind
  who   : List Person
  place : City
  span  : Span
  deriving DecidableEq, Repr

structure Memory where
  born   : Person → Nat
  events : List Event

/-- What a naive agent does: append, check nothing. -/
def Memory.record (m : Memory) (e : Event) : Memory :=
  { m with events := e :: m.events }
-- ANCHOR_END: event

def hour (h : Nat) : Nat := 60 * h
def day (d : Nat) : Nat := 24 * 60 * d

/-! ## 2. Ill-formed facts do not compile -/

-- ANCHOR: wrong_kind
/--
error: Unknown constant `Mem.Person.lisbon`

Note: Inferred this name from the expected resulting type of `.lisbon`:
  Person
-/
#guard_msgs in
example : Event :=
  { id := 9, kind := .meeting, who := [.lisbon]
    place := .lisbon, span := .mk! 0 60 }
-- ANCHOR_END: wrong_kind

-- ANCHOR: backwards
/--
error: could not synthesize default value for parameter 'h' using tactics
---
error: Tactic `decide` proved that the proposition
  day 2000 + hour 12 ≤ day 2000 + hour 10
is false
-/
#guard_msgs in
example : Span :=
  .mk! (day 2000 + hour 12) (day 2000 + hour 10)
-- ANCHOR_END: backwards

/-! ## 3. Axioms are propositions the machine can decide -/

-- ANCHOR: axioms
/-- Nobody attends an event before they are born. -/
def BornBefore (m : Memory) : Prop :=
  ∀ e ∈ m.events, ∀ p ∈ e.who, m.born p ≤ e.span.start

/-- Nobody is physically in two cities at once. -/
def NoBilocation (m : Memory) : Prop :=
  ∀ e₁ ∈ m.events, ∀ e₂ ∈ m.events,
    e₁.kind.physical = true →
    e₂.kind.physical = true →
    e₁.place ≠ e₂.place →
    e₁.span.Overlaps e₂.span →
    ∀ p ∈ e₁.who, p ∉ e₂.who

structure Consistent (m : Memory) : Prop where
  bornBefore   : BornBefore m
  noBilocation : NoBilocation m
-- ANCHOR_END: axioms

instance (m : Memory) : Decidable (BornBefore m) := by
  unfold BornBefore; infer_instance
instance (m : Memory) : Decidable (NoBilocation m) := by
  unfold NoBilocation; infer_instance
instance (m : Memory) : Decidable (Consistent m) :=
  if h₁ : BornBefore m then
    if h₂ : NoBilocation m then isTrue ⟨h₁, h₂⟩
    else isFalse fun c => h₂ c.noBilocation
  else isFalse fun c => h₁ c.bornBefore

/-! ## 4. A memory that carries its own proof -/

-- ANCHOR: certified
inductive Violation where
  | bornBefore | noBilocation
  deriving Repr

/-- A memory together with a proof that it is
    consistent. There is no other way to build one. -/
structure Certified where
  mem : Memory
  ok  : Consistent mem

def Certified.insert (c : Certified) (e : Event) :
    Except Violation Certified :=
  let m := c.mem.record e
  if h : Consistent m then .ok ⟨m, h⟩
  else if BornBefore m then .error .noBilocation
  else .error .bornBefore
-- ANCHOR_END: certified

-- ANCHOR: world
def born : Person → Nat
  | .sofia => day 1000   -- joins the world late
  | _      => 0

def kickoff : Event :=
  { id := 1, kind := .meeting, who := [.anna, .marco]
    place := .lisbon
    span := .mk! (day 2000 + hour 10) (day 2000 + hour 11) }

def review : Event :=
  { id := 2, kind := .call, who := [.anna, .taras]
    place := .kyiv
    span := .mk! (day 2000 + hour 10) (day 2000 + hour 11) }

def store : Memory := { born, events := [review, kickoff] }

/-- The kernel evaluates both axioms on the store. -/
theorem store_ok : Consistent store := by decide

def memory : Certified := ⟨store, store_ok⟩
-- ANCHOR_END: world

/-! ## 5. Hallucinations bounce -/

-- ANCHOR: phantom
/-- The LLM "remembers" Anna in Berlin that morning. -/
def phantom : Event :=
  { id := 3, kind := .meeting, who := [.anna, .lena]
    place := .berlin
    span := .mk! (day 2000 + hour 10) (day 2000 + hour 12) }

/-- info: Except.error (Mem.Violation.noBilocation) -/
#guard_msgs in
#eval (memory.insert phantom).map (·.mem.events.length)
-- ANCHOR_END: phantom

-- ANCHOR: sofia
/-- A meeting with Sofia before she joined the world. -/
def tooEarly : Event :=
  { id := 4, kind := .meeting, who := [.marco, .sofia]
    place := .porto
    span := .mk! (day 500) (day 500 + hour 1) }

/-- info: Except.error (Mem.Violation.bornBefore) -/
#guard_msgs in
#eval (memory.insert tooEarly).map (·.mem.events.length)
-- ANCHOR_END: sofia

-- ANCHOR: fixed
/-- The same meeting on the day the user actually said. -/
def corrected : Event :=
  { phantom with
    span := .mk! (day 2001 + hour 10) (day 2001 + hour 12) }

/-- info: Except.ok 3 -/
#guard_msgs in
#eval (memory.insert corrected).map (·.mem.events.length)
-- ANCHOR_END: fixed

/-! ## 6. Proofs about the ontology, for every memory -/

-- ANCHOR: theorem
/-- Recording a call can never create a bilocation,
    in any memory, for any call. -/
theorem call_safe (m : Memory) (e : Event)
    (hk : e.kind = .call) (h : NoBilocation m) :
    NoBilocation (m.record e) := by
  intro e₁ h₁ e₂ h₂ p₁ p₂ hne hov
  have hk' : e.kind.physical = false := by
    rw [hk]; rfl
  cases List.mem_cons.mp h₁ with
  | inl h => subst h; rw [hk'] at p₁; contradiction
  | inr h₁ =>
    cases List.mem_cons.mp h₂ with
    | inl h => subst h; rw [hk'] at p₂; contradiction
    | inr h₂ => exact h e₁ h₁ e₂ h₂ p₁ p₂ hne hov
-- ANCHOR_END: theorem

/-! ## 7. Answers are proofs, too -/

-- ANCHOR: claims
/-- `p` and `q` were both at the physical event `i`. -/
def MetAt (m : Memory) (p q : Person) (i : Nat) : Prop :=
  ∃ e ∈ m.events, e.id = i ∧ e.kind.physical = true ∧
    p ∈ e.who ∧ q ∈ e.who ∧ p ≠ q

instance (m : Memory) (p q : Person) (i : Nat) :
    Decidable (MetAt m p q i) := by
  unfold MetAt; infer_instance

theorem anna_met_marco : MetAt store .anna .marco 1 := by
  decide
-- ANCHOR_END: claims

-- ANCHOR: claim_fail
/--
error: Tactic `decide` proved that the proposition
  MetAt store Person.anna Person.taras 2
is false
-/
#guard_msgs in
example : MetAt store .anna .taras 2 := by decide
-- ANCHOR_END: claim_fail

end Mem

/-! ## 8. Rules and search in λProlog, via lean-elpi

lean-elpi v0.3.3: `elpi_extern` and the LF commands must run
outside any namespace, so this part lives at the root.
-/

open Elpi.Cmd Mem

-- ANCHOR: bridge
deriving instance Elpi for Person
deriving instance Elpi for City
deriving instance Elpi for Country
deriving instance Elpi for EventKind

-- Lean's functions become ELPI predicates:
-- one source of truth for geography.
elpi_extern Mem.City.country as "country"
elpi_extern Mem.EventKind.physical as "physical"
-- ANCHOR_END: bridge

-- ANCHOR: rules
elpi_program memRules
elpi_accumulate memRules lp%{
  pred event o:int, o:eventKind, o:city.
  pred attends o:int, o:person.

  % P and Q met in person at event E.
  pred met i:person, o:person, o:int.
  met P Q E :-
    attends E P, event E K _, physical K tt,
    attends E Q, not (P = Q).

  % A sloppy rule: forgets that calls are not meetings.
  pred met_sloppy i:person, o:person, o:int.
  met_sloppy P Q E :-
    attends E P, attends E Q, not (P = Q).

  % P was in country C during event E.
  pred was_in i:person, o:country, o:int.
  was_in P C E :-
    attends E P, event E K X, physical K tt,
    country X C.
}%
-- ANCHOR_END: rules

namespace Mem

open Lean (MetaM)

def Person.name : Person → String
  | .anna => "anna" | .marco => "marco" | .lena => "lena"
  | .taras => "taras" | .sofia => "sofia"
def City.name : City → String
  | .lisbon => "lisbon" | .porto => "porto"
  | .berlin => "berlin" | .kyiv => "kyiv"
def EventKind.name : EventKind → String
  | .meeting => "meeting" | .call => "call"

-- ANCHOR: render
/-- The certified memory as ELPI clauses. -/
def clauses (m : Memory) : List String :=
  m.events.flatMap fun e =>
    s!"event {e.id} {e.kind.name} {e.place.name}" ::
    e.who.map fun p => s!"attends {e.id} {p.name}"

/-- `[facts] => goal`: the facts hold for one query
    only. Nothing persists in the engine. -/
def ask (m : Memory) (goal : String) :
    MetaM (List (Person × Nat)) := do
  let q := "[" ++ ", ".intercalate (clauses m) ++
    "] => " ++ goal
  let sols ← Elpi.query memRules q (fuel := 100000)
  return (sols.take 20).filterMap fun
    | .ok s => do
      let p : Person ← s.get? "Q"
      let i : Nat ← s.get? "E"
      pure (p, i)
    | .error _ => none
-- ANCHOR_END: render

-- ANCHOR: search
/-- info: [(Mem.Person.marco, 1)] -/
#guard_msgs in
#eval ask store "met anna Q E"

/-- info: [(Mem.Person.taras, 2), (Mem.Person.marco, 1)] -/
#guard_msgs in
#eval ask store "met_sloppy anna Q E"
-- ANCHOR_END: search

-- ANCHOR: check
/-- ELPI proposes, Lean disposes: keep a candidate only
    if the kernel's decision procedure says yes. -/
def certified (m : Memory) (p : Person) (goal : String) :
    MetaM (List (Person × Nat)) := do
  let cands ← ask m goal
  return cands.filter fun (q, i) => decide (MetAt m p q i)

/-- info: [(Mem.Person.marco, 1)] -/
#guard_msgs in
#eval certified store .anna "met_sloppy anna Q E"
-- ANCHOR_END: check

-- ANCHOR: whatif
-- What if Lena had joined the kickoff?
/-- info: [(Mem.Person.anna, 1), (Mem.Person.marco, 1)] -/
#guard_msgs in
#eval ask store "(attends 1 lena => met lena Q E)"

/-- info: [] -/
#guard_msgs in
#eval ask store "met lena Q E"
-- ANCHOR_END: whatif

end Mem

/-! ## 9. Search results as kernel-checked proof terms -/

open Elpi.LFCmd

-- ANCHOR: lf
lf_signature org lp%{
  #lf
  person : type.
  anna : person. marco : person. lena : person.
  reports : person -> person -> type.
  r_marco : reports marco anna.
  r_anna  : reports anna lena.
  under : person -> person -> type.
  under_one  : under X Y <- reports X Y.
  under_step : under X Z <- reports X Y <- under Y Z.
}%

lf_export org

lf_certify org marco_under_lena lp%{ under marco lena }%
-- ANCHOR_END: lf

/--
info: theorem marco_under_lena : Org.Under Org.Person.marco Org.Person.lena :=
Org.Under.under_step (Org.Under.under_one Org.Reports.r_anna) Org.Reports.r_marco
-/
#guard_msgs in
-- ANCHOR: lf_print
#print marco_under_lena
-- ANCHOR_END: lf_print

/-- info: 'marco_under_lena' does not depend on any axioms -/
#guard_msgs in
-- ANCHOR: lf_axioms
#print axioms marco_under_lena
-- ANCHOR_END: lf_axioms

Originally published on Sovereign Agentic AI on Substack.