Why trust needs types, rules and proofs

When an AI agent from one company does work for another company, the question is never just “can it do the task?” It is “who says so, through whom, for which kind of work, and would that still hold if one link in the chain went bad?” That is a social trust graph, and it is exactly the kind of structure where a plain property graph stores the claims but cannot tell you whether they add up.

In this long read we build one end to end, with three tools from the Lean 4 Knowledge stack working as layers:

  1. 1.

    ladybug-lean stores the graph in LadybugDB with a schema the Lean compiler knows, and checks every Cypher query against it.

  2. 2.

    lean-elpi runs the ontology and the trust rules in λProlog, where policies are higher-order terms, binders are handled by the logic, and “what if” questions are one line.

  3. 3.

    The LF layer of lean-elpi turns a trust derivation into a proof term, and the Lean kernel checks it as a theorem.

[embed: node/e26db11c-8f69]

Each layer hands a typed value to the next; only the bottom one has to be right.

Along the way we lift the Ladybug types a level up: from storage rows to role-indexed keys, refined weights, typestate tasks and, finally, records that carry the proof of their own invariant.

The guiding idea is the one from Let logic search. Let Lean check.: the search engine is allowed to be clever, and even wrong, because the kernel is the only thing we trust.

About the code. Every snippet follows the APIs documented for ladybug-lean v0.1.0 and lean-elpi v0.1.0 (both pinned in the lakefiles below). The snippets were written for this article and not compiled in this session, so treat small names (generated constructor names, export namespaces) as things to confirm with #elpi_signature and #print in your checkout.

The domain: companies, agents and the work between them

The domain has four kinds of thing and nine kinds of edge, and every interesting question crosses at least three of them. Companies request tasks and vouch for agents. Agents are operated by companies, hold capabilities, endorse each other and delegate work. Tasks need a capability, and the requesting company attests to the result.

Weights are integers in basis points, 0 to 10,000, so 9,000 means 90 %. Integers keep the arithmetic exact on all three layers: LadybugDB, λProlog and Lean.

The running example

Acme vouches for orbit-coder-1 on code at 9,000. orbit-coder-1 endorses orbit-reviewer-7 on code.review at 8,000. Task 42 (code.review) is assigned to orbit-coder-1, who delegates it to orbit-reviewer-7. Acme earlier attested task 41 (code.gen, done by orbit-coder-1) as accepted.

The question we will answer, with a checked proof: may orbit-reviewer-7 perform task 42 for Acme, and what breaks if orbit-coder-1 is revoked? The trust Acme can derive in the reviewer is 9,000 × 8,000 / 10,000 = 7,200 basis points, reached only through the coder.

[embed: node/76877c61-1015]

The reviewer’s 7,200 exists only because of the coder; rogue-9 has no path at all, which matters in section 6.

Layer 1: the storage schema in ladybug-lean

The first layer is deliberately boring: the schema is a set of Lean structures, and node_table / rel_table turn them into LadybugDB tables whose shape the compiler knows. A query that names a missing property or walks an edge the wrong way is a compile error, not a runtime surprise.

Start a Lake project with both libraries:

-- lakefile.lean
require ladybug from git "https://github.com/Volland/ladybug-lean" @ "v0.1.0"
require «lean-elpi» from git "https://github.com/Volland/lean-elpi" @ "v0.1.0"

Nodes and relationships

import Ladybug
open Ladybug

structure Company where
  did  : String            -- did:web:acme.example
  name : String

structure Agent where
  did     : String         -- did:key:z6Mk...
  name    : String
  model   : String
  revoked : Bool

structure Capability where
  name   : String          -- "code.review"
  parent : Option String   -- "code"; NULL at the roots

structure Task where
  id      : Int64
  cap     : String
  status  : String         -- stored as text, lifted in the next section
  created : Timestamp

structure OperatedBy                    -- edges without properties
structure HasCapability
structure Requested
structure AssignedTo

structure Partners where
  since : Date

structure Vouches where                 -- Company → Agent
  cap    : String
  weight : Int32                        -- basis points, 0..10000
  stamp  : Timestamp

structure Endorses where                -- Agent → Agent
  cap    : String
  weight : Int32
  stamp  : Timestamp

structure Delegates where
  task  : Int64
  depth : Int32

structure Attests where
  accepted : Bool
  stamp    : Timestamp

node_table Company    (key := did)
node_table Agent      (key := did)
node_table Capability (key := name)
node_table Task                         -- key `id`

rel_table OperatedBy    (from := Agent)   (to := Company)
rel_table HasCapability (from := Agent)   (to := Capability)
rel_table Partners      (from := Company) (to := Company)
rel_table Vouches       (from := Company) (to := Agent)
rel_table Endorses      (from := Agent)   (to := Agent)
rel_table Requested     (from := Company) (to := Task)
rel_table AssignedTo    (from := Task)    (to := Agent)
rel_table Delegates     (from := Agent)   (to := Agent)
rel_table Attests       (from := Company) (to := Task)

def trustSchema : Schema :=
  [.ofNode Company, .ofNode Agent, .ofNode Capability, .ofNode Task,
   .ofRel OperatedBy, .ofRel HasCapability, .ofRel Partners,
   .ofRel Vouches, .ofRel Endorses, .ofRel Requested,
   .ofRel AssignedTo, .ofRel Delegates, .ofRel Attests]

Every field type is checked when the file compiles. A field such as score : Nat → Nat would be rejected at node_table, naming the field, because it has no column type.

Typed queries over the trust graph

The queries the reasoning layer needs are snapshots of edges. With cypher% the result type is inferred from the RETURN clause:

def vouchRows : Query (String × String × String × Int32) := cypher%
  MATCH (c:Company)-[v:Vouches]->(a:Agent)
  RETURN c.did, a.did, v.cap, v.weight

def endorseRows : Query (String × String × String × Int32) := cypher%
  MATCH (x:Agent)-[e:Endorses]->(y:Agent)
  RETURN x.did, y.did, e.cap, e.weight

def delegationRows : Query (String × String × Int64) := cypher%
  MATCH (x:Agent)-[d:Delegates]->(y:Agent)
  RETURN x.did, y.did, d.task

The graph side can already answer reachability. This lists everyone within three endorsement hops of an agent, with typed Path values:

def endorsementReach (start : String) : Query (String × Int64) := query do
  let a ← match_ (node Agent)
  where_ (a.did ==. lit start)
  let (path, b) ← matchPaths a Endorses (node Agent) (max := 3)
  return_ (b.did, pathLength path)

What the graph cannot do on its own is decide whether those hops count. An endorsement for data.etl says nothing about a code.review task; a hop through a revoked agent should not carry trust; a requester’s policy may demand both trust and reputation. Those are rules over the graph, and they belong to the next layers.

Loading the running example

Repo keeps loading typed and backend-agnostic, so the same function seeds an in-memory graph in a test and a LadybugDB file in production:

def seed {m : Type → Type} [MonadGraph m] (now : Timestamp) (d : Date) : m Unit := withTx do
  applySchema trustSchema
  Repo.insertMany (#[⟨"did:web:acme", "Acme Logistics"⟩, ⟨"did:web:orbit", "Orbit Labs"⟩,
                     ⟨"did:web:northwind", "Northwind Data"⟩,
                     ⟨"did:web:helix", "Helix Security"⟩] : Array Company)
  Repo.insertMany (#[⟨"orbit-coder-1", "Coder", "m-large", false⟩,
                     ⟨"orbit-reviewer-7", "Reviewer", "m-small", false⟩,
                     ⟨"nw-etl-3", "ETL", "m-small", false⟩,
                     ⟨"helix-audit-2", "Auditor", "m-large", false⟩,
                     ⟨"rogue-9", "Unknown", "m-small", false⟩] : Array Agent)
  Repo.insertMany (#[⟨"code", none⟩, ⟨"code.gen", some "code"⟩, ⟨"code.review", some "code"⟩,
                     ⟨"data", none⟩, ⟨"data.etl", some "data"⟩,
                     ⟨"security", none⟩, ⟨"security.audit", some "security"⟩] : Array Capability)
  Repo.link "orbit-coder-1"    OperatedBy.mk "did:web:orbit"
  Repo.link "orbit-reviewer-7" OperatedBy.mk "did:web:orbit"
  Repo.link "nw-etl-3"         OperatedBy.mk "did:web:northwind"
  Repo.link "helix-audit-2"    OperatedBy.mk "did:web:helix"
  Repo.link "did:web:acme"  (Partners.mk d) "did:web:northwind"
  Repo.link "did:web:acme"  (Vouches.mk "code" 9000 now) "orbit-coder-1"
  Repo.link "orbit-coder-1" (Endorses.mk "code.review" 8000 now) "orbit-reviewer-7"
  -- tasks 41, 42, 43 and their Requested / AssignedTo / Delegates / Attests edges likewise

The timestamp and date are parameters so the seed stays pure and runs the same in #eval on MemM and against a LadybugDB file. Note the field name stamp rather than at: at is a Lean keyword.

Lifting the Ladybug types to the next level

ladybug-lean already makes the shape of the data a type. The next step is to make the meaning a type: which string is an agent and which is a company, which integers are valid weights, which task transitions are legal, and which records carry evidence. Each level below is ordinary Lean, sitting between the storage rows and the reasoning layer.

The rule of thumb is simple. Storage types stay flat, so LadybugDB can hold them. Domain types are refined, so the program cannot hold nonsense. A lift function is the only bridge, and it can fail.

Level 1: role-indexed identifiers

In storage, a DID is a String. In the domain, an agent’s DID and a company’s DID must never be confused, so we index the type by role:

inductive Role | company | agent

structure DID (r : Role) where
  val : String
  deriving BEq, Hashable, Repr

abbrev CompanyId := DID .company
abbrev AgentId   := DID .agent

def Company.ref (c : Company) : CompanyId := ⟨c.did⟩
def Agent.ref   (a : Agent)   : AgentId   := ⟨a.did⟩

A function vouch : CompanyId → AgentId → … now rejects swapped arguments at compile time. The index costs nothing at runtime.

Level 2: refined weights with proved arithmetic

A weight is an Int32 in storage. In the domain it is a natural number that cannot exceed 10,000, and chaining two weights must stay in range:

abbrev Bp := { n : Nat // n ≤ 10000 }

def Bp.ofInt32? (w : Int32) : Option Bp :=
  let n := w.toInt
  if h : 0 ≤ n ∧ n.toNat ≤ 10000 then some ⟨n.toNat, h.2⟩ else none

/-- Trust through one more hop: the scaled product. -/
def Bp.chain (a b : Bp) : Bp :=
  ⟨a.val * b.val / 10000,
    calc a.val * b.val / 10000
        ≤ 10000 * 10000 / 10000 := Nat.div_le_div_right (Nat.mul_le_mul a.property b.property)
      _ = 10000 := rfl⟩

/-- Trust never grows along a chain. -/
theorem Bp.chain_le_left (a b : Bp) : (a.chain b).val ≤ a.val := by
  show a.val * b.val / 10000 ≤ a.val
  calc a.val * b.val / 10000
      ≤ a.val * 10000 / 10000 := Nat.div_le_div_right (Nat.mul_le_mul_left _ b.property)
    _ = a.val := Nat.mul_div_cancel _ (by decide)

chain_le_left is a small theorem with a large consequence: no sequence of endorsements can manufacture more trust than the first-hand vouch it started from. A Sybil ring of agents endorsing each other at 100 % can never lift an agent above the first-hand vouch the ring hangs from.

Level 3: typestate tasks

In storage, status is a string. In the domain, the status is a type index, and the lifecycle is a set of functions whose types allow only legal moves:

inductive Status | requested | assigned | delivered | accepted | disputed
  deriving DecidableEq, Repr

def Status.parse? : String → Option Status
  | "requested" => some .requested | "assigned" => some .assigned
  | "delivered" => some .delivered | "accepted" => some .accepted
  | "disputed"  => some .disputed  | _ => none

structure TaskAt (s : Status) where
  id  : Nat
  cap : String

def assignTo   (t : TaskAt .requested) (_ : AgentId)   : TaskAt .assigned  := ⟨t.id, t.cap⟩
def deliver    (t : TaskAt .assigned)                  : TaskAt .delivered := ⟨t.id, t.cap⟩
def acceptWork (t : TaskAt .delivered) (_ : CompanyId) : TaskAt .accepted  := ⟨t.id, t.cap⟩
def dispute    (t : TaskAt .delivered) (_ : CompanyId) : TaskAt .disputed  := ⟨t.id, t.cap⟩

/-- A stored row lifts to a task at *some* status, or fails. -/
structure SomeTask where
  status : Status
  task   : TaskAt status

def Task.lift? (t : Task) : Option SomeTask := do
  let s ← Status.parse? t.status
  pure ⟨s, ⟨t.id.toInt.toNat, t.cap⟩⟩

Accepting a task that was never delivered does not type-check. Writing back is a typed Repo.update that stores the index as text again.

Level 4: records that carry their own evidence

The top level is a dependent record: a value that cannot exist unless its invariant holds. An assignment the system is allowed to act on carries the trust it computed, the threshold it met, and a proof that it met it:

structure CheckedAssignment where
  requester : CompanyId
  agent     : AgentId
  task      : TaskAt .assigned
  trust     : Bp
  threshold : Bp
  meets     : threshold.val ≤ trust.val

def CheckedAssignment.mk? (r : CompanyId) (a : AgentId) (t : TaskAt .assigned)
    (trust threshold : Bp) : Option CheckedAssignment :=
  if h : threshold.val ≤ trust.val then some ⟨r, a, t, trust, threshold, h⟩ else none

In section 7 we add one more field, evidence, whose type is the trust judgment exported from the LF layer. At that point the record does not just say the agent is trusted; it holds a kernel-checked derivation of why.

The bridge to the logic

lean-elpi moves values across the boundary when they are plain data: inductive types and structures with Type parameters, no indices, and plain fields. DID .agent is indexed and Bp is a subtype, so neither crosses as-is, and that is the point. We define a flat logic view that derives Elpi, and lift into it from storage:

import Elpi
open Elpi

inductive Verdict | ok | rejected
  deriving Elpi

inductive Fact where
  | operatedBy (agent company : String)
  | partners   (a b : String)
  | vouches    (company agent cap : String) (bp : Nat)
  | endorses   (src dst cap : String) (bp : Nat)
  | capParent  (child parent : String)
  | hasCap     (agent cap : String)
  | requested  (company : String) (task : Nat)
  | taskCap    (task : Nat) (cap : String)
  | assigned   (task : Nat) (agent : String)
  | delegates  (src dst : String) (task : Nat)
  | attests    (company : String) (task : Nat) (v : Verdict)
  | revoked    (agent : String)
  deriving Elpi

#elpi_signature Fact   -- shows the ELPI kind and constructor names

The storage layer, the domain layer and the logic view are three types for one fact, each strict about something different. The diagram below shows the ladder.

[embed: node/e6ceb935-6af8]

Every arrow up the ladder is a function that can fail; the side path flattens storage into terms the logic can read and brings back a proof.

Layer 2: the ontology in λProlog

The ontology layer turns flat facts into a typed vocabulary with rules: a capability lattice, principals, and integrity constraints that must have no solutions. It runs in lean-elpi, which type-checks every clause against declared kinds and modes when the program loads.

Facts are data, one predicate holds them

deriving Elpi gave us an ELPI kind for Fact with one constructor per Lean constructor. Rather than one predicate per edge type, a single predicate holds every fact as a term:

% declared by `deriving Elpi` on the Lean side (confirm names with #elpi_signature):
%   kind fact type.
%   type vouches  string -> string -> string -> int -> fact.
%   type endorses string -> string -> string -> int -> fact.
%   ...

pred fact o:fact.

% rendered from a graph snapshot, one clause per edge
fact (operatedBy "orbit-coder-1" "did:web:orbit").
fact (vouches "did:web:acme" "orbit-coder-1" "code" 9000).
fact (endorses "orbit-coder-1" "orbit-reviewer-7" "code.review" 8000).
fact (capParent "code.review" "code").
fact (requested "did:web:acme" 42).
fact (taskCap 42 "code.review").
fact (assigned 42 "orbit-coder-1").
fact (delegates "orbit-coder-1" "orbit-reviewer-7" 42).
fact (attests "did:web:acme" 41 ok).

Because facts are terms, rules can pattern-match on them, collect them and, later, add them hypothetically. The type checker still rejects fact (vouches "acme" 42 "code" 9000) at load time, since the agent position is a string.

The capability lattice

Capabilities form a hierarchy. An endorsement for code covers a task that needs code.review, but not one that needs data.etl:

% reflexive-transitive closure of capParent
pred sub-cap i:string, o:string.
sub-cap C C.
sub-cap C P :- fact (capParent C Q), sub-cap Q P.

% an endorsement for Endorsed covers a task needing Needed
pred covers i:string, i:string.
covers Endorsed Needed :- sub-cap Needed Endorsed, !.

The cut in covers turns a search into a check: we want to know whether the endorsement covers the need, not every path that shows it.

[embed: node/e7d73f29-0e1f]

covers "code" "code.review" succeeds by walking the highlighted edge; covers "code" "data.etl" has no path and fails.

Principals as derived classes

Classes that are not stored can be derived. A company is anything that operates an agent or requests work; that is a rule, not a column:

pred agent   o:string.
pred company o:string.
agent A   :- fact (operatedBy A _).
company C :- fact (operatedBy _ C).
company C :- fact (requested C _).

Integrity constraints as a typed vocabulary of problems

An ontology earns its keep when it can say what is wrong. Constraints are rules whose solutions are violations, and the violations themselves are typed terms:

kind problem type.
type weight-out-of-range string -> string -> problem.   % src, dst
type revoked-assignee    int -> string -> problem.      % task, agent
type self-endorsement    string -> problem.
type delegation-cycle    int -> string -> problem.      % task, agent

pred violation o:problem.
violation (weight-out-of-range C A) :- fact (vouches C A _ W), (W < 0 ; W > 10000).
violation (weight-out-of-range B A) :- fact (endorses B A _ W), (W < 0 ; W > 10000).
violation (revoked-assignee T A)    :- fact (assigned T A), fact (revoked A).
violation (self-endorsement A)      :- fact (endorses A A _ _).
violation (delegation-cycle T A)    :- fact (delegates A B T), deleg-reach T B A 5.

pred deleg-reach i:int, i:string, i:string, i:int.
deleg-reach T X X _.
deleg-reach T X Y Fuel :- Fuel > 0, F1 is Fuel - 1, fact (delegates X Z T), deleg-reach T Z Y F1.

A healthy snapshot is one where violation P has no solutions. That is a query we can run in CI on every snapshot, and the answers come back to Lean as values of a derived type if we mirror problem with elpi_data.

The lattice and the derived classes are the ontology. The rules that decide trust sit on top of them, and that is where higher-order logic starts to pay.

Higher-order reasoning: where λProlog earns its place

First-order Datalog can compute reachability. What it cannot do directly is treat a policy as a value, pass a predicate as an argument, reason under a hypothetical fact, or quantify over a fresh agent nobody has seen. λProlog does all four natively, and each one answers a real question about agent cooperation.

1. Trust with decay, collected and folded

Trust flows from a company’s first-hand vouch through endorsements, losing weight at each hop, skipping revoked endorsers, and staying inside the capability that was endorsed:

% first-hand trust: a vouch that covers the need, or the company's own agent
pred direct i:string, i:string, i:string, o:int.
direct Co A C W      :- fact (vouches Co A P W), covers P C.
direct Co A _ 10000  :- fact (operatedBy A Co).

% trust through endorsements, with decay and a fuel bound
pred trust i:string, i:string, i:string, i:int, o:int.
trust Co A C _ W :- direct Co A C W.
trust Co A C Fuel W :-
  Fuel > 0, Fuel1 is Fuel - 1,
  fact (endorses B A P WE), covers P C,
  not (fact (revoked B)),
  trust Co B C Fuel1 WB,
  W is WB * WE div 10000.

% the best path wins: collect every derivation, project the weight, fold with max
pred best-trust i:string, i:string, i:string, o:int.
best-trust Co A C Best :-
  std.findall (trust Co A C 3 _) Sols,
  std.map Sols (s\ w\ s = trust _ _ _ _ w) Ws,
  std.fold Ws 0 (w\ acc\ m\ m is max w acc) Best.

The last rule is the first taste of higher-order programming. std.map takes a λ-term s\ w\ … that destructures each solution, and std.fold takes a λ that combines weights. The arithmetic mirrors Bp.chain on the Lean side, so the theorem chain_le_left describes what this rule computes.

For the running example, best-trust "did:web:acme" "orbit-reviewer-7" "code.review" W gives W = 7200: Acme’s 9,000 vouch for the coder, times the coder’s 8,000 endorsement.

2. Policies are λ-terms

A requester’s acceptance rule is not code buried in a service. It is a term of a declared kind, built from combinators, and one of those combinators carries a predicate:

kind policy type.
type min-trust      int -> policy.                         % best trust ≥ N
type min-reputation string -> int -> policy.               % ≥ N accepted deliveries in a family
type not-revoked    policy.
type own-or-partner policy.                                % run by the requester or a partner
type all-of         list policy -> policy.
type any-of         list policy -> policy.
type such-that      (string -> prop) -> policy.            % any predicate on the agent
type under          string -> policy -> policy -> policy.  % capability under Root ? P : Q

pred accept i:policy, i:string, i:string, i:string.        % policy, requester, agent, capability
accept (min-trust N) Co A C        :- best-trust Co A C W, W >= N.
accept (min-reputation F N) _ A _  :- reputation A F R, R >= N.
accept not-revoked _ A _           :- not (fact (revoked A)).
accept own-or-partner Co A _       :- fact (operatedBy A Op), (Op = Co ; fact (partners Co Op)).
accept (all-of Ps) Co A C          :- std.forall Ps (p\ accept p Co A C).
accept (any-of Ps) Co A C          :- std.exists Ps (p\ accept p Co A C).
accept (such-that F) _ A _         :- F A.
accept (under Root P Q) Co A C     :- if (sub-cap C Root) (accept P Co A C) (accept Q Co A C).

pred reputation i:string, i:string, o:int.
reputation A F N :- std.findall (delivered-ok A F _) L, std.length L N.

pred delivered-ok i:string, i:string, o:int.
delivered-ok A F T :-
  fact (assigned T A), fact (taskCap T TC), sub-cap TC F,
  fact (requested Co T), fact (attests Co T ok).

Three things here are higher-order. such-that stores a function from agents to propositions inside a data structure, and accept simply applies it with F A. all-of and any-of hand a λ to std.forall and std.exists. And under passes whole goals to if, which is itself a predicate over propositions.

Acme’s policy reads like its procurement rules:

pred acme-policy o:policy.
acme-policy (all-of [
  not-revoked,
  such-that (a\ not (fact (endorses a a _ _))),          % no self-endorsement
  under "security"
    (all-of [min-trust 9000, own-or-partner])            % security work: strict
    (any-of [min-trust 7000, own-or-partner])            % everything else
]).

3. Policies are programs over policies

Because policies are terms, a rule can rewrite them. tighten raises every trust threshold by a margin and copies everything else, including the λ inside such-that, untouched:

pred tighten i:int, i:policy, o:policy.
tighten D (min-trust N)   (min-trust M)    :- !, M is min 10000 (N + D).
tighten D (all-of Ps)     (all-of Qs)      :- !, std.map Ps (tighten D) Qs.
tighten D (any-of Ps)     (any-of Qs)      :- !, std.map Ps (tighten D) Qs.
tighten D (under R P Q)   (under R P1 Q1)  :- !, tighten D P P1, tighten D Q Q1.
tighten _ P P.

Note std.map Ps (tighten D) Qs: a partially applied predicate passed as an argument. The query “who could still do task 42 if Acme raised every bar by 500?” is acme-policy P, tighten 500 P P2, may-perform P2 42 A. The coder (9,000) passes; the reviewer (7,200 against 7,500) does not.

4. Delegation: trust does not transfer silently

When an agent sub-contracts a task, the requester’s policy must accept every agent on the chain, not just the first one:

pred may-perform i:policy, i:int, o:string.
may-perform P T A :- performer P T 3 A.

pred performer i:policy, i:int, i:int, o:string.
performer P T _ A :-
  fact (requested Co T), fact (taskCap T C), fact (assigned T A), accept P Co A C.
performer P T Fuel B :-
  Fuel > 0, Fuel1 is Fuel - 1,
  performer P T Fuel1 A, fact (delegates A B T),
  fact (requested Co T), fact (taskCap T C), accept P Co B C.

With Acme’s policy, may-perform P 42 A answers orbit-coder-1, then orbit-reviewer-7.

5. Hypotheticals: what breaks if an agent is revoked?

The implication D => G proves G with the clause D added for that proof only. That makes counterfactual questions one rule long, with no copy of the database and no cleanup:

pred breaks-if-revoked i:string, i:policy, o:int, o:string.
breaks-if-revoked X P T A :-
  may-perform P T A,
  (fact (revoked X) => not (may-perform P T A)).

pred blast-radius i:string, i:policy, o:list (pair int string).
blast-radius X P L :- std.findall (breaks-if-revoked X P _ _) Sols,
  std.map Sols (s\ r\ sigma T A\ s = breaks-if-revoked _ _ T A, r = pr T A) L.

Revoking orbit-coder-1 breaks both performers of task 42: the coder fails not-revoked, and the reviewer loses its only trust path and its delegation link at the same time. Revoking orbit-reviewer-7 breaks only the reviewer. This is the question a security team asks after a key compromise, answered before anyone touches the graph.

[embed: node/72231b0d-fa45]

The right panel exists only for the duration of one proof: the => adds the revocation, may-perform is re-run, and the graph itself never changes.

6. Universal checks over fresh agents

pi a\ G proves G for a brand-new constant a that no fact mentions. That lets us test a policy, not an agent:

% soundness: an agent nobody knows is rejected
pred stranger-proof i:policy, i:string, i:string.
stranger-proof P Co C :- pi a\ not (accept P Co a C).

% liveness: an agent the requester vouches for strongly is accepted
pred vouch-sufficient i:policy, i:string, i:string.
vouch-sufficient P Co C :-
  pi a\ fact (vouches Co a C 9500) => accept P Co a C.

Acme’s policy passes both for code.review. A sloppy policy such as any-of [not-revoked, min-trust 9000] fails stranger-proof, because not-revoked alone admits rogue-9 and every other stranger. And vouch-sufficient on Acme’s policy fails for security.audit, because the strict branch also demands own-or-partner: the check catches the rule being stricter than its authors meant, before any real agent is turned away.

These two predicates are the λProlog version of property tests, except that the “random” agent is a logical eigenvariable, so a success is a proof for every agent the graph says nothing about.

The answers in the table are worked out by hand from the rules and the running example; run them with #elpi to confirm in your build.

Layer 3: certified trust with LF and the Lean kernel

The λProlog layer finds answers; the LF layer makes one of them checkable. In the Edinburgh Logical Framework a judgment such as “Acme trusts the reviewer for code review” is a type, each rule is a constant, and a derivation is a term. lean-elpi records that term during search, exports the signature to Lean inductives, and asks the kernel to accept the result as a theorem.

The trust signature

We generate one LF file per snapshot. The vocabulary and rules are fixed; the constants and facts come from the graph, with DIDs turned into identifiers:

#lf
principal  : type.
capability : type.

% constants from the snapshot
acme : principal.   coder1 : principal.   reviewer7 : principal.
code : capability.  code_review : capability.

% judgments are types
parent  : capability -> capability -> type.
sub     : capability -> capability -> type.
vouch   : principal -> principal -> capability -> type.
endorse : principal -> principal -> capability -> type.
trusted : principal -> principal -> capability -> type.

% the snapshot's facts are constants of those types
p_review           : parent code_review code.
v_acme_coder1      : vouch acme coder1 code.
e_coder1_reviewer7 : endorse coder1 reviewer7 code_review.

% rules are constants whose types are inference rules (premises solved left to right)
sub_refl  : sub C C.
sub_up    : sub C P <- parent C Q <- sub Q P.
t_vouch   : trusted Co A C <- vouch Co A P <- sub C P.
t_endorse : trusted Co A C <- endorse B A P <- sub C P <- trusted Co B C.

The premise order in t_endorse matters for search: with the agent known, endorse B A P finds the endorser first, so the recursive premise always has its arguments bound. If you reorder premises, switch on #strategy iddfs and iterative deepening still finds the proof.

From query to theorem

import Elpi
open Elpi.Cmd

lf_signature trustlf "snapshots/2026-10-31/trust.lf.elpi"

#lf_query trustlf lp%{ trusted acme reviewer7 code_review }%
-- prints a proof term built from t_endorse, e_coder1_reviewer7, t_vouch,
-- v_acme_coder1, sub_up, p_review and sub_refl

lf_export trustlf
lf_certify trustlf reviewer7_trusted lp%{ trusted acme reviewer7 code_review }%

#print axioms reviewer7_trusted   -- expected: does not depend on any axioms

[embed: node/19c52658-d7db]

Every leaf is either a fact from the snapshot or sub_refl; the kernel re-checks each step against the exported inductive types.

lf_export writes Lean inductives for the signature: the base types become inductive types, and each judgment becomes an inductive proposition with one constructor per rule or fact. lf_certify translates the proof term into a Lean term and asks the kernel to accept it. If the kernel rejects it, the command reports the error and adds nothing. Soundness rests on the kernel alone, not on the λProlog engine, not on the generator, and not on the graph database.

The exact names of the exported namespace and constructors follow lf_export‘s conventions (for a signature called stlc it generates the namespace Stlc and capitalised families such as Of). Below we write Trustlf.Trusted; confirm with #print.

What the certificate covers, and what it does not

The LF derivation certifies the path: which vouch, which endorsement, which capability subsumption. Two parts of the trust rules live outside it on purpose:

  • Weights. The certificate does not multiply basis points. The Lean side recomputes the weight along the certified path with Bp.chain and proves the threshold with decide. Because the arithmetic is on Nat literals, the kernel checks that too.

  • Revocation. LF has no negation as failure. The generator leaves the endorsements of revoked agents out of the signature, so a certificate can only use edges that were live in that snapshot. The snapshot date is part of the file path, which makes the claim honest: trusted as of this snapshot.

The fully lifted record

Now the top of the type ladder can be finished. The generator also writes a small Lean file mapping each LF constant back to its DID, so the record can tie the proof to the stored identifiers:

-- generated with the snapshot
def Trustlf.Principal.did : Trustlf.Principal → String
  | .acme => "did:web:acme" | .coder1 => "orbit-coder-1" | .reviewer7 => "orbit-reviewer-7"

structure CertifiedAssignment extends CheckedAssignment where
  requesterLF : Trustlf.Principal
  agentLF     : Trustlf.Principal
  capLF       : Trustlf.Capability
  sameReq     : requesterLF.did = requester.val
  sameAgent   : agentLF.did = agent.val
  evidence    : Trustlf.Trusted requesterLF agentLF capLF

def bp (n : Nat) (h : n ≤ 10000 := by decide) : Bp := ⟨n, h⟩

def reviewerOn42 : CertifiedAssignment where
  requester   := ⟨"did:web:acme"⟩
  agent       := ⟨"orbit-reviewer-7"⟩
  task        := ⟨42, "code.review"⟩
  trust       := (bp 9000).chain (bp 8000)          -- 7200, computed by the kernel
  threshold   := bp 7000
  meets       := by decide
  requesterLF := .acme
  agentLF     := .reviewer7
  capLF       := .code_review
  sameReq     := rfl
  sameAgent   := rfl
  evidence    := reviewer7_trusted

This value cannot be built with a wrong DID, a weight above 10,000, a threshold the trust does not meet, a task that is not in the assigned state, or a trust claim without a derivation. Every one of those mistakes is a type error. That is what “lifting Ladybug types to the next level” means in practice: the row from LadybugDB becomes a record whose existence is the proof of its own invariants.

If the exported judgment carries a context index (as it does for signatures with hypothetical premises, like the λ-calculus example in the lean-elpi book), the evidence type takes that context as its first argument.

Wiring it together: snapshot, reason, certify

The running system is a loop with two speeds. At request time it snapshots the graph, loads the facts next to the rules, and answers in milliseconds. In an audit job it writes the same snapshot as an LF signature and lets lake build certify the decisions that matter.

Step 1: snapshot the graph into the logic view

The snapshot is generic over MonadGraph, so it runs on the in-memory backend in tests and on LadybugDB in production. Rows that fail to lift are not silently dropped; they are reported:

structure Snapshot where
  facts  : Array Fact
  errors : Array String

def snapshot {m : Type → Type} [MonadGraph m] : m Snapshot := withReadTx do
  let mut facts : Array Fact := #[]
  let mut errors : Array String := #[]
  for (c, a, k, w) in ← runQuery vouchRows do
    match Bp.ofInt32? w with
    | some b => facts := facts.push (.vouches c a k b.val)
    | none   => errors := errors.push s!"vouch {c} -> {a}: weight {w}"
  for (s, d, k, w) in ← runQuery endorseRows do
    match Bp.ofInt32? w with
    | some b => facts := facts.push (.endorses s d k b.val)
    | none   => errors := errors.push s!"endorse {s} -> {d}: weight {w}"
  for (s, d, t) in ← runQuery delegationRows do
    facts := facts.push (.delegates s d t.toInt.toNat)
  for a in ← Repo.findWhere Agent fun a => a.revoked ==. lit true do
    facts := facts.push (.revoked a.did)
  -- operatedBy, partners, capParent, hasCap, requested, taskCap, assigned, attests:
  -- one typed query each, same pattern
  return ⟨facts, errors⟩

Step 2: render facts and run the rules

Facts become clauses through one total function, so adding a constructor to Fact without a rendering is a compile error:

def q (s : String) : String := "\"" ++ s ++ "\""   -- DIDs are validated on lift

def Verdict.render : Verdict → String
  | .ok => "ok" | .rejected => "rejected"

def Fact.toClause : Fact → String
  | .operatedBy a c  => s!"fact (operatedBy {q a} {q c})."
  | .partners a b    => s!"fact (partners {q a} {q b})."
  | .vouches c a k w => s!"fact (vouches {q c} {q a} {q k} {w})."
  | .endorses s d k w => s!"fact (endorses {q s} {q d} {q k} {w})."
  | .capParent c p   => s!"fact (capParent {q c} {q p})."
  | .hasCap a k      => s!"fact (hasCap {q a} {q k})."
  | .requested c t   => s!"fact (requested {q c} {t})."
  | .taskCap t k     => s!"fact (taskCap {t} {q k})."
  | .assigned t a    => s!"fact (assigned {t} {q a})."
  | .delegates s d t => s!"fact (delegates {q s} {q d} {t})."
  | .attests c t v   => s!"fact (attests {q c} {t} {v.render})."
  | .revoked a       => s!"fact (revoked {q a})."

/-- trust.elpi = the `kind`/`type` lines printed by #elpi_signature Fact,
    followed by the rules of sections 5 and 6. -/
def rulesSrc : String := include_str "trust.elpi"

def reason (s : Snapshot) (goal : String) (limit := 20) : IO (Array String) := do
  let src := rulesSrc ++ "\n" ++ "\n".intercalate (s.facts.toList.map Fact.toClause)
  match Program.load src with
  | .error e => throw (IO.userError s!"{e}")
  | .ok prog =>
    let mut out := #[]
    for r in ((solve prog goal).toList.take limit) do
      match r with
      | .ok sol  => out := out.push s!"{sol}"
      | .error e => throw (IO.userError s!"{e}")
    return out

The program is loaded once per snapshot and is an immutable value, so many queries can run against it. If your orchestrator is not written in Lean, the same trust.elpi and rendered facts load through the Python, Node.js or Rust bindings (pip install leanelpi) with the same answers.

Step 3: one program, two backends

def decide42 {m : Type → Type} [MonadGraph m] [MonadLiftT IO m]
    (now : Timestamp) (d : Date) : m (Array String) := do
  seed now d
  let s ← snapshot
  unless s.errors.isEmpty do throw (IO.userError s!"lift errors: {s.errors}")
  reason s "acme-policy P, may-perform P 42 A"

-- tests and the editor: pure in-memory graph
-- #eval (decide42 now d : MemM _).run' {}

-- production: a LadybugDB file
def main : IO Unit :=
  Ladybug.withDatabase "trust.lbug" fun db => db.withConnection do
    IO.println (← decide42 (← nowTs) (← today))

Here nowTs and today stand for however you produce a Timestamp and a Date, and the MonadLiftT IO m constraint is the assumption that lets the pure reasoning call run inside the graph monad; adapt it to how your backend lifts IO. ladybug-lean’s differential suite checks that MemM and LadybugDB agree on query results, so the facts, and therefore the answers, match.

Step 4: certify in the audit job

The audit job turns the same snapshot into three generated files and builds them:

  1. 1.

    snapshots/<date>/trust.lf.elpi, the signature of section 7, with constants named from DIDs and the endorsements of revoked agents left out.

  2. 2.

    Snapshot<date>/Map.lean, the constant-to-DID functions such as Trustlf.Principal.did.

  3. 3.

    Snapshot<date>/Cert.lean, one lf_certify per decision to certify, plus the CertifiedAssignment values.

lake build then either succeeds, meaning every certified decision has a kernel-checked derivation, or fails at the first decision that does not. Run it on each snapshot, or only for high-stakes capabilities such as security and payments, and keep the build output as the audit record.

Step 5: guard the rules themselves

The policy checks from section 6 make good CI tests, because they are about the rules rather than the data:

/-- Each entry must have at least one solution (or none, when `expect := false`). -/
def policyChecks : List (String × Bool) :=
  [("acme-policy P, stranger-proof P \"did:web:acme\" \"code.review\"", true),
   ("acme-policy P, vouch-sufficient P \"did:web:acme\" \"code.review\"", true),
   ("violation X", false)]

def checkPolicies (s : Snapshot) : IO Unit := do
  for (goal, expect) in policyChecks do
    let found := !(← reason s goal (limit := 1)).isEmpty
    unless found == expect do
      throw (IO.userError s!"policy check failed: {goal}")

Run checkPolicies on a fixture snapshot in CI, with one entry per capability family and per requester policy. A pull request that weakens a policy so that strangers get in, or tightens it so that a strong vouch no longer suffices, fails before it merges.

What we gained, and where the edges are

The result is a trust graph where each layer is strict about one thing and hands a typed value to the next. LadybugDB stores and searches. ladybug-lean makes the schema and every query a compile-time contract. The lifted Lean types make illegal states unrepresentable. λProlog searches with policies, hypotheticals and fresh agents as first-class citizens. The kernel checks the derivations we choose to certify.

Honest limits

  • Certificates are qualitative. The LF layer certifies the derivation path; weights are re-proved in Lean. Bridged functions in LF currently return Nat, which is enough for basis points but means the decay is not inside the LF judgment.

  • Snapshots, not live truth. A certificate is valid for the snapshot it was built from. Revocation after that time needs a new snapshot, which is why the snapshot date is part of the path.

  • Negation lives in λProlog. not and revoked checks are negation as failure over a closed snapshot. The LF layer handles them by leaving revoked edges out of the signature, not by proving a negative.

  • Policies stay on the λProlog side. elpi_data refuses higher-order constructors such as such-that (string -> prop), so policies are not Lean values. Lean can still hold them as reflected terms, or a first-order fragment of the policy language can be mirrored with elpi_data.

  • Fuel bounds. Trust and delegation search use fuel (3 hops) to guarantee termination over cyclic graphs, the same design choice as ladybug-lean’s mandatory max on variable-length paths.

Where to take it next

  1. 1.

    Time. Add validity intervals to Vouches and Endorses and make trust a function of the snapshot instant, in the spirit of causal temporal event graphs.

  2. 2.

    Promises. Model a task as a promise from agent to requester and attestations as assessments of kept promises, so reputation becomes a typed history rather than a count.

  3. 3.

    Totality. Use #mode and #total on the LF signature, so lf_export also proves that sub is defined for every capability in the snapshot.

  4. 4.

    Hybrid retrieval. Use ladybug-lean’s vector and full-text indexes to find candidate agents by task description, then let the policy decide which of them may act.

The pattern generalises beyond trust. Any domain where a learned component proposes and an institution must be able to say why (credit, compliance, clinical routing, supply chains) fits the same three layers: typed storage, higher-order rules, and checked evidence.

Sources

Originally published on Sovereign Agentic AI on Substack.