System architecture¶
This note describes the wider system built around the packages of this
repository: termbank, the judgment_core kernel, judgment_shell, the
theory packages scalar and judgment_nat, the public judgment facade,
and the optional judgment_search and judgment_store. The current
implementation contracts are in the implementation reference;
the theory is normative for the mathematics.
The integration contracts list the contracts between
components and their normative pages. A system workflow described here does
not imply that its engines or CAS interface are implemented; the
capabilities page states what the packages supply.
The examples below are language-neutral design notation. Consult the generated API reference for callable Mojo APIs.
Reading guide¶
| Topic | Sections |
|---|---|
| Core constraints | 1.3, 1.4 |
| Architectural decision and alternatives | 1–2 |
| Logical model, proof functions, and trust | 3–5 |
| Isabelle, Lean, Rocq, and the choice of foundation | 6–7 |
| Storage, guards, contexts, and constructive composition | 8–11 |
| Orchestration, examples, and invariants | 12–14 |
| Two layers: native mathematics and profile conventions; type definitions, overloading, and classes | 15–16 |
| Source-reference requirement, licenses, and upstream implementation map | 6.5 |
| Concrete baseline, types, syntax, and context methods | 17–19 |
| Kernel checking, theorem/guard algorithms, and goal scheduling | 20–22 |
| Engine protocol, equality workspace, and conversions | 23–25 |
| Persistence, errors, acceptance tests, and validation contracts | 26 |
| Packages, pins, contracts, and assembly | 27 |
| The interface with Isabelle/HOL: translation, tiers, OpenTheory, the second auditor, run-time requests | 28 |
| Package and interface validation | 29 |
| Balancing rigor and efficiency: where and when proofs are checked | 30 |
| Symbolic normalization, rule libraries, Rubi, and certified algorithms | 31 |
| Mathematical scope: abstract theories, polynomials, and special-function classes | 32 |
| Open specification work and conclusion | 33–34 |
1. Purpose and architectural decision¶
The proposed system is a proof-producing symbolic reasoning core with contextual, relation-aware transformations. Its durable unit of mathematical knowledge is a checked judgment, not membership in an e-class.
The core represents mathematical knowledge as checked, context-indexed judgments and reusable guarded theorems. Reasoning engines construct and compose evidence for those judgments. Equality saturation is an optional strategy for exploring equivalent representations, while contextual e-graphs serve as specialized equality indexes rather than the logical foundation of the system.
A judgment has the form
where \(\mathcal T\) is the declared logical and semantic environment, \(\Gamma\) supplies scoped parameters and assumptions, and \(P\) is a proposition. Equality is an important instance, but not the only one. Definedness, inequalities, continuity, derivative relations, and certified error bounds must have the same standing as first-class mathematical claims.
A reusable guarded theorem has the form
For an equality theorem, the conclusion is \(t\simeq u\). The guard \(G\) is a sufficient condition, and \(\pi\) is evidence. Any compatible context that establishes \(G\) can apply the theorem. Its discovery layer is provenance, not the definition of its validity.
Author and compose theorems as proof-transforming functions; store them as immutable, shared proof graphs. Guards and support labels index applicability. Goals and derivations organize unfinished reasoning. Specialized engines provide simplification, normalization, relational inference, arithmetic reasoning, congruence closure, and optional equality saturation.
1.1 Architectural center¶
Judgments, contexts, and proof-producing transformations define the system's knowledge. Equality saturation is an optional engine that proposes results and evidence. Its workspace can be replaced without changing the meaning of a checked theorem. Whether saturation is useful for a particular CAS operation is a workload question.
1.2 Scope of this note¶
This document records the proposed architecture, mathematical model, data structures, design discussion, alternatives, and specification boundaries. It incorporates implementation ideas from Isabelle, Lean 4, and Rocq/Coq without committing to reproduce any one proof assistant or its full logical foundation. Its logical core follows Isabelle/HOL's conventions and imports its library (section 15), without reproducing Isabelle's Pure framework, tactics, or tools.
The native implementation remains ordinary Mojo; the logical contracts do not require the host language to implement dependent types. The Isabelle component of section 28 is a separate Isabelle/Scala artifact, not a dependency of the native packages. All code fragments are typed, language-neutral design pseudocode, not compiled Mojo, Scala, or ML. Sections 17–32 specify data shapes, package contracts, methods, and algorithms; exact native syntax, wire encodings, and ABI belong to the implementation reference and the component specifications. No algorithm here is claimed to have been implemented, formally verified, or benchmarked merely because it appears in this note.
1.3 Core constraints¶
| Constraint | Detailed in |
|---|---|
| Kernel conversion includes beta, let, permitted transparent unfolding, declared ACU, and supported literal arithmetic. Distributivity and assumption-sensitive rewriting require theorems. | 7.2, 18.2, 20.5, 20.6 |
| The scalar profile uses extended complex values and makes domain conditions explicit in conditional answers. User symbols are session constants. | 3.1, 17.2, 19.2, 25.2 |
| Returned, stored, and exported results cross a checking boundary; search may share provisional proof recipes inside a request. | 5, 12.5, 22, 24.3, 30 |
| The logic uses polymorphic simple types, conservative definitions, and explicit contexts. Propositional extensionality belongs to the core; classical principles and function extensionality belong to profiles. | 16–20 |
| Applications use n-ary spines. Raw termbank syntax does not rewrite; the kernel builds canonical checked terms. | 18.2 |
| Trust follows package boundaries and admitted axioms. Algorithms propose evidence; only checked evidence establishes a judgment. | 27, 30.6 |
| Rule libraries require proofs or explicitly tracked imports. Numeric testing can reject a proposed rule but cannot admit one. | 31.3 |
| Mathematical structures and domain conditions can be expressed through types, predicates, and guarded theorems. | 32 |
1.4 Integration boundaries¶
The imported HOL layer and the CAS scalar layer remain distinct; bridge theorems relate their operations under guards. Type definitions, specifications, overloading, and classes support HOL-shaped theories. The separate Isabelle bridge owns extraction and translation. Imported statements retain their trust and provenance; replayed derivations are checked by judgment. The integration contracts describe the current package and evidence boundaries.
2. Abstraction boundaries and alternatives to an e-graph-centered core¶
2.1 Separate logic, storage, and search¶
An e-graph, a proof calculus, and a proof assistant answer different architectural questions. E-graphs compactly represent known congruence relationships; equality saturation grows a representation of equivalent forms through inference. Neither distinction determines the logical meaning of the inference rules themselves. 8
| Question | Appropriate abstraction |
|---|---|
| What does a statement mean, and what counts as evidence? | A logical calculus and declared semantic theory. |
| How is established knowledge represented? | Checked judgments, guarded theorems, and proof objects. |
| How are unfinished obligations organized? | Goals, constraints, candidate derivations, and dependencies. |
| How are known equalities queried efficiently? | Congruence closure, possibly maintained by contextual e-graphs. |
| How are equivalent expressions explored? | Rewriting, normalization, equality saturation, and other candidate generators. |
| How is a useful result selected? | An explicit transformation objective and a validity-constrained selection strategy. |
Encoding a proposition as a term equal to True can be a useful engine representation. It is not a substitute for explicit scope, quantification, evidence, unfinished obligations, or the distinction between different mathematical relations.
The architectural issue is therefore not that e-graphs cannot participate in a proof-producing CAS. It is that an e-class is too specialized to be the universal unit of knowledge.
2.2 Candidate reasoning architectures¶
The following alternatives can coexist behind one proof-producing interface. The table describes proposed roles and tradeoffs, not measured rankings for this project.
| Architecture | Main search representation | Proposed use | Tradeoff |
|---|---|---|---|
| Proof-producing rewriting | A term DAG, indexed directed rules, and transformation proofs. | Routine simplification with a preferred normal form. | Commits to directions and intermediate forms; alternative routes need explicit search. |
| Goal-directed proof search | An AND/OR graph of obligations and candidate derivations. | Guard discharge, theorem application, and structured reasoning. | Solving a goal does not by itself optimize the resulting expression. |
| Relational inference with constraints | Fact relations, joins, dependency indexes, and incremental deltas. | Forward propagation of facts over many expressions. | Equality still benefits from specialized congruence machinery. |
| SMT-style cooperating engines | Contextual facts, congruence classes, constraints, and branches. | Equality, arithmetic, theorem instantiation, and case analysis in one session. | Symbolic candidate generation and output selection remain separate responsibilities. |
| Clause-based theorem proving | Indexed clauses and inference records. | Difficult quantified obligations and lemma discovery. | Its natural output is a proof, not necessarily a useful CAS expression. |
| Equality saturation | E-classes with alternative expression nodes. | Exploration where several equivalent intermediate representations interact. | May generate more alternatives than the requested transformation needs. |
Directed simplification and cooperating congruence-based reasoning are both useful proof-assistant patterns; the Lean simplifier and grind illustrate that they need not be competing choices for the entire system. 16
2.3 Recommended organizing abstraction: judgments and derivations¶
The primary coordinator should maintain a graph of goals and candidate derivations. A goal is a judgment to establish. A derivation is a rule application whose premises jointly justify a conclusion. This is a hypergraph because one inference can require several input judgments.
Premises of one derivation form an AND; alternative derivations of the same goal form a search-level OR. That OR is not an object-level disjunction theorem. It means that the coordinator can try more than one way to establish the same proposition.
Context-changing rules require particular care: the premises of implication introduction, universal generalization, or case elimination may live in different local contexts. A derivation edge therefore records its premise judgments and scope transformations, not just a list of propositions in one ambient context.
The coordinator can use forward relational inference to discover facts and backward theorem search to generate obligations. E-graphs remain available inside this organization rather than being replaced with naive pairwise equality edges.
2.4 The central tradeoff¶
A generic proof graph is not automatically an efficient equality engine. Replacing e-graphs with it everywhere could merely reimplement congruence closure and equality-aware sharing less efficiently. Conversely, requiring every transformation to run saturation would force simple or well-structured tasks through unnecessary representation search.
The chosen direction separates the concerns: a general judgment-and-derivation core, with specialized engines selected according to the task. Performance and result quality must be evaluated before changing the default equality-search strategy.
3. Logical model and terminology¶
| Symbol or term | Meaning |
|---|---|
| \(\mathcal T\) | A declared logical and semantic environment: sorts, symbols, axioms, definitions, and permitted certificate checkers. |
| \(\Gamma\), \(\Delta\) | Logical contexts containing scoped parameters and assumptions. |
| \(G\) | A sufficient guard under which a theorem's conclusion holds. |
| \(P\) | A proposition; an equality is one kind of proposition. |
| \(\pi\) | A proof of a stated judgment, with explicit hypothesis and theory dependencies. |
| Guarded theorem | A checked proof of \(G\Rightarrow P\), possibly universally quantified over term parameters. |
| Support | A finite conjunction of obligations sufficient for a retained derivation. |
| Support label | A collection of alternative sufficient supports for a conclusion. |
| Judgment | A scoped claim together with the theory and context needed to interpret it. |
| Goal | A judgment requested but not yet established. |
| Candidate derivation | A possible inference, its premise goals, scope transitions, and proof recipe. |
| Workspace | Derived solver state for a reasoning session; not a source of logical authority. |
| Layer | A materialized contextual congruence inside an optional equality workspace. |
A guard describes what a theorem requires. A context describes what a particular reasoning session assumes. The same proposition syntax may appear in both roles, but their roles are not interchangeable.
The notation
denotes a derivation with parameters and open assumptions supplied by \(\Gamma\). A reusable theorem closes proposition assumptions by implication introduction. For a finite list of such assumptions over an explicit parameter interface, this yields
within that parameter interface. Term parameters are generalized separately when the calculus permits it. Context export must preserve this distinction; a context is not merely an unscoped set of printed proposition strings.
3.1 Equality has a declared meaning¶
The core must not equate “same mathematical value where both happen to be defined” with domain-preserving equality. For strict pointwise CAS semantics, the intended relation is
when, for every environment satisfying \(\Gamma\), the expressions have the same definedness and, when defined, the same value. The exact treatment of exceptional values belongs to the declared theory.
For example, over ordinary real expressions with partial division,
is valid, while the corresponding unconditional identity is not. Equality in a rational-function field is a different semantic interpretation and must be declared as such.
Congruence is available only for operators whose declared semantics respect the chosen equality. Overloaded printed notation does not automatically identify operators from different theories.
The default profile and generic answers. In the scalar profile of section 17.2, every operation is total on a carrier of extended complex values, and "defined" means "finite". The strict equality above is then ordinary kernel equality on that carrier. Generic simplifications such as x/x → 1 are theorems guarded by finiteness conditions (x ≠ 0 for a finite x). By default the CAS returns them as conditional results whose extra guards are only such conditions, accepted by the request's policy and displayed when the user asks. A strict request instead requires evidence for every guard.
3.2 Evidence is not a Boolean¶
An entailment query has an epistemic outcome: established, refuted, or unknown. Unknown means that neither direction has been established by the service; it is not evidence of negation.
For a proposition \(P\), the conceptual outcomes are:
Entailed(proof_of_P)
Refuted(proof_of_not_P)
Unknown(dependencies, versions, resource_reason)
An inconsistent context is reported separately. Although a logic with contradiction elimination can derive any proposition from inconsistency, this must not be presented as an ordinary successful CAS result under meaningful assumptions.
4. Theorems as proof-transforming functions¶
Under propositions-as-types, an implication \(G\Rightarrow P\) is represented by a function from evidence for \(G\) to evidence for \(P\). This is the Curry–Howard interpretation used for implication in Lean. 1
For example:
div_self:
(x: Real) ->
Proof(x ≠ 0) ->
Proof(x / x ≃ 1)
The nonzero argument is a proof, not a Boolean that authorizes the rewrite. This distinguishes proof search from theorem application:
prove_nonzero(context, x) -> Evidence(x ≠ 0) | Unknown
apply_div_self(x, nonzero_evidence) -> Evidence(x / x ≃ 1)
Proof search may be expensive or unsuccessful. Applying a checked theorem to well-formed evidence requires no additional proof search, although checking and constructing the application still have computational costs.
4.1 Joint premises compose by conjunction¶
Given
transitivity constructs
Its proof-transforming interpretation is
Likewise, congruence combines the guards of the argument equalities. A rule application includes the support of every premise used to establish that application—not merely the side conditions written explicitly in the rulebook.
4.2 Alternative proofs compose by disjunction¶
Given
disjunction elimination constructs
alternative(evidence_for_disjunction):
eliminate evidence_for_disjunction:
left(h1): use π1(h1)
right(h2): use π2(h2)
This is a logical eliminator. It does not require a runtime procedure that decides arbitrary propositions, nor does it require proof evidence to remain computationally inspectable after proof erasure.
An OR-shaped guard annotation is not sufficient by itself: the system must retain or construct evidence for the corresponding implication.
4.3 Reuse in a new context is precomposition¶
Given
the theorem can be specialized by
which proves \(\Delta\Rightarrow P\).
For example,
can be used under \(x>10\) by composing it with a proof of \(x>10\Rightarrow x\ne0\). The original theorem is neither copied conceptually nor rewritten to depend permanently on \(x>10\).
The logical requirement is evidence of the guard, not an ancestor relationship between storage layers.
5. Trust boundary: functions author proofs; the kernel checks them¶
A mathematical proof function and an arbitrary Mojo function are different objects. A host-language function can loop, fail, inspect mutable state, or construct malformed data. Its host-language signature is not, by itself, evidence of a theorem about arbitrary runtime propositions.
The proposed boundary is an LCF-style opaque checked-theorem interface, with retained proof objects. In the LCF tradition, a small trusted kernel controls theorem construction while larger automation remains outside it. 2
Untrusted automation
|
v
Proof candidate
|
v
Small proof kernel
|
v
Opaque checked theorem
The kernel checks inference rules, scope, substitutions, statement types, and declared theory dependencies. A checked theorem means derivable relative to those declarations; it does not establish the consistency or intended interpretation of every client-supplied axiom.
The system may support both checked certificates and explicitly trusted declarations. Their dependencies must be visible. Re-running an external computation is not independent mathematical verification of that computation.
This is a small proof language for the engine, not a commitment to implementing a complete dependent type theory. Proposition-indexed notation such as Proof(P) describes the logical contract; an implementation can enforce it dynamically through opaque handles and a kernel.
Checked judgments and closed theorems use the same evidence discipline. An engine may construct tentative proof recipes or work with speculative state, but an unchecked candidate is not an established premise. Validation may occur at a composite-proof boundary; accepted knowledge and externally justified results cannot depend on trusting unverified solver state.
Where the boundary is. The boundary is the edge of a request: a returned answer, an entry into a durable or shared store, an export. Within one request, engines may exchange provisional facts that carry proof recipes; the kernel checks the proof of whatever leaves the request. Section 30 states the conditions under which this is sound, its risks, and the evidence labels every result carries.
What a checked judgment rests on. Every dependency of an accepted judgment belongs to one class, and every label lists the classes it uses (K31):
| Class | Dependencies | Why it may be trusted |
|---|---|---|
| Core | the logic core's one axiom, propositional extensionality | true in every topos |
| Profile axioms | a semantic profile's axioms (scalar's G1–G7), classical principles |
each profile proves its axioms consistent; scalar's are later theorems of a model in HOL (section 15.4) |
| Literal kinds, ACU | the laws they cite | the cited laws are theorems or profile axioms; conversion adds no logical strength (section 20.5) |
| Definitions | constant definitions, type definitions, specifications, instance definitions, class predicates | each preserves models (sections 16.2, 16.3); none adds logical strength |
| Instances | instance declarations | each cites the theorem proving its class predicate (section 16.4) |
| Imported statements | theorems of the pinned Isabelle release, used without a kernel-checked proof | proved by Isabelle's kernel and translated faithfully; each names its source (section 28.4) |
| External claims | uncertified answers of external deciders, entered as hypotheses | not trusted: they stay in the statement until discharged |
| Checkers | admitted certificate checkers, if any | each admitted explicitly, with a soundness argument (section 7.4) |
A replayed Isabelle proof has no class of its own: it is a kernel derivation like any other. The numeric filter of section 31.3 is not a class: it never admits anything.
6. Implementation ideas from Isabelle, Lean 4, and Rocq¶
The proposal borrows implementation boundaries and algorithms, not an entire proof assistant. The systems have different logical foundations and should not be treated as interchangeable instances of constructive type theory.
| Source | Most relevant ideas | Proposed adaptation |
|---|---|---|
| Isabelle | Abstract theorem values, certified syntax, theory/proof-context separation, context export, and conversions. | Organize durable knowledge and scoped transformations. |
| Lean 4 | Elaboration to explicit core syntax, distinct variable classes, metavariable goals, theorem indexes, and cooperating automation. | Organize rule compilation, scoped search, and solver cooperation. |
| Rocq/Coq | Reflection, certified algebraic computation, denominator obligations, and generalized rewriting. | Give mathematical domains dedicated algorithms and relation-aware transformation contracts. |
| E-graph and relational research | Congruence closure, shared alternatives, equality-aware matching, and incremental inference. | Keep efficient specialized workspaces behind the common evidence interface. |
6.1 Isabelle: the closest organizational model¶
Isabelle separates ordinary terms, certified terms and types, theorem values, background theories, and local proof contexts. Its thm type is abstract, while cterm and ctyp represent syntax certified relative to a theory. This is a useful model for separating syntax construction, well-formedness checking, and established mathematical knowledge. 9
Checked theorem values. An engine that establishes a fact should publish a checked theorem, not mutate an authoritative global equivalence relation. An equality workspace may consume the theorem and update its own representation. The theorem remains meaningful independently of that representation.
Theory versus proof context. The logical environment records declarations, definitions, and admitted principles. The proof context records local parameters and assumptions. Solver queues, indexes, caches, and union-finds belong to neither semantic definition. Isabelle's theory and context infrastructure provides a concrete precedent for maintaining these distinctions. 10
Context export. A result established in an inner context can be exported by discharging its local assumptions and, when valid, generalizing its local parameters. Isabelle provides explicit mechanisms for this operation. 10 For this core, the corresponding inference is
The generalization step must obey the calculus's side conditions: a local parameter cannot simply be generalized while its dependencies remain hidden in undischarged assumptions. The exact representation of context interfaces and dependency order belongs in the specification.
This turns a local reasoning session into a reusable theorem function. It is not an operation that copies a context's union-find into an ancestor. Nor does it automatically discover a globally weakest guard; support minimization remains a separate, evidence-bearing optimization.
Conversions. In the LCF tradition, a conversion transforms a term and produces an equality theorem; Isabelle provides conversion combinators and a conversion interface to simplification. 12 Our generalized version is
A directed rewrite, polynomial normalizer, substitution procedure, or saturation run can all satisfy this contract. The algorithm is interchangeable; the meaning of its output is not.
Persistence and replay. Abstract checked handles protect construction within a process. Retained proof DAGs additionally support serialization, replay, trust inspection, and cache-independent checking. The proposed core uses both; it does not assume that an opaque in-memory handle alone supplies a portable certificate.
Proof DAGs are stored rows: every checked judgment is a proof row of termbank.dag with its conclusion, context, dependency summary, and home theory (DAG storage), and a proof library publishes its declarations and the proofs of its exported theorems, with the rows they reach (ST9). The stored proof rows are the portable evidence of a stored result: every load of a library, and Library.recheck, checks them again with the current checker and no search engine, for audit or after a kernel fix (Proposition B-6). No recipe, replay record, or certificate row is stored; a statement-only import, which trusts the library's producer, is the one result kept without its proof (ST9.8).
6.2 Lean 4: explicit syntax and scoped proof search¶
Lean separates elaboration of rich syntax and tactic execution from kernel checking of the resulting core expressions. This provides a useful model for convenient mathematical rule authoring backed by a small, explicit checking language. 13
A rule such as sqrt(x²) = x provided x ≥ 0 should elaborate into fully identified operators, typed parameters, guard propositions, substitutions, and proof obligations. The kernel should not interpret that convenience syntax or trust the elaborator's choice of meaning.
Distinct variable classes. Lean's expressions distinguish bound variables, uniquely identified local free variables, and metavariables used during elaboration; unresolved metavariables are not kernel-level proof evidence. Its expression representation also records cached structural information. 14 The proposed core should distinguish at least:
BoundVariable
ContextParameter
DeclaredConstant
PatternParameter
SearchMetavariable
These may share storage machinery but must not share substitution rules accidentally. Bound variables in integrals and sums, free parameters with the same printed name, and unknown expressions being synthesized are different entities.
A checked theorem contains no unresolved search holes. A metavariable belongs to an explicit local context, and a proposed assignment may use only the parameters and hypotheses allowed by that context. Capture avoidance and prevention of escaping local variables are kernel or elaboration obligations, not printing conventions.
Goals and theorem indexes. Lean's discrimination-tree infrastructure provides a model for retrieving theorem candidates by expression shape. 15 Such an index answers, “Which theorem conclusions might solve this goal?” The relational matcher answers a different question: “Which combinations of known facts instantiate this multipremise theorem?” Both are useful; neither should be forced to simulate the other universally.
Cooperating engines. Lean's grind combines congruence closure, propagation, E-matching, case analysis, and specialized reasoning while producing Lean proofs. 16 The implementation lesson is not to clone its complete tactic interface, but to let several engines exchange justified facts within a reasoning session. A proof-assistant-style architecture and congruence closure are compatible.
The local logic profile must still control classical reasoning. A solver based on contradiction or classical case splitting must expose the required principles in its output evidence rather than silently extending a constructive fragment.
6.3 Rocq: certified computation and generalized rewriting¶
Rocq's ring machinery illustrates reflection: expressions are represented as data, normalized computationally, and related to their meanings by correctness theorems. Its field reasoning also generates nonzero obligations for denominators. 17
For this project, the important pattern is to prove a normalizer correct once, then instantiate that correctness theorem for individual expressions. An alternative implementation uses an untrusted fast normalizer that emits a certificate for a small checker. Both approaches can avoid recording a large collection of elementary distributivity and reassociation rewrites.
The trust bridge must be explicit. A theorem about a mathematical algorithm is not automatically a theorem about unrelated Mojo code that purports to implement it. Either connect the executable computation to the checked algorithm, or validate the concrete result with evidence whose checker has a declared soundness contract.
Rocq's generalized-rewriting machinery also supports declared relations and proofs that functions respect those relations. 18 This motivates a relation-aware core rather than one universal equality relation. Exact equality, inequalities, refinement, set inclusion, and error bounds can all be propositions, while only suitable equivalence relations are materialized through union-find.
The next section develops these mathematical contracts; they are not requests to build all algebra into the generic kernel.
6.4 What is deliberately not being copied¶
The core does not inherit a proof assistant's full tactic language, universe hierarchy, type-class mechanism, evaluator, theorem library, or semantic conventions merely because it borrows an implementation pattern. These remain separable decisions. The integration adopts two of them for Isabelle/HOL: its type-class mechanism becomes a kernel mechanism (section 16), and its theorem library is imported, with its conventions, into the logical core (sections 15 and 28). Its tactic language and evaluator are not adopted, and the CAS keeps the profile's specified semantics.
In particular, Lean's dependent type theory, Rocq's calculus, and Isabelle's Pure framework are not the same foundation. Isabelle's account separates simply typed terms and its proof framework, while Lean specifies a dependently typed core. 9 The proposed baseline remains a small explicitly specified logical framework until concrete CAS requirements justify more machinery.
6.5 Source-guided development is an explicit project requirement¶
Development should study and use the Isabelle and Lean 4 source code as primary implementation references, not stop at papers, manuals, or architectural analogies. Before designing a foundational component from scratch, inspect the relevant upstream implementation, identify the invariants it protects, and record how the Mojo design preserves or deliberately changes those invariants. Adapt or port suitable code when it is beneficial and the applicable license obligations are met. Source-guided development does not require a runtime dependency on either proof assistant.
The Isabelle core copyright file contains the three-clause BSD conditions; Lean 4's repository license is Apache License 2.0. These permit use and adaptation subject to their terms. Isabelle's official site also makes clear that its full distribution contains components under multiple licenses. A repository-level license is therefore not blanket permission to ignore a file's header or the terms of a bundled dependency. 22 24
License and provenance rules¶
| Situation | Project rule |
|---|---|
| Studying an algorithm and writing a fresh implementation | Cite the implementation studied and record the design correspondence. Do not claim the upstream implementation was ported or verified when it was only consulted. |
| Copying, translating, or adapting source, tests, or substantial comments | Treat the work as source-derived; inspect the exact files and pinned revision, preserve applicable notices, and record local modifications. Translation from ML, Lean, or C++ into Mojo does not erase provenance. |
| Isabelle core material under its BSD terms | Retain the copyright notice, conditions, and disclaimer; reproduce the required notices with binary distributions; do not imply upstream endorsement. 22 |
| Lean material under Apache 2.0 | Supply the license, retain applicable notices, identify modified files, and carry forward relevant upstream NOTICE attributions when present. The patent and trademark provisions remain applicable. 23 |
| Third-party components, other repositories, or differently licensed files | Review their own terms before copying. This requirement includes material reached through upstream dependencies; it does not infer Rocq's or any library's license from Isabelle's or Lean's. |
| Unclear provenance or incompatible redistribution requirements | Do not incorporate the material until the issue is resolved. An engineering attribution record is not a substitute for the applicable license. |
The project's own packages are licensed under the Apache License 2.0 with LLVM exceptions, like Mojo's standard library. Material under Isabelle's BSD terms or Lean's Apache 2.0 license can be incorporated into such packages when its notices and conditions are carried forward as the table above requires.
This is the project's development and redistribution policy, not a finding that every upstream file has already been audited. The present note contains original design pseudocode and source references, not an imported upstream implementation or a change to this project's license.
Reference map for implementation work¶
The entries below identify concrete starting points. Inspect the full relevant implementation and tests before a port; the map is not an audit of those modules. 26 28 30
| Our component | Upstream starting point | What to study and adapt |
|---|---|---|
| Certified syntax, theorem handles, primitive inference | Isabelle src/Pure/thm.ML |
Abstract interfaces, theory association, premise accounting, substitution, and theorem composition. |
| Scoped hypotheses and context export | Isabelle src/Pure/assumption.ML |
Assumption packages, inner/outer context validation, and export as proof transformation. |
| Proof-producing transformation combinators | Isabelle src/Pure/conv.ML |
Sequential composition, alternatives, traversal under binders, and equality-producing conversions. Our version adds guards, budgets, and explicit error categories. |
| Typed expression nodes and binder utilities | Lean src/Lean/Expr.lean |
Separate variable roles, expression metadata, and scope-sensitive operations. Do not copy Lean's complete dependent type system into the baseline by accident. |
| Search-variable ownership and substitution | Lean src/Lean/MetavarContext.lean |
Allowed local contexts, assignment ownership, nested search, and prevention of escaping variables. |
| Equality provenance and cooperating solvers | Lean src/Lean/Meta/Tactic/Grind/Types.lean |
Solver extension state and recording sufficient details to reconstruct noncircular congruence proofs. |
| Candidate lookup | Lean src/Lean/Meta/DiscrTree/Basic.lean, reached through its API source link |
Structural candidate filtering followed by real matching; no index lookup is itself a proof. 15 |
| Further theory/context and binder work | Isabelle src/Pure/context.ML, src/Pure/variable.ML, src/Pure/term.ML |
Persistent logical identities, parameter generalization, and capture-avoiding term operations. Verify paths at the chosen upstream revision. |
The source references 26–31 identify the upstream files they cite, most at a fixed revision. They are reference snapshots, not claims about a latest release or proof of semantic compatibility; a source-derived implementation pins the exact revision it uses.
For every source-derived component, maintain a record such as:
SourceReference:
upstream_project: String
repository_url: String
revision: ImmutableRevision
paths: List[SourcePath]
local_paths: List[SourcePath]
use_kind: Studied | Adapted | Translated | Copied
license_files: List[SourcePath]
retained_notices: List[SourcePath]
correspondence: String
intentional_changes: List[String]
validation_tests: List[TestId]
A source-derived component keeps such a record, and the distribution carries the copied license texts and required notices. A change review answers which upstream invariant was retained, which assumption was changed, and which test covers the change.
Native implementation remains the goal. Use standard Mojo facilities when they meet the requirement; do not port an upstream container merely because it exists. Borrow algorithms and invariants, adapting their physical layout to termbank's row storage and the workload of this project. External proof assistants may serve as development or differential-testing tools without becoming mandatory production dependencies. Separately, section 28 specifies the interface with Isabelle/HOL, an integration through exported theories and proofs; source consultation and runtime integration are distinct.
7. Logical foundation, relation-aware transformations, and certified computation¶
7.1 A small proof language before a full dependent type theory¶
The baseline needs typed expression syntax, scoped assumptions, quantifiers, declared relations, and proof constructors. This is sufficient to express theorem functions \(G\Rightarrow P\) and theorem schemas \(\forall x:A.\,G(x)\Rightarrow P(x)\) without committing to a general-purpose dependent type theory.
Full dependent types would add additional obligations. For example, terms of types \(\operatorname{Vector}(A,n)\) and \(\operatorname{Vector}(A,m)\) may require explicit transport along an equality of indices. Establishing \(n=m\) in a contextual e-graph does not by itself supply every type-transport justification. The later specification must either model such transports or explicitly restrict the initial type system.
The choice is therefore an Isabelle-inspired separation of terms, propositions, contexts, and theorems, with explicit proof terms and scoped goal machinery. Section 17 selects a simply typed baseline, and section 20 describes its primitive proof instructions. Their full formal soundness argument remains specification work.
7.2 Computational conversion is not CAS equivalence search¶
Proof assistants distinguish the computational equality built into their core language from propositional equalities established by proofs. Lean's description of definitional equality provides the relevant model. 19
If the chosen calculus includes lambda abstraction, a rule such as
may be part of its computational conversion. An identity such as
instead requires the appropriate algebraic interpretation and evidence.
The kernel must not invoke arbitrary CAS simplification, contextual saturation, or a budget-sensitive heuristic to decide its own definitional equality. Its conversion rules need an explicit soundness and operational contract. Context-independent syntax normalization is likewise distinct from an assumption-sensitive mathematical transformation.
The kernel supports two context-independent, decidable additions to conversion, each justified by declarations the kernel validates: equality modulo associativity, commutativity, and units for constants a theory declares ACU, and literal arithmetic for declared literal kinds. Both identify only terms that are provably equal from the declared theorems (the ACU laws and the literal laws), so they add speed and shorter proofs, not logical strength. (a+b)^2 = a^2+2ab+b^2 still needs evidence: distributivity is not part of conversion. Section 20.5 specifies the algorithm.
7.3 The core accepts relations; equality engines require extra structure¶
A generalized conversion can return
where \(R\) is a declared relation. To rewrite inside an operator, the engine needs evidence that the operator respects the relevant relations. For example,
For multiple arguments, the corresponding morphism theorem includes all required input relations. Ordinary equality congruence is a special case. This follows the design principle behind generalized rewriting, rather than assuming that every operator is compatible with every relation. 18
Error bounds demonstrate why a universal union-find is inappropriate. Over a declared real or metric setting,
The bound changes during composition. “Within a fixed tolerance” is not generally transitive and cannot safely be treated as exact class membership. Inequalities and refinement relations may also be directional rather than symmetric.
An equality workspace is therefore enabled only for a relation with the required reflexivity, symmetry, transitivity, and operator-compatibility contract. Rewriting, bounds, and other relational reasoning need not be forced into that workspace.
7.4 Certified normalizers as first-class engines¶
A reflected polynomial normalizer can be specified schematically as
with an embedding \(\iota\) back to expression syntax and a correctness theorem
The declared domain and evaluator must be part of that theorem. For an individual expression, the engine uses the theorem with checked computation or validates a concrete normalization certificate. It need not enumerate an unconstrained saturation search over all equivalent polynomial forms. Rocq's ring and field tactics motivate this organization. 17
A rational-expression procedure additionally preserves definedness obligations under strict pointwise semantics:
The generic core supplies evidence-bearing interfaces. Algebraic algorithms, function interpretations, and specialized certificates belong to declared theory components.
B0 cannot use reflection. Rocq-style reflection defines the normalizer inside the logic and proves it correct by induction. The B0 kernel has no recursive definitions or induction principle (sections 17.1 and 19.1), so that route is not available. Certified computation in B0 therefore takes one of two forms:
- Certificates checked through the kernel. The engine emits a certificate whose checking reduces to kernel steps and conversion, including literal arithmetic. Checking a certificate should be much simpler than producing it: verify a factorization by multiplying, not by factoring.
- An admitted checker. A validator implemented in Mojo is an explicit, recorded extension of the trusted base. Prefer the first form; use the second only where measurements show the first is too slow.
7.5 Borrow algorithms without silently importing semantics¶
A proof-assistant library can use a different interpretation of a printed operation. For example, JudgmentMathlib's GroupWithZero convention includes an inverse of zero equal to zero. 20 That totalized operation is not identical to strict partial division.
Reusing a theorem across such interpretations requires a checked semantic bridge and the appropriate domain obligations. Printed operator names, matching syntax, or use of the same host implementation are not sufficient. The same discipline applies to complex branches, approximate arithmetic, and overloaded algebraic operations.
The system applies this discipline to Isabelle/HOL, whose library it imports: Isabelle's theorems are true of its totalized constants (\(x/0 = 0\) for every division_ring), and they reach CAS results only through bridge theorems whose guards exclude exactly the points where the native and profile conventions differ (section 15).
8. Logical stores, search state, and derived indexes¶
The system separates theorem storage, contexts, and unfinished reasoning into distinct owners.
| Store or structure | Contents | Architectural role |
|---|---|---|
| Theory/declaration store | Stable declarations, definitions, admitted principles, and compatibility relationships. | Interpret statements and identify logical dependencies. |
| Context store | Scoped parameters, assumptions, and context interfaces. | Define local judgments independently of solver workspaces. |
| Term/proposition bank | Immutable, shared mathematical syntax. | Stable identities for expressions and statements. |
| Proof rows | Immutable proof rows of termbank.dag, connected into directed acyclic graphs. |
Checkable evidence with shared subderivations. |
| Theorem table | Parameters, guard, conclusion, and checked proof. | Durable reusable knowledge, including non-equality facts. |
| Guard/support index | Factored formulas and selected sufficient supports. | Applicability queries and useful proof alternatives. |
| Goal/derivation graph | Pending judgments, candidate inferences, scoped premises, and dependencies. | Organize incomplete proof search without treating it as evidence. |
| Candidate-conversion store | Proposed output expressions, guards, relation claims, proofs or pending obligations, and objective costs. | Compare useful transformations without confusing utility with validity. |
| Specialized workspaces | Relational indexes, arithmetic state, congruence classes, and optional e-graphs. | Accelerate particular reasoning tasks. |
The logical records and the dependencies of retained proofs must survive disposal of derived search state. Indexes, candidate queues, and workspaces may be mutable and incomplete. Their incompleteness must not change the meaning of an accepted theorem. The table describes responsibilities, not a requirement for nine separate allocations, databases, or packages.
8.1 Stable syntax and scoped variables¶
Propositions can be stored in the shared termbank. A PropId may be a checked wrapper around a term identifier rather than an independent syntax representation.
A theorem refers to stable syntax identities, not merely the current roots of a mutable union-find. Indexes may use contextual representatives, but every replacement that affects the logical statement requires an equality proof connecting the original syntax to that representative.
For example, using a context-local equality \(x\simeq y\) to rewrite a theorem's guard from \(G(x)\) to \(G(y)\) requires proof transport. It must not silently produce a globally valid theorem about \(y\).
Variable identity includes scope: a context parameter is its binding site, the frame it extends, its type and its name. Two variables printed as x at different binding sites are not interchangeable. Bound variables, context parameters, pattern variables, and search metavariables have distinct roles. Section 18 selects de Bruijn indices for bound variables and binding sites for context parameters, and gives the capture-avoiding substitution contract. Term and proof hash-consing preserve these identities: two fixes of one name and type over one frame are one parameter.
8.2 The theorem table¶
A schematic record is:
Theorem:
theory: TheoryId
parameters: ParameterListId
guard: GuardId
conclusion: PropId
proof: ProofId
Its invariant is
The parameter list carries the sorts and scopes needed to interpret both the guard and conclusion. Equality theorems and ordinary fact theorems use the same representation.
TheoryId identifies the applicable declarations and semantic interpretation. Reuse in an extension requires a validated compatibility relationship; matching the printed names of declarations is insufficient.
An originating layer may be stored as optional provenance metadata, but is not required for the theorem's meaning. Trust-dependency summaries can be cached from the proof. They must not replace the dependency information needed to validate it.
8.3 Proof rows¶
Proofs are immutable tagged nodes referring to earlier or otherwise acyclic subderivations. A candidate instruction set is:
ProofNode =
Hypothesis(hypothesis_id, proposition)
| Reflexivity(term)
| Symmetry(proof)
| Transitivity(left_proof, right_proof)
| Congruence(head, argument_proofs)
| RuleInstance(declaration, substitution, premise_proofs)
| TheoremApplication(theorem_id, substitution, guard_proof)
| AndIntroduction(proofs)
| AndProjection(proof, index)
| OrIntroduction(side, proof)
| OrElimination(disjunction_proof, left_branch, right_branch)
| ImplicationIntroduction(hypothesis_id, body)
| ImplicationElimination(function_proof, argument_proof)
| FalseElimination(contradiction_proof, conclusion)
| Certificate(checker_id, payload)
This is the conceptual instruction vocabulary. Section 20 refines it into the B0 kernel instructions, including universal parameter instantiation, declared axioms, and computational conversion; the conceptual names here are not extra unchecked primitives. The implementation has no Certificate node: termbank.dag refuses certificate rows, and a certificate enters a proof only as data that an expander turns into checked steps (trusted base).
The physical representation is termbank.dag's: proof rows with compact ids in one commit sequence, operand columns for variable-length arguments, and exact deduplication of value rows (DAG storage). Repeated applications reference a shared theorem body rather than copying it. Hash-consing includes scope-sensitive data; it must not merge hypotheses merely because their proposition text is identical.
For example:
p0 = Hypothesis(h, x > 0)
p1 = RuleInstance(positive_implies_nonzero, x, [p0])
p2 = RuleInstance(div_self, x, [p1])
p3 = ImplicationIntroduction(h, p2)
Here p3 establishes \(x>0\Rightarrow x/x\simeq1\) within the real-number parameter context. Universally closing the term parameter produces the corresponding theorem schema.
Open proofs carry explicit hypothesis interfaces. Discharging one hypothesis does not discharge another occurrence with a different scope identity. Memoized proof checks must respect the theory, parameter, and hypothesis interface under which a node is valid.
The proof DAG is not itself an equality-saturated graph. A certificate remains a finite, well-founded derivation even when the search engine contains cycles.
8.4 Context and goal handles are not theorem handles¶
An assumption introduced in a context creates a scoped hypothesis, not an unconditional fact. A goal handle records work to be done, not evidence that its proposition holds. Theorems, hypotheses, pending goals, proof candidates, and checked results should therefore have distinguishable APIs even if their physical handles use the same integer width.
A context may be shared by several engines, and an engine may create several workspaces for one context. Their identities must not be collapsed merely for convenience. The logical context determines permitted assumptions; the workspace identity determines where a particular cache or search state lives.
9. Guard representation and support algebra¶
Two representations serve complementary purposes: a factored guard DAG preserves the theorem's condition, while a bounded support index accelerates finding useful applications.
9.1 Factored guards are the primary representation¶
Guard =
True
| False
| Atom(proposition_id)
| And(child_guard_ids)
| Or(child_guard_ids)
An atom denotes a proposition, not a truth-availability bit. Negation can initially be an explicit proposition inside an atom. In particular, an unset index entry for \(P\) does not establish \(\neg P\).
Hash-consed constructors can flatten AND and OR nodes, sort operands, remove duplicates, and use justified elementary simplifications. Factoring can preserve a compact condition such as
Changing the guard of a theorem requires proof adaptation. If a normalizer replaces \(G\) by \(G'\), it must supply the implication needed to use the old proof under \(G'\)—or a checked equivalence supporting both directions. Structural metadata normalization must not silently become a logical inference.
Guard interning may reuse the termbank's machinery. This is not complete normalization modulo arithmetic: \(x>10\Rightarrow x>0\) is a theory theorem, not a consequence of sorting guard operands.
9.2 Supports and antichains¶
A support is a finite set of obligation identities:
A label is a collection of alternative supports. For example,
represents the sufficient guard \((a\land b)\lor c\). Each retained support references a checked proof or a proof recipe that is checked before use, establishing \(\sem{S}\Rightarrow P\).
This follows the assumption-based truth-maintenance idea of associating conclusions with alternative supporting environments rather than only one active context. 3
For applicability, a support that strictly contains another support is redundant. A proof under \(a\land b\) can already be applied in a context that establishes \(a\land b\land c\). The minimal-support index therefore maintains an antichain under set inclusion.
Define \(\min_{\subseteq}\) to remove strict supersets and duplicate sets. Alternative derivations combine by
and joint premises combine by
The distinguished labels are
Here \(0\) means no retained support and \(1\) means an unconditional proof. The former is not evidence of the conclusion's negation. Its associated empty disjunction is a false sufficient guard, not a completeness claim about the conclusion.
With a fixed vocabulary of atomic obligations, these operations give an idempotent, absorptive support algebra. They track sufficiency, not proof counts or the identities of all derivations. The connection to relational provenance is that alternatives combine additively and joint dependencies multiplicatively; general semiring provenance studies that pattern for relational and Datalog inference. 4
9.3 Set subsumption is not full logical implication¶
The supports \(\{x>10\}\) and \(\{x>0\}\) are incomparable by set inclusion. Their logical relationship must be established by a theorem.
Replacing a support by a weaker guard requires a proof from that weaker guard to the conclusion. Knowing that the old guard implies the new one does not suffice. From a theorem under \(x>10\), one cannot infer the same theorem under \(x>0\) merely because \(x>10\Rightarrow x>0\).
Furthermore, logical redundancy and computational usefulness are different. A stronger guard may have a shorter proof, a faster certificate checker, or fewer trusted dependencies. The minimal-support applicability index can discard a redundant support while a separate proof-candidate collection retains its useful derivation.
The core does not promise a globally weakest guard. It stores proved sufficient conditions and may improve them through additional reasoning.
9.4 Physical representations and growth control¶
Small supports can use sorted ID arrays with inline storage. Larger or denser supports can use bitsets. The crossover threshold is a measurement question for the full specification.
Antichains must not be the only representation. The factored condition
has linear formula size but, over independent atoms, has \(2^n\) minimal conjunction supports. Eager expansion would lose the benefit of factoring.
| Representation | Proposed role |
|---|---|
| Factored guard DAG | Default persistent representation without mandatory expansion. |
| Bounded support antichain | Fast applicability and readable explanations. |
| Zero-suppressed decision diagram (ZDD) | Optional backend for large families of sparse supports. |
| Binary decision diagram (BDD) | Optional backend for workloads dominated by Boolean guard operations. |
BDDs represent Boolean functions and ZDDs represent families of sets; these are related but distinct representation tasks. 7 No polynomial-size guarantee is assumed for either backend. They are optional indexes, not additions to the trusted logical rules.
A bounded antichain is an under-approximation of the available proof opportunities, not a claim to contain all minimal supports. Dropping a complete alternative is safe for soundness. Removing a conjunct from a retained support is not safe without a new proof.
10. Contexts, entailment, and materialized congruences¶
10.1 Logical context identity is separate from layer identity¶
A context denotes scoped parameters and assumptions. An equality layer is a physical cache of equalities established under that context. A tree of sparse layered union-finds can remain the initial equality-materialization strategy; logical reuse does not require replacing it with an arbitrary graph of union-finds. A context exists and supports theorem application even when no equality workspace has been allocated for it.
If the engine establishes
then a theorem usable under \(\Gamma\) can be used under \(\Delta\). This relationship need not coincide with layer ancestry. Contextual equality-saturation research likewise treats stronger contexts as permitting more equalities over shared terms. 5
Context normalization can initially flatten, sort, and deduplicate conjunctions while preserving scope. Full canonicalization modulo the background theory is not an initial requirement.
10.2 Evidence maps and applicability indexes¶
Conceptual runtime indexes are:
ContextFacts:
(context_id, proposition_id) -> contextual_evidence_candidates
TheoremsByConclusion:
proposition_pattern -> theorem_ids
GuardWatchers:
obligation_pattern -> dependent_guard_nodes_or_instances
Ground instances can be keyed by proposition ID. Parameterized theorems require pattern matching and checked substitution, not an exact-ID lookup alone. Initially, guard watchers can be installed lazily for instantiated theorem candidates rather than enumerating every possible substitution.
When a context establishes a new fact, relevant guard nodes are reconsidered. Satisfying a conjunction requires evidence for all conjuncts. Establishing one disjunct is sufficient to satisfy a disjunction, but the engine must also accept a proof of the whole disjunction without requiring knowledge of a particular disjunct.
The applicability index accelerates finding evidence; it does not define the limits of the logic.
10.3 Demand-driven entailment¶
A structural match, a proposed conversion, or backward theorem search can generate a demanded obligation:
Need(context, instantiated_guard)
The entailment service attempts to establish it using known facts, analyses, relational inference, and theory procedures. A successful answer becomes evidence available to further matching. The support includes the context facts, argument equalities, and normalization steps actually used in the derivation.
Unknown answers may be cached, but retry dependencies include relevant facts, analysis versions, and solver state—not merely the e-class of the queried proposition. A changed resource allowance may also warrant retrying. Successful proofs are durable; failed search attempts are conditional on what information and resources were available.
No unproved validity condition authorizes a union in the current context. Such a candidate remains guarded, is deferred, or is applied in a child context explicitly assuming its guard. Search-only predicates such as “these classes have not yet merged” are not evidence of mathematical disequality.
10.4 The theorem bank and equality workspaces have different jobs¶
Once a theorem's guard is established in a context, application produces a contextual proof. For an equality conclusion, an active equality workspace can materialize a union justified by that proof. The result can also be consumed directly by another engine or returned to the caller without materialization.
Shared terms + theorem / conversion candidates
|
v
Guard obligations and evidence
|
v
Checked contextual result
|
+--> direct result or theorem reuse
+--> fact propagation and pending goals
+--> optional equality-workspace update
|
v
new matches and obligations
When present, a layered union-find remains a fast equality-query structure. The system does not require a theorem-graph search for every find operation and does not eagerly store a theorem for every pair of equal terms. Compound equality lemmas can be assembled or promoted when useful, with explicit evidence rather than reliance on the current partition alone.
The initial context model is monotone: strengthening assumptions may enable more results. Weakening or retracting assumptions requires a different context or validated reconstruction, not continued use of a contaminated monotone union-find. Dropping a workspace does not invalidate retained closed theorems whose logical dependencies remain available.
11. Constructive composition and explicit classical reasoning¶
The proof-composition core can be constructive without requiring all CAS theories to avoid classical axioms. The distinction is explicit evidence, not a ban on classical mathematics.
From
one obtains
An unconditional conclusion additionally needs a proof of \(p\lor\neg p\). That coverage may follow from decidability of the particular proposition or from a declared classical principle; it is not automatically available in constructive logic. 6
A general case eliminator therefore has the contract
cases(
coverage: Evidence(G₁ ∨ G₂),
branch₁: Evidence(G₁ → P),
branch₂: Evidence(G₂ → P)
) -> Evidence(P)
For piecewise results, coverage must refer to the domain requested by the caller. Branch-local assumptions are discharged through the eliminator rather than leaking into the parent context.
A Boolean index may use classical methods to propose candidates, but any result entering the kernel must be justified in the declared logic. Negation is never inferred merely from an absent support. Theory axioms, external certificates, and classical principles remain visible dependencies of the resulting theorem.
12. Three architectural layers and the reasoning coordinator¶
The logical architecture has three layers. These responsibility boundaries are realized through the separate packages in section 27; a logical layer may span several packages. The Isabelle component of section 28 is a separate process, not a fourth logical layer.
| Layer | Responsibility | Must not depend semantically on |
|---|---|---|
| Mathematical kernel | Check well-formed statements, inference steps, scope, theory compatibility, and admitted certificates. | Search order, solver budgets, unverified heuristics, or current union-find membership. |
| Theorem and derivation infrastructure | Retain proofs, checked judgments, guarded theorems, context exports, dependencies, and theorem indexes. | The workspace in which a theorem happened to be discovered. |
| Goal and fact coordinator | Manage requests, candidate transformations, obligations, facts, scheduling, and engine dependencies. | An assumption that one engine can solve every supported problem. |
12.1 The mathematical kernel¶
The kernel produces checked judgments with the conceptual interface
CheckedJudgment:
theory
context_interface
proposition
proof
The context interface records all parameters and assumptions on which an open result depends. Closed theorem export discharges or generalizes that interface according to the calculus. The kernel does not optimize expressions, perform saturation, or decide which theorem candidates to try.
Its soundness is relative to the declared axioms, semantic profiles, and trusted certificate validators. A small kernel is an engineering objective, not a reason to hide additional trust in unrecorded callbacks.
12.2 Theorem and derivation infrastructure¶
This layer stores durable evidence and supports reuse. The theorem bank retains
and a context can apply it using
Proof DAGs, stable statements, context export, theory identities, and guard indexes belong here. Structural indexes are derived accelerators; deleting an index does not delete the mathematical meaning of its entries.
A theorem can be used directly to answer a request, generate a new obligation, or activate a solver workspace. Passing through an e-graph is not a prerequisite for applying or exporting it.
12.3 Goals and candidate derivations¶
A candidate runtime representation is:
Goal:
theory: TheoryId
context: ContextId
proposition: PropId
evidence_policy: EvidencePolicyId
status: GoalStatus
candidate_derivations: Slice[DerivationId]
waiting_dependents: Slice[DerivationId]
retry_dependencies: DependencySetId
Derivation:
rule_or_theorem: DeclarationOrTheoremId
substitution: SubstitutionId
premise_goals: Slice[GoalId]
scope_transitions: ScopeTransitionId
proof_recipe: ProofRecipeId
GoalStatus = Open | Waiting | Candidate | Proved
These are the conceptual records; sections 20–23 give the concrete B0 fields, states, and methods. A failed attempt is recorded separately from a refutation. Evidence of \(\neg P\) is a checked result in its own right, not a failure status that can be manufactured by exhausting a budget. Context inconsistency likewise has a separate, evidence-bearing diagnostic.
The coordinator can deduplicate equivalent requests using theory, context, stable proposition identities, and evidence-acceptance policy. Proof candidates may be shared across policies, but a result is usable only when its transitive dependencies satisfy the requesting policy. Syntactic or alpha-normalized keys are an initial option. Merging more general logically equivalent requests requires justified transport; heuristic index collisions cannot identify their meanings.
A derivation's premises may use different contexts. For example, proving \(G\Rightarrow P\) introduces \(G\) in an inner context, while case elimination has separate branch contexts and a coverage premise. The proof recipe records those scope transitions explicitly.
Search cycles are permitted as dependencies, but do not establish themselves. A completed goal needs a finite checked proof. Incomplete proof recipes remain search objects, not theorem handles.
12.4 Forward facts and backward demands cooperate¶
A transformation or theorem candidate can generate Need(context, proposition). Backward search finds candidate theorems whose conclusions match that need. Forward relational inference derives consequences of facts already established. Both routes may activate theory solvers, and both publish evidence through the same checking boundary.
The coordinator should prefer cheap known evidence before expensive search, without making that order part of the logical meaning. Demand generation, watcher activation, caching, and incremental retry can be optimized independently of the kernel.
The engine catalog includes directed simplification, relational fact inference, arithmetic and definedness solvers, certified algebraic normalizers, contextual congruence closure, optional equality saturation, and optional external proof search. Installing an engine does not authorize new axioms: its accepted output must satisfy the declared proof or certificate contract.
12.5 Checked publication versus speculative search¶
An engine may work speculatively and submit a composite proof instead of checking every internal step immediately. Speculative candidates and checked facts must remain distinguishable.
Only checked judgments may become durable mathematical knowledge, justify a returned result, or be consumed as established premises outside the request that produced them. Within one request (section 30), engines may consume each other's provisional facts as search inputs, provided each carries a well-founded proof recipe; any proof that uses them is checked before its result leaves the request, and a failed check discards the result. Internal tentative merges must be isolated or carry the obligations needed for a subsequently checked proof. A workspace cannot make its own unsupported membership facts into proof premises.
The conceptual flow is:
CAS request + objective + context
|
v
Goal / fact coordinator
|
+--> directed rewriting and normalization
+--> relational and arithmetic reasoning
+--> contextual congruence closure
+--> optional equality saturation
+--> other proof-producing procedures
|
v
Proof / certificate checking
|
v
Checked theorem store
|
+--> evidence for pending obligations
+--> derived solver indexes and workspaces
+--> justified CAS result
12.6 Transformation and selection are separate from proof search¶
A goal such as \(\exists u.\,t\simeq u\) has the unhelpful witness \(u=t\). A useful CAS operation needs a candidate-generation strategy and an explicit objective, not just an existential equality goal.
The core transformation contract is schematically
where
Free parameters are universally closed or retained in an explicit parameter interface. In strict mode the result also supplies evidence \(\mathcal T;\Gamma\vdash G\). In conditional mode, the unresolved sufficient guard is returned explicitly. A relation-aware variant states the requested relation instead of equality. A piecewise result additionally includes coverage and branch evidence for the requested domain.
A transformation request may also stop without an improvement, return a checked identity fallback, or report an inconsistent context. A conditional candidate is not an unconditional success, and an exhausted budget is not a refutation.
Selection can optimize readability, evaluation cost, size, suitability for a subsequent operation, proof cost, or trusted dependencies. Validity is a constraint, not a cost that can be traded against a shorter expression. Tree and sharing-aware DAG extraction are separate strategies; a generic local node cost does not capture all global sharing choices.
12.7 Solver caches are disposable¶
The architecture must pass the following independence test:
Deleting every e-graph, union-find, matcher index, and solver cache leaves all retained theorem statements and proofs meaningful and checkable, provided their declared logical dependencies remain available.
Relevant workspaces can then be reconstructed from the retained theorems. Reconstruction need not reproduce the exact search history, intermediate representatives, or heuristic choices.
This does not require retaining every transient search candidate forever. It requires distinguishing disposable search state from dependencies of proofs chosen for retention.
13. Worked lifecycles and architectural consequences¶
13.1 The original guarded theorem, with optional materialization¶
Assume the declared theory supplies
A request arrives in context \(\Delta=(x>10)\) with expression \(x/x\).
Select and instantiate. Directed matching, backward theorem search, or an equality workspace selects \(\tau\) and binds its parameter to the request's scoped variable. The resulting obligation is \(x\ne0\). Any equality used in matching contributes its own proof dependencies.
Establish the guard. The coordinator obtains
from known facts or a proof-producing arithmetic engine.
Apply. Applying \(\tau\) to \(\eta\) establishes
The request can return this checked conversion immediately. If an equality workspace is active, the same theorem can also justify a contextual union. Materialization is optional; the proof does not depend on it.
Reuse elsewhere. A sibling context \(\Theta=(x<-5)\) can independently establish the guard and use the same theorem. No storage-ancestry relationship is required. The correct variable and theory identities must still be supplied.
Export. Context export discharges the assumptions used by a local derivation. Retaining the original theorem under \(x\ne0\) avoids making its validity depend permanently on the stronger discovery assumption \(x>10\). A newly exported proof is not assumed to have the globally weakest possible guard.
13.2 Rational normalization without mandatory saturation¶
Consider strict partial real expressions and
under \(\Gamma=(x>2)\), with the objective of a simpler expression.
A certified algebraic procedure proposes \(u(x)=x+1\) together with the theorem
The coordinator generates the obligation \(\Gamma\vdash x\ne1\). An arithmetic engine supplies evidence, and theorem application gives the strict result. No exploration of every factorized and expanded form is required.
Under a context that cannot establish \(x\ne1\), the same proposal remains a conditional result or the system preserves the original expression. At \(x=1\), the original is undefined under this semantic profile; the engine must not treat the unconditional equality as established merely because the polynomial numerator can be factorized.
An e-graph may still help if this expression is part of a larger problem with several competing forms. Its usefulness is an algorithmic question, not a prerequisite for the normalization theorem.
13.3 Alternatives, case coverage, and sibling reuse¶
Suppose the theorem bank contains
Proof composition yields
Replacing that guard by \(x\ne0\) requires the corresponding theorem of the declared real-number logic. It is not an operation on obligation IDs. The two search branches are not by themselves evidence that their conditions cover the requested domain.
For \(E(x)=\sqrt{x^2}+x/x\), real sign reasoning gives guarded candidates \(x+1\) for \(x>0\) and \(1-x\) for \(x<0\). A combined result under \(x\ne0\) can be expressed as \(|x|+1\) with the necessary proof. At \(x=0\), the strict original remains undefined. This exercises branch coverage, domain preservation, and support reuse without requiring the context tree to encode every logical implication.
13.4 Bounds are composed, not unioned¶
Suppose one certified procedure establishes \(|t-u|\le\varepsilon\) and another establishes \(|u-v|\le\delta\) under compatible guards and a declared real or metric interpretation. A composition theorem yields \(|t-v|\le\varepsilon+\delta\), with the joint guard and all required domain evidence.
The coordinator can manage this derivation exactly as it manages equality proofs. It must not merge \(t\), \(u\), and \(v\) into one exact e-class. The logical infrastructure is shared, while the relation-specific engine and composition theorem differ.
14. Core invariants and soundness target¶
| ID | Invariant |
|---|---|
| K1 — Evidence | Every accepted theorem has a checked derivation relative to its declared theory and explicit dependencies. |
| K2 — Scope | All term parameters and proof hypotheses are scoped. Closure discharges the specified hypotheses and no others. |
| K3 — Stable statements | Stored statements use stable syntax identities. Contextual representative changes require proof transport. |
| K4 — Guard discipline | A guarded conclusion becomes an established contextual fact only after its guard is proved there or explicitly introduced as a scoped assumption. |
| K5 — Complete dependencies | Matching, substitution, normalization, congruence, and oracle premises contribute their actual logical dependencies. |
| K6 — Support evidence | A retained support is sufficient only because a corresponding implication is proved; labels are not independent axioms. |
| K7 — Safe approximation | Budgets may drop opportunities or complete alternatives. They cannot remove a required premise without new evidence. |
| K8 — Well-founded proofs | Accepted certificates, including theorem-reference dependencies, are finite and acyclic. Search cycles do not establish their own premises. |
| K9 — Explicit coverage | Case lifting uses checked coverage and discharges branch-local assumptions. |
| K10 — Theory compatibility | Reuse respects operator semantics, types, branch conventions, and declaration compatibility. |
| K11 — Knowledge versus absence | Unknown facts and separate e-classes do not establish negation or disequality. |
| K12 — Proof-bearing output | A strict equality result includes a checked equality under the requested context; other transformations prove their declared relation, and conditional results expose their additional guards. |
| K13 — Workspace independence | Retained theorem statements and proofs remain meaningful and checkable after solver caches are deleted, provided their logical dependencies are retained. |
| K14 — Relation discipline | Only appropriate equivalence/congruence relations are materialized by equality workspaces; other relations use their declared composition and morphism rules. |
| K15 — Search versus logic | Candidate derivations, search-level alternatives, and failed attempts are not proof premises, disjunction evidence, or refutations. |
| K16 — Conversion boundary | Kernel computational conversion consists of α, β, ζ, δ, ACU for declared constants, and declared literal kinds (section 20.5). It does not depend on assumption-sensitive CAS search or heuristic saturation. |
| K17 — Scoped search holes | Checked theorems contain no unresolved search metavariables; assignments and exports respect their local interfaces. |
| K18 — Checked publication | Speculative engine state remains distinguishable from checked facts; crossing the accepted-knowledge boundary (a returned result, a durable or shared store, an export) requires validated evidence. Provisional facts with recipes may circulate only inside their own request (section 30). |
| K19 — Certified computation | Computed transformations are justified by a checked algorithmic connection, a sound certificate validator, or an explicit recorded trust dependency. |
| K20 — Handle integrity | Session and bank ownership, reference bounds, and workspace generations are checked (CG4); raw or serialized ids cannot manufacture checked objects. |
| K21 — Versioned validation | Cached checks and attempts respect their theory, scope, substitution, checker, and relevant state versions. |
| K22 — Stable evidence reconstruction | Congruence and matching explanations preserve the original endpoints, argument pairing, and well-founded premise evidence. |
| K23 — Atomic publication | A candidate becomes an accepted fact only after validation and compatibility checks; failed publication cannot expose a partial fact. |
| K24 — Package independence | Native foundational packages have explicit acyclic dependencies and remain usable without the coordinator, optional engines, or Isabelle. |
| K25 — Semantic interoperability | Every imported claim uses the pinned, versioned translation of its exact types, operators, sorts, and scope (section 28.3); it is a claim about the import theory's constants, never about the CAS layer's. |
| K26 — Evidence-policy isolation | Goals, fact views, contradictions, and equality workspaces use only evidence whose complete dependencies satisfy their acceptance policy. |
| K27 — Replayable imported evidence | An exporter's report or a server's answer is not authority; imported results enter as statements with provenance, or as proofs the kernel replays. |
| K28 — Import acyclicity | Imported and native theorem references cannot justify themselves through a cycle; a run-time request to Isabelle cannot delegate back to the goal that issued it. |
| K29 — Optional integration | The Isabelle interface and imported theories never silently add axioms, change semantic profiles, or become mandatory for native-only use. |
| K30 — Request confinement | Provisional state belongs to exactly one request: it is discarded when the request ends, never read by another request, and never written to a durable store. |
| K31 — Evidence labels | Every returned result states its checking level (checked or unchecked) and the classes of its dependencies (native rules, profile axioms, literal kinds, instances, imported statements with their sources). Unchecked results are never the default and never stored. |
| K32 — Justified conversion | Every conversion step corresponds to a kernel-validated declaration: a transparent definition, an ACU declaration with its theorems, or a literal kind with its admitted scheme. |
| K33 — Literal integrity | Accelerated literal operations produce canonical literals, may decline any input, and are tested against an independent reference implementation. |
| K34 — Deterministic replay | A run without wall-clock stops can be replayed exactly, so a proof omitted for speed can be reconstructed on demand. |
| K35 — Layer separation | No CAS-layer constant is defined as, or identified with, an imported constant; the two meet only in the model theory's definitions and in bridge theorems (section 15.8). |
| K36 — Bridge guards | Every rewrite across the layers uses a bridge theorem and carries its guard. |
| K37 — Provenance | Every imported statement names its prover, release, session, theory, and theorem, and appears in the label of every result that depends on it. |
| K38 — Proved statements only | A statement used without a kernel-checked proof is a theorem of the pinned Isabelle release, imported with its provenance; numeric evidence admits nothing. |
| K39 — Definitional discipline | A type definition cites its witness; instance definitions are orthogonal and their dependencies terminate; an instance declaration cites the theorem proving its class predicate (section 16). |
| K40 — Sort discipline | Every type substitution is admissible for the sorts it instantiates; sort hypotheses are recorded, and a Proven theorem's are witnessed (section 16.4). |
K32's literal scheme is not admitted: a LiteralKind cites theorems or axioms stating that its bound operations form an ordered commutative ring or an ordered field on its domain, and the scheme holds in every model of them (Theorem C-11).
K33's declining is restricted. An operation evaluates only where the cited laws determine its value and declines elsewhere: an inverse of 0; 0⁰, 0ⁿ for n < 0, non-integer exponents, and negative exponents of integers. A power also declines when its exponent exceeds 4096 in magnitude or a bound on its result exceeds the size ceiling. Whether an operation declines depends only on its inputs. Addition and multiplication never decline: when the actual result's encoding exceeds MAX_LITERAL_BYTES = 2²⁰ bytes, the call fails with a capacity error and builds no term.
The soundness target is:
Assuming the kernel's inference rules, certificate-validation contracts, and admitted theory interpretations are sound, every accepted strict equality result is equivalent to the input under the requested assumptions. Every other accepted relational result establishes its declared relation under its stated conditions. These claims are independent of engine selection, matching order, heuristic choices, and whether any search reaches saturation.
This is a target established through the kernel and engine contracts, not a claim that the implementation is formally verified. Union-find membership must not substitute for evidence when checking an exported result. A malformed search result should be rejected, not converted into a theorem by trusting the current graph.
Completeness, globally weakest guards, minimal proof size, and termination of unrestricted saturation are separate properties. None is an implicit consequence of the soundness target.
15. Two layers: native mathematics and profile conventions¶
The integration separates imported mathematics from CAS conventions. The logical core follows Isabelle/HOL: its number types, constants, definitions, names, and type classes are imported from a pinned Isabelle release, so that Isabelle's theorems are theorems here, word for word. The CAS layer follows the scalar profile: section 17.2 specifies its extended-complex values, including its infinities and indeterminate value. The two layers are connected by bridge theorems, proved in the kernel, each under a guard that excludes exactly the points where the conventions differ. No constant of one layer is ever identified with a constant of the other.
15.1 Why one layer cannot serve both¶
Isabelle/HOL, like every HOL system and judgment_mathlib, makes partial operations total by fixing values where mathematics leaves them open. The scalar profile assigns different values at some of those points, and the CAS follows the profile's definitions. The conventions conflict on concrete points (read from Isabelle2025-2's sources and checked numerically; the scalar theory page The HOL model and bridges gives the full table and proofs):
| Expression | Isabelle/HOL | The scalar profile |
|---|---|---|
| \(x/0\) | \(0\) (inverse_zero, an axiom of every division_ring) |
ComplexInfinity for \(x \ne 0\); Indeterminate for \(x = 0\) |
| \(0^0\) | \(1\) for the natural power; 0 powr 0 = 0 |
Indeterminate |
| \(0^a\), \(\mathrm{Re}\,a < 0\) | \(0\) | ComplexInfinity |
| real \(\sqrt{-4}\) | \(-2\) (the real square root is odd) | \(2i\) |
| real \(\ln(-2)\), \(\ln 0\) | \(\ln 2\), \(0\) (since Isabelle2025) | \(\ln 2 + i\pi\), \(-\infty\) |
| \(\tan(\pi/2)\) | \(0\) (\(\sin/\cos\) with \(x/0 = 0\)) | ComplexInfinity |
Arctan on its upper cut, at \(2i\) |
\(-\pi/2 + \tfrac{i}{2}\ln 3\) | \(\pi/2 + \tfrac{i}{2}\ln 3\) |
| extended reals: \(\infty + (-\infty)\), \(0\cdot\infty\) | \(\infty\), \(0\) (ereal) |
Indeterminate, Indeterminate |
No single function satisfies both \(1/0 = 0\) and $1/0 = $ ComplexInfinity. Identifying Isabelle's division with the CAS's would make the system inconsistent, and choosing either convention for both would lose either Isabelle's library or the scalar profile's declared behavior. Keeping two layers keeps both: Isabelle's theorems are true of Isabelle's constants, and the CAS's answers are true of the CAS's constants.
Away from the conflict points the conventions agree, and the agreement is exact enough to be useful: the complex exponential, the principal logarithm (argument in \((-\pi, \pi]\)), the principal square root (closed from above on its cut), and Arcsin and Arccos agree everywhere on finite arguments, cuts included; Arctan agrees except on its upper cut and at \(\pm i\). Section 15.3's bridges state this as theorems.
15.2 The two layers¶
| Logical core | CAS layer | |
|---|---|---|
| Conventions | Isabelle/HOL's, from a pinned release (Isabelle2025-2) | Explicit extended-complex conventions |
| Number types | Isabelle's nat, int, rat, real, complex, ereal, each a type of its own |
one carrier, Scalar (section 17.2) |
| Undefined points | junk values fixed by definitions (\(x/0 = 0\)) | ComplexInfinity, Indeterminate, directed infinities |
| Domains | types and type classes | predicates on Scalar (real, integer, positive, …) |
| Where it comes from | imported Isabelle theories: statements with provenance, then replayed proofs (section 28) | the scalar package: axioms G1–G7 and definitions, proved in a model inside HOL (section 15.4) |
| What it is for | reusing Isabelle's library and proofs; abstract mathematics | answering CAS requests |
The CAS's user symbols are constants of type Scalar. Requests are answered in the CAS layer. Isabelle's library enters a CAS answer only through bridges, so every step that crosses the layers carries its guard.
15.3 Bridge theorems¶
A bridge relates a CAS operation \(f\) to an Isabelle operation \(f_H\) on complex numbers through the embedding \(\mathrm{Fin}: \mathbb C \to \texttt{Scalar}\) of Isabelle's complex numbers into the finite values of the carrier:
The guard \(G\) is exact when the equation fails, or Isabelle's side is unspecified, at every point outside it. The scalar package proves these bridges (contract X-bridge; bridge theory, Theorems H-4 to H-7):
| Operations | Guard | Note |
|---|---|---|
\(+\), \(\cdot\), negation; \(\exp\); the principal square root (csqrt); Arcsin, Arccos |
none | Arccos agrees because \(\mathrm{Re}(iz + \sqrt{1 - z^2}) \ge 0\) always |
| division | \(b \ne 0\) | Isabelle: \(a/0 = 0\) |
| natural power | \(a \ne 0 \lor n \ge 1\) | Isabelle: \(0^0 = 1\) |
general power powr |
\(z \ne 0 \lor \mathrm{Re}\,w > 0\) | Isabelle: \(0^w = 0\) |
complex Ln |
\(z \ne 0\) | Isabelle: \(\mathrm{Ln}\,0\) unspecified |
real ln, real sqrt |
\(x > 0\), \(x \ge 0\) | |
Arctan |
\(z \notin \{iy: y \ge 1\} \cup \{-i\}\) | on the upper cut Isabelle's value is the profile's minus \(\pi\) |
tan |
\(\cos z \ne 0\) | |
ereal order; ereal arithmetic |
none; except \(\infty + (-\infty)\), \(0 \cdot (\pm\infty)\), \(1/0\) | the order on extended reals |
A reference script (tests/judgment_mathlib/reference/conventions.py) evaluates Isabelle's definitions as written in its sources against the profile's formulas at points on and off every cut, at 40 digits, and records where they agree; every guard must contain exactly those points (Scalar ground rule XG2).
15.4 The carrier built inside HOL¶
The scalar profile is first an axiomatic theory (axioms G1–G7, categorical for the carrier \(\hat S\)). The scalar package also constructs \(\hat S\) inside HOL from the complex type of judgment_mathlib, the proof library of the Isabelle/HOL theories the system uses (HOL model and bridges, judgment_mathlib):
Ŝ_H:= typedef { (k, z): ℕ × ℂ | k = 0 ∨ (k = 1 ∧ |z| = 1) ∨ (k ∈ {2, 3} ∧ z = 0) }
Fin z:= abs(0, z) Dir θ:= abs(1, θ) C∞:= abs(2, 0) I:= abs(3, 0)
Each profile constant is then defined on \(\hat S_H\) by cases: on finite arguments by Isabelle's operation where the conventions agree, elsewhere by the profile's tables. The profile's axioms become theorems of this model theory (Theorem H-1 there), proved from judgment_mathlib's theorems, imported from Isabelle2025-2 (exp_add, the field instance of complex, the completeness of real, the uniqueness of Ln's description). The profile is then interpreted in the model theory (judgment_store's theory interpretations), so every theorem of the profile holds there. From that point the profile's axioms rest on HOL and Isabelle's definitions rather than on a paper consistency proof, and the bridges of section 15.3 are short consequences of the definitions.
15.5 Using Isabelle's theorems in CAS answers¶
transfer_through_bridges(statement over Scalar, finite arguments a⃗):
1. write each argument as Fin(α) # guard: finite(a)
2. rewrite each profile operation applied to Fin values by its bridge, collecting guards
3. apply an Isabelle theorem to the resulting statement over ℂ (imported or replayed)
4. rewrite back by the bridges
result guard:= finiteness ∧ bridge guards ∧ the Isabelle theorem's hypotheses
Example: \(\exp(a + b) = \exp a \cdot \exp b\) for finite \(a, b\) follows from Isabelle's exp_add through unguarded bridges, so its guard is \(\mathrm{finite}(a) \land \mathrm{finite}(b)\). The result is an ordinary kernel judgment; its label names the Isabelle theorem used, as an imported statement until its proof is replayed (section 28.6). Lemmas of the profile that need analysis (existence of real roots, monotonicity, bounds on \(\pi\), the polynomial bounds MetiTarski uses) are proved this way rather than admitted.
15.6 The carrier in Isabelle's classes¶
Addition and multiplication on \(\hat S\) are commutative monoids on the whole carrier (their ACU laws are kernel-checked theorems), so \(\hat S_H\) is declared an instance of Isabelle's comm_monoid_add and comm_monoid_mult. Isabelle's theorems that need only those classes and their superclasses apply to the carrier as they are: 514 of the 10,950 class theorems of Isabelle2025-2's HOL session, such as rearrangements of finite sums. \(\hat S_H\) is an instance of no class with additive inverses (ab_group_add: $x - x = $ Indeterminate for infinite \(x\)), distributivity, or field laws; since an instance declaration needs a proof of the class predicate (section 16.4), such a declaration is refused, and no field theorem can reach the carrier by mistake. Isabelle's own natural power ^ at this type is iterated multiplication, with \(0 \mathbin{\hat{}} 0 = 1\); it is a different constant from the profile's power, where $0^0 = $ Indeterminate. That is the layering at work.
15.7 What lives where¶
| Concern | Owner | Normative pages |
|---|---|---|
| Type definitions, overloading, classes, sorts in the kernel | judgment_core |
kernel additions K2.6–K2.10; theory |
| Reading OpenTheory articles; import theories; provenance | judgment_store |
ST6; OpenTheory export and import |
| Exporting Isabelle's theories and proofs; our results back into Isabelle; run-time requests | isabelle_bridge (external) |
its own theory and design pages (section 28) |
| The Isabelle/HOL theories the system uses, exported once with their proofs and converted into a proof library | judgment_mathlib (data outside the repository, opened with judgment_store) |
judgment_mathlib |
| The carrier, its axioms, the model in HOL, the bridges | scalar |
Scalar theory, including The HOL model and bridges |
| Dependency classes of imported statements; sort-aware matching; bundles from class instances | judgment_shell |
L2.4, L3.1, L3.7 |
15.8 Rules of the layering¶
These rules are part of the invariants of section 14 (K35–K40):
- No identification. No constant of the CAS layer is defined as, or identified with, an imported Isabelle constant; they meet only in the model theory's definitions and in bridge theorems.
- Guards cross with the step. Every rewrite across the layers uses a bridge and carries its guard.
- Provenance. Every imported statement names its source (prover, release, session, theory, theorem) in every label that depends on it.
- Only proved statements. A statement used without a proof checked by our kernel is a theorem of the pinned Isabelle release; nothing is admitted on numeric evidence.
- One release. Isabelle's definitions change between releases (the real logarithm changed in Isabelle2025), so the release is pinned and named in every source.
16. Definitional mechanisms: type definitions, overloading, classes, and sorts¶
The kernel implements four definitional mechanisms used by Isabelle/HOL libraries: type definitions, loose constant specifications, overloaded definitions, and type classes with sorted type variables. None adds logical strength beyond definitions; what they add is fidelity (Isabelle's statements keep their shape) and efficiency (class membership is a lookup, not a proof). The kernel additions K2.6 to K2.10 specify them, and the kernel's theory page Type definitions, overloading, and classes (results Y) proves or cites why each preserves consistency.
16.1 Why in the kernel¶
Isabelle's library is organized by classes. In Isabelle2025-2's HOL session (measured from its theory export):
| Measure | Value |
|---|---|
| exported theorems | 33,673 |
theorems that need a class other than type |
10,950 (32%) |
| classes; instance declarations; type constructors with instances | 242; 1,831; 87 |
type constructors in linorder; comm_monoid_add; ab_group_add; field |
13; 10; 8; 5 |
With classes in the kernel, such a theorem is stored once, applied at a type by one membership check, indexed by its constant head (plus, not a variable), and replayed from Isabelle's proof nearly step for step. Without them, each generic theorem would need its operations as explicit arguments (a variable head defeats discrimination indexes), or one copy per instance type: about 97,000 copies for HOL alone, and no finite set of copies for parametric instances such as polynomials over any commutative ring.
16.2 Type definitions and loose specifications¶
Declaration.type_definition(name, abs_name, rep_name, params, predicate P: σ → Prop, witness ⊢ ∃x. P x)
declares κ(params), abs: σ → κ, rep: κ → σ, and the theorems
∀a. abs (rep a) = a ∀r. P r = (rep (abs r) = r)
Declaration.specification(names, witness ⊢ ∀v⃗. v₁ = t₁ → … → vₖ = tₖ → φ)
declares constants c⃗ and the theorem φ[c⃗/v⃗] (no equations cᵢ = tᵢ)
The first is HOL Light's basic type definition and OpenTheory's defineTypeOp; the second is Arthan's principle and OpenTheory's defineConstList 32. Both preserve models: the type denotes the nonempty subset that \(P\) carves out, and the constants can be interpreted by the witnesses' values (Theorems Y-1 and Y-2). They are what every HOL library builds its number types with; an imported article stops at its first defineTypeOp without them.
16.3 Overloaded definitions¶
An overloaded constant (Isabelle's plus, times, inverse, …) is declared once and defined separately at type instances by instance definitions \(c[\bar\tau]:= b\). Two conditions keep this consistent 33:
- Orthogonality: no two instance definitions of one constant have unifiable type arguments.
- Termination: the dependency relation between defined items (constant instances and types defined by type definitions), closed under type substitution, has no infinite chain.
Isabelle's earlier check missed a cycle that ran through a type definition, which allowed a proof of False until it was corrected 34; the kernel checks termination over both kinds of items, by Kunčar's algorithm, which is decidable under orthogonality, and a verified checker exists in HOL4 35. Overloading cannot be interpreted by the kernel's set-based semantics (two types may denote the same set while an overloaded constant differs at them), so the kernel adopts Kunčar and Popescu's ground semantics, which interprets ground types and ground constant instances together by well-founded recursion along the dependency relation; on theories without overloading every earlier model restricts to a ground model, and the kernel's soundness argument uses ground models (Theorem Y-8).
16.4 Classes, instances, and sorts¶
class c (superclasses c₁…cₘ, parameters o₁…oₙ over one type variable α, axiom A(α))
defines of_class_c: itself(α) → Prop:= λ_. of_class_c₁(TYPE[α]) ∧ … ∧ A(α)
instance κ:: (S₁, …, Sₖ) c citing ⊢ of_class_c(TYPE[κ(α₁^S₁, …, αₖ^Sₖ)])
type variables carry sorts (sets of classes); τ: S is decided from the arities
every type substitution must be admissible: θ(α^S): S
The logic core gains the type itself with the constant TYPE, so that a property of a type is a predicate in the logic without breaking the type-variable condition of definitions 36. An instance declaration cites the theorem that proves the class predicate at the type constructor, as LiteralKind and AcuOperator declarations cite their laws; the kernel then records the arity and decides membership by one descent through the arities, kept coregular so that membership needs no search [38]. Two rules relate sorts to propositions: of_class(Γ, τ, c) proves \(\mathsf{of\_class}_c(\mathsf{TYPE}[\tau])\) when \(\tau: \{c\}\), and unconstrain turns a sorted type variable into an unsorted one with class premises. Every judgment records sort hypotheses, the sorts of type variables that occurred in its derivation and no longer occur in its statement; a sort with no instance would make reasoning about it vacuous, so a Proven theorem requires each of its sort hypotheses to be witnessed (Isabelle keeps the same record). Classes add no logical strength (Theorem Y-6, after Wenzel 37): every derivation with sorts translates into one without, which is also how classes are written to formats that lack them, such as OpenTheory.
16.5 ACU operators at a class¶
An AcuOperator may be declared at a sorted type variable, \(c[\alpha^S]\), citing class-level laws. Canonical construction then treats every spine \(c[\tau](\dots)\) with \(\tau: S\) as an ACU spine, including type variables whose sort entails \(S\), so terms over an arbitrary commutative monoid or ring get canonical forms. Because membership depends on instance declarations, an instance that makes some type a member of such a sort is part of the canonical signature, as ACU and literal-kind declarations are, and terms at that type are lifted when used past it. Overlap with a declaration at a concrete type of the sort is refused (extended). Soundness is Theorem Y-7.
16.6 What classes give the CAS¶
- Generic simplifiers, written once. Ring normalization, field simplification with its nonzero side conditions, linear arithmetic over ordered fields, and lattice laws each work for every instance: numbers, polynomials, matrices, finite fields, user-defined structures.
- A fast entailment layer. "This type is a field" is decided by lookup; an engine selects its procedure and lemmas by the type's classes, and inherits every lemma proved for a superclass.
- Bundles from instances.
judgment_shellfills a law bundle at a type of a class from the class's theorems (L3.7), so engines keep their bundle interface. - The limit. Classes describe types, not values: assumptions such as \(x > 0\) or "\(x\) is an integer" stay guards. The scalar carrier, which is not a field, reaches the class library through the bridges of section 15.
16.7 What it costs¶
The trusted base grows by the definitional checks (section 30.6): type definitions and specifications; the orthogonality and termination checks; membership, coregularity, admissibility of every type substitution, and sort hypotheses; class-level ACU. The kernel's types carry sorts, and every substitution checks them. In exchange, the kernel reads Isabelle's statements without translation, and Theorem Y-6 keeps the logical content exactly that of HOL with definitions.
17. Concrete baseline B0 and module boundaries¶
Sections 17–26 turn the architecture into an implementation blueprint; sections 27–29 add package contracts and optional interoperability. The choices labeled B0 are the concrete baseline of the design, rather than a menu of equally unspecified alternatives, and refine the earlier conceptual sketches. judgment_core implements the kernel's part of B0, as the implementation reference specifies; the coordinator and engines are not among the current packages. The sketches are design notation, not compilable Mojo source or a formal soundness proof.
17.1 Baseline choices¶
| Area | B0 choice | Deliberately deferred |
|---|---|---|
| Object syntax | Polymorphic simple types (type variables, HOL-style), declared type constructors, explicit lambda and let binders, n-ary application spines with variadic application of ACU constants, a proposition type, literals of declared literal kinds, type definitions, overloaded definitions, and type classes with sorted type variables (section 16). | Dependent types, universes, implicit coercions, and higher-order unification. |
| Logical calculus | Natural deduction for implication, conjunction, disjunction, falsity, and universal quantification; homogeneous kernel equality with the ξ-rule; ∃, ↔, and ¬ defined in the logic core. |
Primitive choice, excluded middle, extensionality, and induction: admitted per semantic profile (the CAS profiles admit them from the start), or added later as checked extensions. |
| Conversion | α (de Bruijn), β, ζ, δ for transparent definitions, ACU for declared constants, and literal-kind evaluation (section 20.5). | η, extensionality, distributivity, annihilators, and any assumption-sensitive normalization. |
| Literals | Literal kinds with canonical payloads and a few accelerated operations: exact integers and rationals from apn_mojo; formal polynomial literals (section 20.6). | Accelerated algorithms beyond arithmetic and comparison (gcd, factorization, and the like are untrusted and certified). |
| Semantic profile | scalar: one carrier of extended complex values, domains as predicates, generic answers as conditional results with finiteness guards (section 17.2). |
Further profiles: real-only, interval, finite-field, and abstract theories (section 32). |
| Mathematical relations | Named, typed propositions with theorem-backed composition and morphisms. | Treating every relation as class membership. |
| Variables | De Bruijn indices for bound variables; a local is its binding site (frame, type, name); separate pattern/search syntax. | Identity by printed name across frames. |
| Proofs | Append-only candidate DAGs, checked through a small kernel; opaque checked handles. | Cyclic proofs or unvalidated theorem-reference shortcuts. |
| Contexts | Immutable parent-linked frames, deduplicated by parent and entry; explicit context transport; mutable reasoning state stored separately. | Automatic identification of logically equivalent contexts. |
| Storage | Reuse termbank syntax storage; typed row ids, operand columns, exact structural interning. | A mandatory on-disk database or a bespoke replacement for all standard containers. |
| Theorems | Closed guarded theorem schemes over explicit term parameters and type variables; instances by term and type instantiation. | Higher-rank polymorphism and schemes over type constructors. |
| Search | Exact-context and evidence-policy goal interning, candidate hyperedges, forward facts, deterministic event queues. | Completeness of unrestricted search. |
| Guards | Hash-consed AND/OR DAGs plus bounded support antichains carrying witnesses. | Eager full DNF, mandatory BDDs/ZDDs, or automatic weakest-precondition synthesis. |
| Equality | Optional proof-producing congruence workspace; budgeted saturation is a strategy on top. | Global unions justified by unresolved guards. |
| Checking policy | Check at the boundary of a request (section 30): every returned result, durable store entry, and export. Engines share provisional facts with recipes inside the request. An explicit, labeled unchecked mode never writes to a store. | Eager checking of every internal step, except as a debugging option; passing provisional facts to another request. |
| Execution | One writer initially; iterative traversals and deterministic operation budgets. | Parallel publication or nondeterministic logical results. |
| Packaging | One repository and version for the native packages; external dependencies at pinned channel versions; contracts owned by their producers; explicit acyclic imports; trust follows package boundaries (section 27). | Publication as versioned conda packages. |
| Foreign provers | Isabelle/HOL: theorems imported as statements with provenance and then as replayed proofs, through OpenTheory articles; our results replayed in Isabelle; run-time requests (section 28). There is no Lean bridge. | Universal proof translation; a mandatory Isabelle installation. |
Propositional extensionality, ∀P Q:Prop. (P → Q) → (Q → P) → P = Q, is an axiom of the logic core rather than of the profiles. It holds in every topos, so the core stays compatible with constructive profiles, and it is needed to eliminate conversion steps that evaluate literal comparisons inside larger terms. Excluded middle, choice, function extensionality, and infinity remain profile axioms.
Simply typed lambda syntax is useful for binders and compositional expressions even when theorem matching is initially first-order. A mathematical integral can take a lambda term as an argument without adding integration to the kernel evaluator. Lambda evaluation is total at the kernel's denotational level; a partial mathematical operation is not silently made total over ordinary real values.
17.2 Exact equality and partial-expression semantics¶
B0 distinguishes two notions in its API:
KernelEq(A, t, u) # homogeneous equality in a total interpreted carrier A
RelApp(relation, args) # a declared mathematical relation, including strict CAS equivalence
The natural-deduction equality rules apply to KernelEq, not indiscriminately to every RelApp. A profile may encode partiality through a carrier on which every operation is total, with a predicate marking the ordinary values, or through a declared semantic relation between expression representations. In either encoding, its checked declarations must state the connection to the intended pointwise semantics. An equality workspace cannot infer this connection from the name Equal.
The first profile, scalar. It specifies extended-complex arithmetic explicitly:
- Carrier. One type,
Scalar. Its values are the finite complex numbers, the directed infinitiesDirectedInfinity(θ)for unit complexθ,ComplexInfinity, andIndeterminate. - Total operations. Every arithmetic and elementary operation is total on
Scalar, with declared conventions for the special values:1/0 = ComplexInfinity,0/0 = Indeterminate,0·∞ = Indeterminate, andIndeterminateabsorbs everything. These conventions are the profile's axioms. - A proof obligation. That
+and·stay associative and commutative, with units 0 and 1, on the special values must be discharged before the profile's ACU declarations are admitted. It is checked by case analysis over the finitely many classes of special values. - Definedness.
finite(t)holds whentis a finite complex number. A generic simplification is a theorem guarded by finiteness:finite(x) ∧ x ≠ 0 ⇒ x/x = 1. Annihilation (0·x = 0) is likewise guarded byfinite(x). - Strict equality. Kernel equality on
Scalar: two expressions are strictly equal when they have the same value, special values included. This profile needs no separateRelAppand no bridge for its equality. - Domains. Domains are predicates on
Scalar, not types:real(x),integer(x),positive(x), membership in intervals and sets. Together with finiteness, a real inequality such asx > 0impliesreal(x);<also relates the infinities±∞(\(\infty > 10\) holds), and is false whenever an argument is not an extended real. Assumptions can then change what is known about a symbol's domain without changing its type, which static types could not do. - Symbols. CAS user symbols are opaque constants of type
Scalardeclared in a session theory (section 19.2). The session context assumes each symbol finite by default; that is a hypothesis of the context, not an axiom, so a request can drop it. - Axioms and model. The profile's axioms G1–G7 describe the carrier by its four classes of elements and the operation tables, the reals as a complete ordered field, and
expandlogby their functional equation, a local bound, and the principal branch. They are true in the carrier and determine it up to isomorphism, so "true in \(\hat S\)" is exactly what the profile commits to. The ACU laws of+and·are kernel-checked theorems of them, proved by case analysis over the classes. Thescalarpackage also builds the carrier inside HOL from Isabelle'scomplex, where the axioms become theorems (section 15.4). - Elementary functions.
expandlogare the only analytic primitives; the trigonometric and hyperbolic functions, their inverses, general powers, the principal square root, and the real rootssurd(x, n)are definitions by explicit formulas, with the principal logarithm's argument in \((-\pi, \pi]\), so the closures of the branch cuts are what the formulas give (counterclockwise continuity, and its image under \(1/z\)). Values at infinity are limits along rays, with explicit exceptions (\(\operatorname{arccot}(0)\), \(\operatorname{arccoth}(0)\), \(1^\infty\)); \(\exp(x)\) may be written as \(E^x\) because \(E^w = \exp(w)\) is a theorem. Identities such as \(\log(e^z) = z\) carry guards on imaginary parts, cuts, or unwinding numbers, in a guard language that extends finiteness and nonzero conditions. - The numeric filter. Ball evaluation with apn_mojo, aware of branch cuts and exact on them, refutes wrong candidate rules before anyone tries to prove them; it admits nothing (section 31.3).
- The bridges. The profile's operations agree with Isabelle's on finite values except at the points that bridge guards exclude (section 15.3); the
scalarpackage owns the bridges and their proofs.
Generic answers. By default the CAS returns conditional results whose extra guards are only finiteness and nonzero conditions, accepted by the request's policy and displayed on request (section 3.1). A strict request requires evidence for every guard.
RelApp remains for genuinely different relations: bounds, refinements, inclusions, and the relations of section 7.3. Their composition is not equality transitivity.
17.3 Responsibility map and package realization¶
termbank/ # immutable raw syntax; no proof search
core/
ids, types, syntax # typed views, scope operations, certification
theories, contexts # declarations and local interfaces
proof, kernel # proof nodes, checking, dependency summaries
theorem, guards # closed theorems and evidence-bearing guard operations
certificates # versioned checking interfaces
reasoning/
goals, derivations # unfinished obligations and recipes
facts, indexes # checked evidence and candidate lookup
events, dependencies # scheduling and invalidation
engine, conversions # engine protocol and result contracts
engines/
simplify, relational, arithmetic, polynomial
congruence, saturation
persistence/ # checked import/export, not serialization of authority
This layout records logical responsibilities. Section 27 defines their realization as independently usable packages, and the package graph is authoritative for package names and import direction. In package terms: core/ is realized by the trusted kernel package judgment_core (ids through certificates) and the untrusted judgment_shell (theorem store, guards, export, proof building, conversion combinators, bundles); reasoning/ by judgment_shell's engine protocol and the design's reasoner package; persistence/ by judgment_store; each engine is its own package. In particular, judgment_core must not import judgment_shell, reasoner, or any engine. Certificate validators admitted into the trusted base remain distinct from the untrusted engines that generate their inputs.
18. Handles, types, syntax, and scope algorithms¶
18.1 IDs and ownership¶
Use nominal ID wrappers rather than interchangeable integers:
TypeId, TermId, PropId, DeclId, TheoryId, ContextId
LocalId, HypId, ProofId, JudgmentId, TheoremId
GuardId, SupportId, RelationId, CheckerId
GoalId, DerivationId, AttemptId, WorkspaceId, CandidateId
EvidencePolicyId, ImportSourceId, ClassId, SortId
A PropId is a checked view of a term of proposition type, not a second copy of its syntax. Only the checker's verdicts make a row checked (CG5, CG8). An unchecked wire integer or a raw row id is not a checked term or judgment.
Physical baseline: compact ids inside each termbank.dag table: UInt32 where the table is bounded below 2³² rows, and UInt64 sequence numbers (CG3). A public handle is valid only in the session or bank that issued it; crossing banks requires import. Rows are never renumbered while handles may survive. Workspace handles carry a generation. Overflow, a handle of another session or bank, a stale generation, and an out-of-bounds index are errors, never wraparound (CG4).
The kernel holds no tables. Terms, types, proofs, contexts, declarations, and theories are rows of termbank.dag, appended in one commit sequence and never renumbered, and the kernel's checks advance a verified watermark over them (DAG storage, the checker). A request builds its rows in a workspace over a verified prefix: a failed operation, or a return to a snapshot, truncates the workspace; a session fork is a child workspace, which Session.merge commits into its parent, where its rows are checked again. Every handle carries its workspace's generation, so a handle to a removed row is rejected rather than misread.
SliceRef[T]:
offset: UInt32
length: UInt32
DurableRef[T]:
store: StoreId
index: UInt32
EphemeralRef[T]:
workspace: WorkspaceId
index: UInt32
generation: UInt32
The generic notation describes nominal ownership, not a fixed ABI. A content digest is used for persisted identities and integrity; structural equality and proof checking remain necessary. A hash collision must not identify two unequal declarations or validate a proof.
18.2 Types and expressions¶
TypeNode =
Var(variable: TypeVarId) # type variable
| Construct(type_constructor: DeclId, arguments: SliceRef[TypeId])
| Arrow(domain: TypeId, codomain: TypeId)
TermNode =
Bound(index: UInt32)
| Local(id: LocalId)
| Constant(declaration: DeclId, type_arguments: SliceRef[TypeId]) # instance of a polymorphic constant
| Apply(function: TermId, arguments: SliceRef[TermId]) # n-ary spine
| Lambda(parameter_type: TypeId, body: TermId)
| Let(value_type: TypeId, value: TermId, body: TermId)
| Literal(kind: LiteralKindId, payload: UInt64)
CheckedTerm: # opaque
term: TermId
type: TypeId
theory: TheoryId
scope: ScopeInterfaceId
B0 type constructors have declared fixed arity. Types contain no term-level variables, but they may contain type variables: a constant, axiom, or theorem with type variables in its type is a scheme, used at instances obtained by substituting types for those variables. A Constant node records the instance's type arguments, so every term has exactly one type. Type polymorphism is never inferred from a printed name. Numeric literal payloads require a declared literal kind with a canonical representation (section 20.6); a user-supplied atom pool index is not automatically a mathematical constant.
Application spines. An Apply node's function is never itself an Apply: constructors flatten nested applications into one spine, so each applied term has a unique representation. A constant declared ACU at some instance (section 19.1) may be applied to any number of arguments of its carrier type, two or more, and that application means the right-nested binary application. Conversion (section 20.5) makes all such spellings, groupings, and orders equal.
Logical propositions are typed applications of reserved logical declarations. Constructor helpers expose their logical shape without inventing a second term representation:
truth() -> PropId
falsity() -> PropId
implies(p, q) -> PropId
and_(p, q) -> PropId
or_(p, q) -> PropId
not_(p) -> PropId # abbreviation p -> False
forall_(type, de_bruijn_body) -> PropId
kernel_eq(type, left, right) -> PropId
relation(relation_id, args) -> Result[PropId, TypeError]
forall_ uses the same binder discipline as lambda syntax. The generic proposition constructors are available only over certified components or produce a raw candidate requiring certification.
Termbank keeps its head-table encoding and n-ary rows, extended with binders: one head per declared constant (rows hold the type arguments, then the term arguments), one generic application head for spines whose function is not a constant, binder heads for Lambda and Let, and atom kinds for bound variables, locals, type variables, and literals. The checked view defines the exact correspondence to the nodes above; it must not create a second competing identity space. Raw interning preserves ordered syntax and performs no rewriting. ACU canonical forms and literal folding are built by judgment_core's syntax constructors on top of raw interning, and they are justified by the extended conversion; any other normalization (distributivity, annihilators, context-aware steps) produces equality evidence outside this path.
18.3 Metadata and certification¶
Cache structural hash, node kind, child slice, and loose-bound-variable range. Free-local sets and inferred types can be memoized, but a type for an open term is cached with its binder/local interface. Bound(0) may have different types under different binders.
Syntax.certify(theory, context, raw_term, binder_types)
-> Result[CheckedTerm, CheckFailure]
Syntax.certify_prop(theory, context, raw_term)
-> Result[PropId, CheckFailure]
Syntax.infer_type(theory, context, raw_term, binder_types)
-> Result[TypeId, CheckFailure]
Certification checks declaration availability, binder indices, local scope membership, application domains, let types, literal validity, and the absence of search holes. It uses an explicit traversal stack and memo keys containing the typing environment. Inferring a type is independent of facts such as x > 0.
The implementation has no certify: a term is a NODE row that the construction engine builds canonically, and it means something in a theory only through the verified fact a check establishes for it (its type, home, scope and canonicity; KC1.4). Stored terms are bound-closed: binders are built by abstracting a local, and terms with loose bound variables exist only under binders and inside the engine's traversals. A certified term's type then depends on the term alone. Each certified term records its home theory (the least theory that contains the declarations it needs) and its scope (the innermost frame among those that fix its locals); it is usable in a context whose theory includes its home theory, and whose chain contains its scope.
18.4 Capture-avoiding substitution¶
Closed binder syntax uses de Bruijn indices. At binder depth d, opening the outermost binder with term s maps:
Bound(k) where k < d -> Bound(k)
Bound(k) where k == d -> shift(s, amount=d, cutoff=0)
Bound(k) where k > d -> Bound(k - 1)
Entering the body of a binder increments d. The value of a Let is visited at the original depth and its body at the incremented depth. Local and declaration IDs are unaffected by index shifting.
Syntax.open_binder(body, argument) -> TermId
Syntax.abstract_local(body, local_id) -> TermId
Syntax.substitute_locals(term, substitution) -> TermId
Syntax.free_locals(term) -> LocalSet
abstract_local replaces that exact LocalId by Bound(d) and shifts loose indices at or above d to account for the newly introduced enclosing binder. Substituting a local under binders shifts the replacement by the current depth. Memoization keys include term ID, depth, and substitution identity; a term-only cache is invalid. Rebuild changed nodes through raw structural interning.
These algorithms are written recursively in mathematical descriptions but implemented by work stacks to avoid host-stack dependence. Complexity is proportional to the visited (node, depth, substitution) states and produced output, not always the number of unique term IDs.
18.5 Search variables are not kernel expressions¶
SearchNode = Rigid(TermId) | Meta(MetaId) | SearchApply(...) | SearchLambda(...)
MetaVariable:
expected_type: TypeId
allowed_scope: ContextId
owner: SearchScopeId
assignment: Optional[SearchExprId]
AssignmentTrail:
entries: List[UndoRecord]
assign(meta, expression) performs a type check, transitive occurs check, and local-scope/ownership check. Each alternative theorem match takes a trail checkpoint; failure rolls back its assignments. An engine must not assign a metavariable owned by an enclosing search merely to make its own candidate succeed. This design is motivated by the scope and nested-search issues documented in Lean's metavariable implementation. 30
zonk expands assignments and emits a kernel term only when all reachable metavariables are resolved. It rejects escaping locals. B0 uses first-order theorem matching; higher-order constraints are deferred as unsupported rather than solved by unsound heuristic substitution.
19. Theories, contexts, and checked transport¶
19.1 Immutable declarations and theory extension¶
Declaration =
TypeConstructor(name, arity)
| Constant(name, type) # type may contain type variables
| Definition(name, type, closed_body, transparency)
| Axiom(name, closed_proposition) # type variables make it a scheme
| Proven(name, checked_closed_judgment)
| AcuOperator(constant, type_arguments, unit, associativity, commutativity, unit_law)
| LiteralKind(name, carrier_type, implementation, bindings)
| TypeDefinition(name, abs, rep, params, predicate, witness) # section 16.2
| Specification(names, witness) # section 16.2
| OverloadedConstant(name, type) # section 16.3
| InstanceDefinition(constant, type_arguments, body) # section 16.3
| Class(name, superclasses, parameters, axiom) # section 16.4
| Instance(type_constructor, argument_sorts, class, witness) # section 16.4
TheorySnapshot:
parent: Optional[TheoryId]
declarations: PersistentMap[DeclId, Declaration]
names: PersistentMap[QualifiedName, DeclId]
profile: SemanticProfileId
kernel_version: KernelVersion
TheoryStore.extend(parent, declaration) -> Result[TheoryId, DeclarationError]
TheoryStore.compatible(source, target, dependencies)
-> Result[TheoryEmbedding, CompatibilityError]
In the implementation there is no theory store. A declaration is a DECL row of termbank.dag and a theory a THEORY row holding a version vector; extending a theory commits the declaration row and the theory row just after it, and the theory pass checks both (K1.3, KC1.11). A session declares through its own methods (Session.symbol, axiom, define, theorem, and the rest; API guide).
A ground sort is a type constructor of arity 0. Every type is assumed inhabited, as in HOL; declaring a type constructor carries that commitment, and a type definition (section 16.2) requires a witness. Type variables carry sorts (section 16.4), and every instantiation must respect them.
Conservative definitions. A Definition introduces a new constant c with the defining equation c = body. The kernel requires that the body is closed, that it does not mention c or any later declaration, and that every type variable of the body occurs in c's type (HOL Light's condition, which keeps definitions conservative under type instantiation). A transparent definition takes part in δ-conversion; an opaque one provides only its equation, as a theorem.
ACU declarations. AcuOperator declares a binary constant, at the given type arguments, associative and commutative, with an optional unit. Its carrier must be an application of a type constructor, never an arrow type or a type variable: this keeps the variadic reading of ACU spines unambiguous and the algebraic part of conversion independent of β, which the proof of canonical forms requires. The unit is a closed canonical term that is not an application of the constant, and two declarations for one constant must not have unifiable type arguments. Each law names a checked theorem or an axiom of the theory whose statement the kernel compares with the expected form, ∀a b c. f(f(a,b),c) = f(a,f(b,c)), ∀a b. f(a,b) = f(b,a), and ∀a. f(e,a) = a. The constants of the logic core (∧, ∨, →, kernel equality) cannot be declared ACU, so that the natural-deduction rules stay syntactic. An operator taking a structure as an explicit argument, such as a group's multiplication mul(G, a, b), is not ACU in conversion; its laws are used by rewriting.
The unit is atomic: a literal, or an instance of a constant that is not a transparent definition, because a compound unit is canonical only for the signature in which it was declared. Neither an ACU constant, nor a unit, nor a constant bound to a literal operation is a transparent definition, so canonical construction never unfolds. Two declarations for one constant conflict when their type arguments unify after their variables are renamed apart, and an instance finds its declaration by one-way matching. The constant and the cited laws must be visible in the parent theory.
Canonical signature. The AcuOperator and LiteralKind declarations visible in a theory form its canonical signature, on which canonical construction depends (section 20.5). A judgment is usable unchanged in a descendant theory with the same signature; across a different signature, the kernel rebuilds its context entries and proposition canonically and records the step as a conversion. Profiles make these declarations while they are built; session theories add only constants. Every judgment depends on its theory's canonical signature.
Literal kinds. A LiteralKind binds one of the kernel's literal implementations (section 20.6) to a carrier type, and binds each accelerated operation of the implementation to a constant of the theory. Its scheme (for example, lit(a) + lit(b) = lit(a + b) for all payloads a and b) is recorded in every dependency summary. The scheme is not an axiom family: the declaration cites theorems stating that the bound operations form an ordered commutative ring (integers) or ordered field (rationals) on a domain predicate, and the scheme follows from them because ℤ and ℚ embed uniquely into every such structure; the values 0 and 1 are the bound zero and one constants.
Each declaration has immutable identity including its full checked content and dependencies. Extension cannot redefine an existing identity. Overloaded constants, are the one form of definition by cases on types: their instance definitions must be orthogonal and their dependencies, through type definitions as well, must terminate (section 16.3). B0 admits only acyclic, nonrecursive definitions. Primitive recursion over the natural numbers is definitional: the optional judgment_nat package declares c := rec a f as an opaque definition with its equations as checked theorems (Definition NR-6), with no kernel change. Adding an axiom records a new admitted dependency; it is not presented as a checked derivation of that axiom's truth.
B0 compatibility is identity-preserving extension of required declarations. Cross-theory reinterpretation requires a separate checked interpretation/bridge, not a matching name or equal file hash. Reusing a theorem may require only its dependency closure rather than every unrelated declaration in its discovery snapshot, but the kernel/profile versions must remain compatible.
Theories form a directed acyclic graph rather than a chain of snapshots: besides an extension by one declaration, a theory row may record a merge or a join, the union of two theories, and the theory pass checks that no name is declared twice and that the canonical signatures do not conflict (K1.3, K2.7). A theory is represented by a version vector over segments of consecutive declarations, so inclusion is a pointwise comparison. The compatibility check above is realized by home theories: each judgment records the least theory containing the declarations its derivation uses and the canonical signature of its theory, and it may be transported into, or declared Proven in, any theory that includes that home theory (Theorems D-7 and D-8). Identity-preserving reuse thus needs no separate TheoryEmbedding; reinterpretation across different declarations still needs a checked interpretation. The canonical-signature paragraph above reads accordingly: a judgment is usable unchanged in every theory that includes its home theory and has the same canonical signature, whether or not it descends from the judgment's theory. Across a different signature, the kernel lifts the judgment, and likewise every stored content it uses there: declaration statements, definition bodies, and the hypotheses of earlier frames.
19.2 Context frames and evidence interfaces¶
ContextEntry = Fix(LocalId, TypeId) | Assume(HypId, PropId)
ContextFrame:
parent: Optional[ContextId]
theory: TheoryId
entry: ContextEntry
depth: UInt32
ProofInterface:
locals: OrderedLocalDeclarations
hypotheses: OrderedHypothesisDeclarations
ContextStore.fix(parent, type, name)
-> (ContextId, LocalId)
ContextStore.assume(parent, proposition)
-> (ContextId, HypId)
ContextStore.is_extension(inner, outer) -> Bool
Session theories. The CAS declares each user symbol as an opaque constant in a session theory that extends the profile, not as a fresh local of a context. A context then consists of hypotheses about named constants, so it can be identified by its content, and equal assumption sets in different requests are the same context. Fresh locals remain for genuine binders, generalization, and the quantifiers of theorems.
A local is its binding site: the frame it extends, its type and its name; within a frame, the name is part of a local's identity (section 8.1). Frames are deduplicated by parent and entry, so fixing one name and type over one frame twice gives one local and one frame, and assuming one proposition over one frame twice gives one hypothesis. B0 preserves declaration order. Equivalent-looking assumptions at different binding sites are not silently conflated: identifying contexts whose chains differ needs a checked renaming map.
Contexts are compared by their entries. A frame without an entry, made by rebase, moves a context to a theory that includes its own; such frames never stack, so a context is determined by its innermost entry and its theory. is_extension is the relation that the checker decides on frame rows with their ancestor pointers (local checking, Definition LC-7): Δ extends Γ when Γ's entries are a prefix of Δ's and Δ's theory includes Γ's. A rule's premises and term arguments must have entries on one chain, and its result lies in the deepest entries, at the largest theory.
A checked result's interface lists its actual retained proof dependencies, not necessarily all assumptions present in the ambient context. The ambient context must contain or justify that interface. Syntactic dependency accounting is conservative proof support, not a globally minimal assumption set.
Mutable facts do not live in ContextFrame. They live in a separate state indexed by the immutable context. Thus discovering a consequence does not change the identity of the context's assumptions.
19.3 Context transport¶
ContextMap:
source: ContextId
target: ContextId
locals: TypedSubstitution
hypotheses: Map[HypId, CheckedJudgment]
theory_map: TheoryEmbedding
Kernel.transport(judgment, context_map) -> Result[CheckedJudgment, CheckFailure]
In the implementation, transport is the authoring rule transport: Session.transport commits a proof row whose operands are the premise, the local map, and a judgment for each hypothesis the premise uses, and the checker checks that row (local checking, Definition LC-11).
Every source hypothesis used by the judgment must map to evidence for its substituted proposition in the target. Each source local maps to a well-typed target term. Substitution is checked and capture-avoiding. A genuine context extension has the identity local map and reused hypotheses, providing a fast path for weakening. An arbitrary sibling context requires evidence; ancestry is neither necessary nor sufficient for a changed interpretation.
A context map is directional. Evidence that target satisfies the source interface does not authorize transport in the reverse direction. It also does not imply that the two contexts have identical consistency status.
19.4 Export algorithm¶
export_to(j, outer) requires a validated ancestor/interface relationship. Its default operation is:
- Read the kernel-computed dependencies of
j. Reject an unbound or unresolved dependency. - Identify used assumptions introduced after
outer. Discharge them by implication introduction. Retain the displayed support order deterministically. - Identify remaining new local parameters in the result and discharged assumptions. Generalize them in reverse declaration order, checking that no retained outer assumption contains a generalized parameter.
- Ensure that the resulting proof uses only the outer interface. Return a checked judgment there.
For B0's nondependent term types, a helper can deliberately arrange the result as forall parameters, guard -> conclusion: discharge the new assumptions before generalizing their parameters, and prove the conversion from a list of implications to the guard conjunction. The helper must account for all new local dependencies, not only locals occurring in the final conclusion.
TheoremStore.close_global(judgment, chosen_guard_order)
-> Result[TheoremId, ExportError]
Global export requires no unresolved hypotheses or free local IDs in the closed proposition or proof interface. Unused parameters need not be generalized. Retained outer assumptions prevent global export until explicitly discharged; a context-relative lemma stays context-relative.
This makes the Isabelle-inspired export operation concrete while leaving semantic guard weakening to a separate proof-producing procedure. 27
20. Proof nodes, kernel methods, and the checking algorithm¶
20.1 Candidate evidence and checked evidence¶
JudgmentSpec:
theory: TheoryId
context: ContextId
proposition: PropId
ProofNode:
scope: ContextId
step: ProofStep
CheckedJudgment: # opaque, kernel-created
specification: JudgmentSpec
proof: ProofId
dependencies: ProofDependenciesId
stamp: KernelValidationStamp
ProofDependencies:
locals: LocalSet
hypotheses: HypSet
declarations: DeclSet
axioms: DeclSet
checkers: Set[CheckerVersionId]
imported: Set[ImportedStatementId] # tier 1 statements, with their sources
sort_hyps: Set[SortId] # section 16.4
The last two fields record imported statements (section 28.4) and sort hypotheses (section 16.4); they are empty for proofs without them, and inherited through every inference that uses such premises. Request acceptance policies filter checked evidence by its full dependency closure; a checked handle is not a claim that every caller accepts the same import sources.
A proof node's scope is a claim to be validated, not authority to import its hypotheses into an outer result. Dependencies are computed by the kernel, including after hypothesis discharge, quantifier introduction, theorem application, and certificate checking. A stamp is process-local validation metadata, not a portable substitute for the proof. Opaque handles enforce the logical API boundary under the implementation's memory-safety and module-visibility assumptions. They are not a sandbox against arbitrary native code that corrupts process memory; hostile extensions require a separate isolation boundary. Unsafe runtime operations that can violate those assumptions belong in the implementation trust review.
Use append-only proof storage with variable-length argument slices. An ordinary proof node references already allocated children, including every hypothesis proof in a transport map and every checked premise of a certificate. Imported artifacts are topologically sorted and checked for cycles, including cycles through referenced theorems. Proof hash-consing includes the inference tag, endpoints, substitutions, scope/binder identities, and child IDs.
20.2 B0 proof instruction set¶
| Constructor | Checked obligation and resulting inference |
|---|---|
Hyp(h) |
h is an available hypothesis with its recorded proposition. Result depends on that exact HypId. |
AxiomRef(d) |
d is an admitted proposition declaration in a compatible theory. Record its axiom dependency. |
UseTheorem(t, type_args, args) |
t is a closed checked theorem or axiom; instantiate its type variables with type_args (type instantiation, each admissible for its variable's sort section 16.4), then its typed term parameters. It produces the instantiated implication before its guard is discharged. |
TruthIntro |
Establish logical True. |
ImpIntro(h, body) |
The body is valid under the corresponding extended interface. Discharge exactly h and obtain P -> Q. |
ImpElim(f, p) |
The function proof establishes P -> Q, and the argument proof establishes the same P in a compatible context. Obtain Q. |
AndIntro(left, right) |
Obtain P and Q from proofs of both propositions. |
AndLeft(p), AndRight(p) |
Project the appropriate proposition from a conjunction. |
OrLeft(p, Q), OrRight(P, q) |
Introduce a disjunction using evidence for one side. |
OrElim(disjunction, left_branch, right_branch) |
Check evidence for P or Q and proofs of P -> R and Q -> R. Obtain R. Coverage is not implicit. |
FalseElim(p, Q) |
Check a proof of False, then obtain well-formed Q. The coordinator still reports the inconsistent context explicitly. |
ForallIntro(local, body) |
The body is checked under the frame that fixes that local, which occurs in no term usable at the frame it extends. Generalize it only when it is not free in undischarged hypotheses; abstract it capture-avoidantly. |
ForallElim(p, term) |
Instantiate the bound variable with a certified term of the quantified type. |
EqRefl(t) |
Obtain KernelEq(type(t), t, t). |
EqSym(p), EqTrans(p, q) |
Check equality type, orientation, and common endpoint; apply homogeneous symmetry or transitivity. |
EqApply(pf, pa) |
From kernel equal functions and equal arguments, obtain kernel equal applications. No dependent type transport is hidden here. For an n-ary spine, EqApply takes one equality per argument position. |
EqAbstract(local, p) |
The ξ-rule: from s = t proved under a local x fixed over the premise's context, that no undischarged hypothesis mentions, obtain (λx. s) = (λx. t). |
EqSubstitute(predicate, equality, premise) |
Check P(a), a = b, and the scoped predicate abstraction; obtain P(b). |
Convert(p, target) |
The proved proposition and target are definitionally equal under the conversion of section 20.5: α, β, ζ, δ, ACU, and literal kinds. No solver or rewrite search is called. |
Transport(p, context_map) |
Check theory, local substitution, and every required hypothesis mapping. |
Certificate(checker, version, payload, claim, premises) |
Check the versioned certificate against the exact claim and checked premises; record validator dependencies. No checker is admitted, and termbank.dag refuses certificate rows (TD1.8): a certificate is data that an expander turns into the other instructions. |
OfClass(τ, c) |
τ belongs to class c by the theory's arities (section 16.4). Obtain of_class_c(TYPE[τ]). |
Unconstrain(p, α) |
the sorted type variable α^S does not occur in the context. Obtain the statement with α unsorted and the class premises of S (section 16.4). |
A conversion step names the transparent definitions it may unfold: Convert(p, target, unfolding) checks definitional equality unfolding only those, and the step depends on exactly them, so dependency summaries do not depend on the unfolding strategy.
∃, ↔, and ¬ are transparent definitions of the logic core (∃x. P x is ∀Q. (∀x. P x → Q) → Q, ¬P is P → False), so their introduction and elimination rules are derived, not primitive. Type variables occurring in a context are rigid: inside a proof they behave as unknown fixed types. When a theorem is closed, its type variables are implicitly generalized, and UseTheorem instantiates them.
Named mathematical rules are not additional unchecked primitives. A registered rewrite points to a TheoremId, or to an explicitly admitted axiom declaration. Its pattern and orientation are search metadata. The earlier RuleInstance, Congruence, and TheoremApplication sketches elaborate into the primitive instructions or checked theorem applications described here.
RelApp symmetry, transitivity, congruence, and predicate transport require their own registered theorems. They do not invoke EqSym, EqTrans, or EqSubstitute unless an explicit bridge to kernel equality has been checked. B0 has no arbitrary TrustMe, AssumeTrueInBase, or CurrentUnionFindSaysSo instruction.
20.3 Kernel-facing methods¶
# The checker (judgment_core): pure functions of a view, which never raise
check_proof(view, seq, budget, scratch) -> Result[Facts, Refusal]
check_chunk(view, chunk, budget, scratch) -> ChunkVerdict
check_theory(view, start, end, budget, scratch) -> TheoryVerdict
# Authoring (judgment_shell's Session): each method commits one proof row
Session.hypothesis(assumed) -> Step
Session.imp_intro(frame, step) -> Step
Session.imp_elim(implication, antecedent) -> Step
Session.forall_intro(frame, step) -> Step
Session.forall_elim(step, term) -> Step
Session.transport(step, target, locals, hypotheses) -> Step
Session.convert(step, target, unfold) -> Step
A session method computes its row's stored fields with the construction engine and commits the row; the checker then checks it like any other row (KC1.8), and the session hands out a handle only for a row the checks passed. Only the checker constructs the verdicts that make a row checked (CG8). Automation can commit raw proof candidates freely in its own workspace, subject to its allowance; a failed call truncates the workspace (CG6). The checker and the API guide give the exact signatures.
20.4 Iterative proof checking¶
check(root, expected, limits):
verify expected theory, scope, and proposition
stack:= [(root, Enter)]
visit:= map() # Unseen, Active, Complete
while stack is not empty:
charge_one_check_step(limits)
node, phase:= pop(stack)
key:= check_key(node, theory, scope, kernel_and_checker_versions)
if key has a valid completed memo: continue
if phase == Enter:
reject if key is Active
mark key Active
push(node, Exit)
push unchecked children in deterministic reverse order
else:
validate node's scope and inference tag
read checked child judgments
derive result and dependency summary
validate side conditions and declared endpoints
store completed checked memo; mark key Complete
compare derived root judgment with expected, using only permitted conversion
return the opaque checked root
The implementation does not traverse a proof: every row stores its conclusion, so each row is checked locally against its premises' stored fields, and chunks of rows are checked in parallel (checker, KC1.7 to KC1.12). A real implementation of the traversal above represents imported theorem dependencies as additional checked dependencies of it. Memo keys include the logical interface and versions, not only ProofId. The kernel must recompute or validate imported metadata; a file can lie about its free-variable set, dependencies, or validation stamp.
A checker may reach its resource limit while validating a sound proof. That yields Incomplete, not Invalid and not a theorem. Proof size, substitution output, conversion work, certificate length, and memory all have explicit limits.
Ignoring substitution and conversion costs, traversal is linear in visited proof nodes and premise edges. Those omitted costs may dominate. DAG sharing does not justify claiming that every proof check is linear in the original input expression.
20.5 Definitional conversion¶
Conversion decides definitional equality, the equality the kernel uses when it compares propositions and terms. It recognizes:
| Rule | Meaning |
|---|---|
| α | Equality up to bound-variable names, by de Bruijn indices. |
| β | (λx. b) a reduces to b[a/x]. |
| ζ | let x = v in b reduces to b[v/x]. |
| δ | A transparent definition unfolds to its body (section 19.1). |
| ACU | For a constant declared ACU at a type instance, or, at a class for every type of the class (section 16.5): nesting, argument order, and occurrences of the unit do not matter. |
| Literals | An accelerated operation applied to literals of its kind evaluates to a literal, and comparison or equality of two literals evaluates to True or False (section 20.6). |
It does not perform η-reduction, function extensionality, distributivity, annihilation (0·x = 0), numerical approximation, contextual simplification, or equality saturation.
Canonical construction. The kernel builds every checked term in ACU-and-literal canonical form, through its own term constructors:
- Flatten. An argument that is itself an application of the same ACU operator, at the same type instance, is replaced by its arguments.
- Fold literals. All literal arguments of the operator's bound literal kind are combined by the accelerated operation into one literal. A result equal to the unit is dropped.
- Drop units. Arguments equal to the unit are removed.
- Sort. The remaining arguments are sorted by the kernel's structural order.
- Collapse. No arguments left gives the unit; one argument gives that argument; otherwise the result is the n-ary spine.
The structural order compares structural hashes (computed from content, not from interning order) and breaks ties by full structural comparison, so canonical forms of terms without locals do not depend on the history of a session (locals are ordered by their hash, binding depth and name). Any total order would be sound, since commutativity justifies every permutation. The CAS's chosen display order is applied by printers and normalizers, outside the kernel, and has no proof obligation.
A local's node names its LOCAL row: its binding site. Locals are ordered by their hash, binding depth and name. History independence covers terms without locals and Proven statements: a Proven declares its sequent's canonical closure (Theorem Q-3a). The order breaks the remaining ties, between same-named declarations of sibling theories and between same-named locals at one depth on different chains, by index.
Because checked terms are always canonical, two terms equal modulo ACU and literal arithmetic are the same term, and the inference rules compare premises by identity. Substitution and instantiation rebuild through the same constructors, so instantiating a + b with 2 and 3 yields the literal 5. A constructor that would produce a β-redex (an application whose function is a λ after canonicalization) reduces it at once.
DefEqResult = Equal | Different | Incomplete(reason)
Kernel.defeq(theory, scope, left, right, limits) -> DefEqResult
defeq first compares canonical forms, which are already β-normal. If they differ, it normalizes both sides by ζ and δ, rebuilding canonically, and compares again. Full normalization is the reference semantics; an implementation may unfold definitions lazily, provided it agrees with full normalization on every input. With simple types, acyclic definitions, and canonical ACU forms, this procedure terminates and decides the conversion relation; limits bound its cost.
The implementation has no defeq method. A convert row names its unfolding set \(U\), and its check compares the full unfoldings \(D_U\) of both propositions (Corollary C-8a; KC1.7). The producer's Constructor.convertible(a, b, budget) asks the same question with an empty unfolding set; it is a query that admits no judgment, and running out of budget raises LIMIT (KC1.8).
Different means not equal under this computational conversion, not mathematical disequality. Incomplete is a resource outcome. If an imported definition changes, it has a new declaration identity rather than invalidating a proof invisibly.
Why conversion stays sound. Every identification made by conversion is an instance of a declared law: the ACU theorems, the literal scheme, or a definition's equation. Conversion therefore proves nothing that the declared theory does not, and a theory whose ACU or literal declarations are rejected loses only speed. Annihilation and distributivity stay out because they fail on the extended carrier of section 17.2 (0·∞ is Indeterminate, and ∞ − ∞ is not 0); they are guarded theorems.
20.6 Literal kinds¶
A literal is a term Literal(kind, payload). Its payload is a canonical encoding of a value in termbank's literal pool, so two literals are the same term exactly when they denote the same value. A literal-kind implementation is part of the kernel and of the trusted base. It provides:
| Member | Contract |
|---|---|
| Encoding | A canonical byte encoding and its validation; for example, a rational is reduced, with a positive denominator. Decoding untrusted bytes validates them. |
| Operations | Named operations with their arities, each a total Mojo function on payloads that may decline an input (for example, an inverse of zero, or a result above a size limit). Declining leaves the term unevaluated; it never yields a wrong literal. Whether an operation declines depends only on its input values; addition and multiplication never decline. |
| Predicates | Exact comparison and equality, used for lit(a) < lit(b) and lit(a) = lit(b). |
| Reference | An independent, simple reference implementation used by differential tests (K33). |
| Implementation | Payload | Operations |
|---|---|---|
ExactInteger |
apn_mojo Integer |
add, negate, multiply, power by a small natural exponent; compare, equal |
ExactRational |
apn_mojo Rational, reduced |
the integer operations and inverse of a nonzero value |
FormalPolynomial |
sparse polynomial in indexed indeterminates X₀, X₁, … with rational coefficients, monomials in a fixed order |
add, negate, multiply, power by a small natural exponent; equal |
The kernel's polynomial arithmetic is deliberately simple: schoolbook multiplication over sorted monomials. The fast algorithms of polynomials (gcd, factorization, Gröbner bases) stay untrusted; their results are checked by this arithmetic (section 32.2).
A theory binds an implementation by a LiteralKind declaration (section 19.1), naming the carrier type (a ground type headed by a type constructor) and the constants for each operation. Polynomial kinds also bind operations whose arguments are literals of another kind (an integer literal to an indeterminate, a rational literal to a constant polynomial). Facts about literals such as real(1/2) or ¬integer(1/2) are lemmas of the scalar library, proved per literal by a derived rule rather than evaluated: the kernel evaluates only the operations a literal kind binds. The scalar profile binds ExactRational to Scalar, with +, ·, negation, inverse, <, and kernel equality; every rational literal is then a finite real number of the carrier.
21. Theorem records, guard methods, and support maintenance¶
21.1 Checked theorem and instantiated theorem types¶
GuardedTheorem: # stored only after validation
theory: TheoryId
parameter_types: SliceRef[TypeId]
guard: GuardId
conclusion: PropId # both under the parameter binders
closed_proof: CheckedJudgment # forall params, guard -> conclusion
dependencies: ProofDependenciesId
provenance: Optional[ProvenanceId]
InstantiatedTheorem:
theorem: TheoremId
arguments: SliceRef[CheckedTerm]
context: ContextId
guard: GuardId
conclusion: PropId
implication: CheckedJudgment
TheoremStore.register(record) -> Result[TheoremId, RegistrationError]
TheoremStore.instantiate(theorem, context, arguments) -> InstantiatedTheorem
TheoremStore.apply(instance, evidence_for_guard) -> CheckedJudgment
Registration checks that the closed proof has exactly the advertised quantified shape and no escaped locals or hypotheses. Guard and conclusion metadata must agree with that proposition. Instantiation opens binders through ForallElim; application uses ImpElim. No oracle call is hidden inside either operation.
Two theorems may have the same conclusion but different guards, proofs, costs, or trust dependencies. Retain theorem identity separately from a normalized statement key. A ClosedTheoremId is not manufactured by assigning a new layer to an open result.
21.2 Theorem operations as checked proof construction¶
compose_relation(t1, t2, composition_theorem) -> GuardedTheorem
alternatives(t1, t2) -> GuardedTheorem
weaken_guard(theorem, implication_new_guard_to_old_guard) -> GuardedTheorem
export_to(judgment, outer_context) -> CheckedJudgment
close_global(judgment) -> GuardedTheorem
compose_relation aligns parameter interfaces and the common expression endpoint, assumes the conjunction of both guards, applies the two theorems, and applies the declared composition theorem. It then discharges the guard. Equality transitivity is one instance; error-bound composition uses its own relation and bound arithmetic.
alternatives first aligns parameters and conclusions. It proves the new implication by OrElim with branch proofs, then exports the assumption. An equality between differently presented conclusions needs an explicit bridge before they can be combined.
weaken_guard requires evidence for new_guard -> old_guard. The method name refers to requiring less of the caller, not to removing a conjunct without proof. It also works when the new guard is stronger, but the engine must not describe that as a logical improvement.
21.3 Guard representation and normalization¶
GuardNode = Top | Bottom | Atom(PropId)
| All(SliceRef[GuardId]) | Any(SliceRef[GuardId])
GuardRecord:
node: GuardNode
proposition: PropId
free_locals: LocalSet
structural_hash: Hash
GuardNormalization:
normalized: GuardId
original_to_new: CheckedJudgment
new_to_original: CheckedJudgment
GuardStore.normalize(theory, scope, proposition) -> GuardNormalization
GuardStore.all(children) -> GuardId
GuardStore.any(children) -> GuardId
All([]) is True; Any([]) is False. The proposition view uses a defined binary association. Flattening, reordering, duplicate elimination, identities, annihilators, and absorption are justified with constructive propositional proof templates. normalize returns both implications whenever it changes the advertised logical formula. Structural constructors can be used to define a new formula without a proof, but cannot claim it equivalent to an old formula without that evidence.
B0 does not distribute conjunction over every disjunction. It does not simplify p or not p to True without an admitted principle. An arithmetic implication such as x > 10 -> x > 0 comes from a theorem/solver, not from sorting obligation IDs.
An implementation may delay constructing a normalization proof until an equivalent guard is actually used, but it must retain enough reconstruction information. A delayed proof recipe is not a checked theorem.
21.4 Support entries and safe antichain insertion¶
SupportEntry:
obligations: SortedUniqueList[PropId]
witness: TheoremId # conjunction(obligations) -> conclusion
proof_cost: CostSummary
trust: ProofDependenciesId
SupportBucket:
conclusion_interface: StatementKey
minimal_supports: List[SupportEntry]
other_useful_proofs: BoundedList[TheoremId]
revision: UInt64
A bucket fixes the theory interpretation, parameter interface, and exact conclusion. Different contexts or renamed parameters are not compared by raw IDs until a checked alignment is available.
insert_support(bucket, S, witness):
validate witness matches conjunction(S) -> bucket.conclusion
S:= sort_and_deduplicate_with_corresponding_proof(S)
if some existing T is a subset of S:
consider witness for proof-cost/trust alternatives
return NoApplicabilityChange
remove applicability entries U for which S is a strict subset of U
add (S, witness)
retain a deterministic bounded set of entries if over budget
increment bucket revision only if its retained state changed
Removing a superset from the applicability antichain does not delete proof objects still referenced elsewhere. A shorter proof under a stronger guard may remain in other_useful_proofs. Trust requirements and output objectives can justify retaining alternatives that logical subsumption alone would discard.
For joint premises, enumerate unions of support sets lazily and construct each corresponding composition proof. For alternative derivations, merge support entries and construct disjunction proofs only when needed. Enforce work limits during enumeration, not after allocating a complete Cartesian product.
The retained support family is a sufficient under-approximation of available proof opportunities: its disjunction implies the conclusion. It is not asserted to be equivalent to the theorem's full guard or to enumerate all derivations. Dropping a complete alternative is safe; deleting one required obligation is not. With k retained entries and at most s obligations each, straightforward sorted-array subset testing costs O(k s) per insertion; generating all joint candidates can still have combinatorial cost.
21.5 Guard activation and proof-valued watchers¶
GuardInstanceKey = (ContextId, GuardId, ParameterInstantiationId)
GuardActivation:
key: GuardInstanceKey
child_evidence: List[Optional[CheckedJudgment]]
completed_children: BitSet
current_evidence: Optional[CheckedJudgment]
parents: List[GuardInstanceKey]
A conjunction activates only after all children have checked evidence. A disjunction can activate through evidence for any child or through evidence for the whole disjunction. The latter is essential when neither disjunct is individually known. Watcher completion produces a proof using introduction rules or reuses the already proved whole formula; it does not set an unproved Boolean flag.
The activation state is tied to an immutable context and typed instantiation. Arrival of a better proof can update evidence without changing logical truth; use separate truth and evidence revisions so proof optimization does not restart all fact inference unnecessarily.
22. Goal graph, event scheduling, and dependency-aware caching¶
22.1 Goal and derivation records¶
GoalKey:
theory: TheoryId
context: ContextId
proposition: PropId
evidence_policy: EvidencePolicyId
SearchStatus = Pending | Queued | Running | Waiting
| Exhausted | Cancelled | Finished
GoalRecord:
key: GoalKey
search_status: SearchStatus
proof: Optional[CheckedJudgment]
negation_proof: Optional[CheckedJudgment]
alternatives: List[DerivationId]
dependents: List[DerivationId]
attempts: List[AttemptId]
DerivationRecord:
conclusion: GoalId
premises: List[GoalId]
scope_maps: List[ScopeTransition]
recipe: ProofRecipeId
solved_slots: BitSet
status: Waiting | Ready | Rejected | Accepted
ProofRecipe is an untrusted program of proof constructors with explicitly typed premise slots. Slots may be filled only with checked judgments matching the required proposition and scope. A recipe that discharges a hypothesis or introduces a parameter records that scope transition. It cannot fill an outer goal with an inner proof and omit the discharge.
Exhausted means the configured strategies or resources produced no proof. It is not Refuted. A negation proof is evidence for the exact proposition's negation. If the context establishes both a proposition and its negation, the coordinator derives a contradiction and reports the context as inconsistent.
Goal interning initially uses exact stable syntax, context identity, and evidence policy. Definitionally equal or logically equivalent goals can be connected by a checked conversion/transport; they are not merged on the basis of a speculative workspace root. A proof that rests on an imported statement can solve a goal whose policy accepts that import source while leaving a stricter goal for the same proposition unresolved. Shared evidence stores retain alternatives, so a later replayed proof (tier 2) can satisfy the stricter goal.
22.2 Coordinator API¶
Coordinator.request_goal(specification, evidence_policy) -> GoalId
Coordinator.add_derivation(conclusion, premises, transitions, recipe) -> DerivationId
Coordinator.publish(candidate: EvidenceCandidate) -> PublicationResult
Coordinator.request_transform(request) -> RequestId
Coordinator.run(request_id, budget) -> RunReport
Coordinator.resume(request_id, extra_budget) -> RunReport
Coordinator.cancel(request_id) -> Unit
A request may share already interned goals and checked facts with another request in the same logical context, but its budget and cancellation state remain separate. Provisional facts are never shared between requests (K30). Canceling one request does not invalidate a theorem or cancel a shared goal still needed by another request. A result is immutable once checked; new evidence can supersede a chosen result without mutating its meaning.
Strategies. A CAS command is not a single proof goal: Simplify, Expand, Together, and Solve each mean a particular choice of engines, rules, objective, and budget. The coordinator therefore accepts named strategies:
Strategy:
name: StrategyName # simplify, expand, together, solve,...
engines: List[EngineSelection] # with their law bundles
rule_sets: List[BundleId]
objective: ObjectiveId # for example, leaf count with deterministic structural tie-breaks
budget: WorkBudget
evidence: EvidencePolicyId # generic or strict, checked or unchecked
Coordinator.run_strategy(strategy, request) -> RunReport
A strategy is configuration, not trusted code. Two strategies may return different answers for the same input; both answers are checked.
22.3 Deterministic worklist algorithm¶
run(request, budget):
queue initial goals and applicable cheap engines
while eligible events remain and budget has resources:
event:= take_next_fair_event()
charge event and engine work
proposals:= dispatch_read_only(event, per_engine_budget)
for proposal in stable_order(proposals):
if proposal is Need:
intern goal and install dependency
elif proposal is Derivation:
register its premise slots and recipe
elif proposal is EvidenceCandidate:
result:= kernel.check(proposal.proof, proposal.claim, check_budget)
if result is Checked:
publish_checked(result)
elif result is Invalid:
record rejected proposal; do not publish
else:
retain resumable validation state if budget allows
elif proposal is Unknown:
record versioned attempt and retry dependencies
enqueue newly ready derivations and guard activations
return report with checked results, unresolved goals, and stop reason
Use deterministic FIFO queues within priority classes and weighted round-robin service across classes. This provides service to lower-priority work without making a general completeness promise. Coalesce duplicate events by their exact event key and generation. No wall-clock timing is used to decide a proof's validity. An optional wall-clock cap may stop a run, and the report marks that stop as nondeterministic.
When a derivation becomes ready, fill its slots with concrete checked proofs, expand the recipe to a finite candidate proof DAG, and check the conclusion. Do not accept a recipe because its advertised premises have matching text. Endpoint, substitution, and scope checks remain mandatory.
The search graph can contain a cycle, such as demands for P through Q and Q through P. Interning prevents endless creation of duplicate goals. Without an established base fact, the cycle remains waiting. Queue quiescence yields unresolved goals; it does not turn the cycle into a proof or prove its goals false.
22.4 Checked fact publication¶
ContextFactState:
facts: Map[PropId, EvidenceCandidates]
fact_revision: UInt64
evidence_revision: UInt64
relation_versions: Map[RelationHead, UInt64]
contradictions: List[CheckedJudgment] # selected by request evidence policy
publish_checked(j):
verify j's handle belongs to this kernel/store and accepted theory
validate j's interface in the target context or require a ContextMap
retain j as evidence for its exact proposition
if the proposition is new: increment fact and relevant relation revisions
if only evidence improved: increment evidence revision
notify goals, guard watchers, and engines whose policies admit the evidence
check whether policy-compatible opposite propositions yield False
retain contradiction evidence with its complete dependency profile
Absence of a contradiction proof means not known inconsistent, not proved satisfiable. The normal result path reports an established contradiction explicitly instead of silently returning an arbitrary expression by explosion. Lower-level proof export may still record a theorem with inconsistent assumptions, correctly labeled by its guard.
Fact indexes may retain evidence for several policies. QueryView, guard activation, and contradiction reporting expose only evidence permitted by the current request. A contradiction derived with classical principles or from imported statements must not contaminate a request whose policy excludes them.
Publication is transactional: validate before mutating authoritative fact indexes. Allocation failure or an engine exception must not leave a partly published fact. Extra interned syntax left behind after a failed proposal is harmless because syntax alone establishes nothing.
22.5 Attempts, dependencies, and unknown answers¶
ReadDependency =
FactRelation(context, head, revision)
| FactSet(context, revision)
| AnalysisValue(workspace, key, revision)
| EqualityState(workspace, generation)
| TheoremIndex(index, revision)
| SearchAssignments(scope, revision)
| SolverState(engine, context, revision)
UnknownReason = Unsupported | MissingEvidence | WorkLimit | CheckLimit
| ExternalUnknown | EngineFailure
AttemptRecord:
goal: GoalId
engine: EngineVersionId
configuration: StrategyDigest
reads: List[ReadDependency]
allowance: BudgetSummary
outcome: UnknownReason
An attempt can be reused only while all relevant read versions are unchanged and no materially larger resource allowance warrants retrying it. A failed lookup depends on the relevant relation or fact-set version, not just the objects it happened to find. Start with conservative context-wide versions for opaque solvers; refine to finer dependencies only when the read contract is reliable.
A cache keyed only by proposition classes would be unsafe: a newly proved x > 10 can invalidate an unknown answer about x > 0 even if neither proposition's e-class changes. Engines access state through an instrumented QueryView or explicitly declare broad dependencies; an untracked read makes an unknown cache entry unsafe for completeness.
Positive and negative proofs are durable under compatible strengthening. Their availability in a different context still requires transport. Cached search outcomes are not durable theorems.
22.6 SMT/entailment adapter contract¶
EntailmentResult =
Established(proof_of_P)
| Refuted(proof_of_not_P)
| Inconsistent(proof_of_False)
| Unknown(reads, reason)
For a classical SMT adapter, proving unsatisfiability of Gamma and not P can justify P only through the declared classical bridge and a checked or explicitly trusted certificate. Proving unsatisfiability of Gamma and P justifies not P. A satisfying countermodel to Gamma and not P does not prove Gamma |- not P; it shows that P is not entailed, subject to the model's validated interpretation. Solver unknown, timeout, unsupported input, and lack of a model certificate remain unknown outcomes.
An explicitly trusted answer is not a trusted rule: the kernel has no oracles. A decider's answer enters a derivation with a certificate that the kernel checks by its own rules, or as a hypothesis, so that the checked result is the guarded theorem claim ⇒ result, whose label names the decider; a later certificate discharges the hypothesis. MetiTarski's RCF decisions follow the same rule.
23. Engine protocol, theorem lookup, and relational inference¶
23.1 Common engine types¶
EngineDescriptor:
id: EngineVersionId
capabilities: Set[Capability]
supported_profiles: Set[SemanticProfileId]
evidence_modes: Set[EvidenceMode] # native proofs, or results resting on imported statements
subscriptions: Set[EventKind]
Capability = Prove | Rewrite | Normalize | Propagate | Congruence | Saturate
| Elaborate | ExportProof
EvidenceMode = Native | RestsOnImportedStatements
EngineEvent = NewGoal(GoalId) | NewFact(CheckedJudgment)
| GuardReady(GuardInstanceKey) | DependencyChanged(ReadDependency)
| TransformRequest(RequestId) | Resume
EngineDelta:
obligations: List[GoalRequest]
derivations: List[DerivationProposal]
evidence: List[EvidenceCandidate]
conversions: List[ConversionCandidate]
attempts: List[AttemptRecord]
Engine.step(query_view, event, budget, candidate_builder) -> EngineDelta
QueryView exposes declarations, scoped syntax, checked facts eligible under the request's evidence policy, and dependency-tracked workspace reads. The candidate builder allocates syntax and proof recipes but cannot mint checked judgments. An engine may call kernel constructors to obtain genuinely checked judgments; it still cannot bypass publication policy or change another engine's state directly.
An engine returns new obligations instead of recursively running the whole coordinator. Its own computation must be interruptible under its work allowance. Unsupported input is a normal outcome, not permission to reinterpret an operator or silently apply a more permissive semantic profile.
23.2 Theorem matching and discrimination indexes¶
TheoremIndex:
by_conclusion: DiscriminationTree[TheoremId]
by_lhs_head: Map[TypedHeadKey, List[RewriteRuleId]]
RewriteRule:
theorem: TheoremId
lhs_pattern: PatternId
rhs_pattern: PatternId
guard_pattern: PatternId
direction: Forward | Reverse
priority: Int
selection: Optional[SearchPredicateId]
An index returns candidates, not proofs. Patterns over sorted type variables match only types of their sorts, so a class theorem is found at every instance of its class and never outside it. B0 matching assigns theorem pattern parameters against rigid scoped terms of compatible types. A repeated pattern parameter must match the same syntax modulo allowed computational conversion. When equality-aware matching permits different representatives, it must return the equality/morphism evidence explaining that match.
MatchResult:
substitution: TypedSubstitution
origin_terms: SliceRef[TermId]
bridges: SliceRef[CheckedJudgment or ProofRecipeId]
reads: List[ReadDependency]
After matching, instantiate the theorem using its original parameter terms. Construct any bridges needed between the literal instance and the actual matched expression. The final guard/support includes all bridge assumptions. Replacing the stored parameter values by current e-class roots and forgetting the old values is prohibited.
A selection predicate such as “not already merged” can suppress redundant work. It cannot establish a validity premise. Reverse rewriting is permitted only when the theorem's relation supports the required reversal; a theorem about an inequality cannot be reversed as though it were symmetric equality.
23.3 Semi-naive relational propagation¶
The existing relational machinery should be reused as a fact engine. Preserve literal fact tuples and their evidence; canonicalized index tuples are derived views.
For a finite set of fixed rules and a fixed finite active term domain, a non-generative rule body is a conjunction of fact relations. Semi-naive evaluation forms rule instances in which at least one premise comes from the current delta. Each successful join records the premise evidence and creates a theorem-application recipe for the head.
propagate(context, changed_relations):
for each affected rule and selected delta premise:
enumerate joins using the current fact indexes
validate typed substitutions and equality bridges
construct a head-proof candidate from the premise proofs
send the candidate to checked publication
Deduplicate rule instances by rule identity, typed substitution, context, and relevant evidence/interface identity. Equality rekeying can create new join opportunities even without new literal propositions, so equality-view changes must produce appropriate index deltas. A tuple canonicalized under one context is not reused in a sibling context without evidence.
Termination of the fixed-domain fact closure does not imply termination when a rule constructs new terms, when another engine keeps enlarging the domain, or when the rulebook changes. Such work is budgeted and reported as generative. Query planning, indexes, and joins are untrusted search machinery; proof validation protects the output.
23.4 Certificate interface¶
CertificateEnvelope:
checker: CheckerId
checker_version: VersionDigest
claim: JudgmentSpec
premises: SliceRef[CheckedJudgment]
payload: ByteSlice
payload_digest: Digest
CertificateChecker.validate(envelope, read_only_theory, limits)
-> ValidatedCertificate | Invalid | Incomplete
A checker validates the exact claim, context, operators, and premises. It must not consult a mutable e-graph as evidence or accept a certificate because an engine ID is familiar. New checker code is an explicit extension of the trusted base unless its output is reconstructed entirely into already accepted kernel rules. Its identity and version appear in proof dependencies.
B0 has no automatic execution of code named in an imported artifact. The importer resolves checker IDs against an explicitly allowed local registry and rejects unknown versions or requests for unrestricted execution. A certificate's digest detects alteration; it does not prove mathematical validity.
23.5 Semantic analyses¶
AnalysisDomain:
initial(term, profile) -> AbstractValueId
refine(previous, incoming) -> AbstractValueId
transfer(head, argument_values) -> AbstractValueId
candidate_fact(value, requested_predicate) -> Optional[EvidenceCandidate]
AnalysisEntry:
context: ContextId
subject: TermId or WorkspaceClassId
value: AbstractValueId
revision: UInt64
justification_data: AnalysisCertificateId
The domain contract supplies a concretization meaning: what possible values the abstract value includes. A sign or interval fact is justified only if the approximation and its transfer/certificate support it. A host-language True from an analysis callback is not a theorem.
For possible-value sets, greater information corresponds to smaller sets; combining sound observations may intersect them. An empty result requires evidence of contradiction or an error report, not silently classifying every predicate as true. The facts used in refinement contribute their contextual dependencies.
No termination claim follows merely from calling refine a lattice operation. A domain declares a finite-height policy, a bounded iteration policy, or a sound widening strategy. Widening cannot falsify a previously checked theorem, and its less precise result cannot justify stronger new facts. Analyses in cyclic expression graphs start from sound information; a circular self-supporting refinement is not a certificate.
24. Contextual congruence and optional equality saturation¶
24.1 Eligibility and workspace state¶
CongruenceProfile:
relation: RelationId
carrier: TypeId
reflexivity: TheoremId
symmetry: TheoremId
transitivity: TheoremId
head_laws: Map[TypedHeadKey, TheoremId]
EqualityWorkspace:
context: ContextId
profile: CongruenceProfileId
evidence_policy: EvidencePolicyId
generation: UInt64
class_parent: Array[WorkspaceClassId]
class_size: Array[UInt32]
terms: Map[TermId, WorkspaceClassId]
use_lists: Map[WorkspaceClassId, List[ApplicationId]]
signatures: Map[CongruenceSignature, ApplicationId]
reasons: AppendOnlyList[EqualityReason]
rebuild_queue: Queue[ApplicationId]
The profile is validated against the exact relation, carrier, and typed head declarations. B0 supports only heads whose required relation-respect theorem is applicable. A morphism with extra instance-dependent guards is not unconditional congruence: it must discharge those guards before a merge, or remain outside the automatic congruence path.
A workspace for ordinary kernel equality can use the kernel's equality rules. A workspace for a different equivalence relation must construct its explanations through the declared laws. Predicates about members are transported only when they respect that relation; facts are not substituted through arbitrary equivalences automatically.
24.2 Workspace API¶
Equality.open(context, profile, evidence_policy) -> WorkspaceId
Equality.add(workspace, checked_term) -> WorkspaceClassId
Equality.assert(workspace, checked_relation_judgment) -> MergeResult
Equality.find(workspace, term) -> ClassObservation
Equality.explain(workspace, left, right, limits) -> ProofCandidate | Unknown
Equality.rebuild(workspace, budget) -> RebuildReport
Equality.refresh(workspace, new_checked_facts, budget) -> RebuildReport
Equality.drop(workspace) -> Unit
ClassObservation is search data, not a checked equality. assert requires a matching relation judgment whose interface is available in the workspace's context. It rejects an undisclosed guard or a proof from an incompatible sibling context. The API names the workspace explicitly rather than relying on a hidden global active layer. A workspace materializes only equalities admitted by its evidence policy. A stricter request uses a suitable separate/replayed workspace; it cannot reuse a partition containing merges that rest on disallowed imported statements merely because its context and carrier match.
Use union by size with deterministic tie-breaking for the baseline. Keep proof reasons separate from the parent forest so path optimization cannot erase the evidence needed for explanation. Existing sparse layered union-finds may implement this interface once they meet its invariants. Where an inherited-state refresh is difficult to validate, discard and replay the affected derived workspace rather than guessing at a correct rekeying.
24.3 Congruence rebuilding¶
rebuild(workspace, budget):
while dirty applications remain and budget permits:
app:= take_dirty_application()
key:= (typed_head(app), current_classes_of_arguments(app))
if an existing application other has this key:
freeze proofs relating each original argument pair
obtain the applicable head-respect theorem and any extra guard evidence
build the exact relation proof for app and other
validate that proof before committing the certified merge
update signature index and enqueue affected parent applications
A dirty signature identifies a candidate pair, not a valid inference by itself. The original term arguments, their orientation/pairing, and the head law are recorded. Proof dependencies are frozen when the inference is made; later equality changes must not change the explanation's premises.
EqualityReason =
Asserted(CheckedJudgment)
| Congruent(original_left, original_right,
head_law, argument_proofs, guard_proofs)
Lean's grind source explicitly documents a circular-reconstruction failure caused by losing whether a congruence step used ordinary or swapped argument pairing. The lesson here is to retain the actual derivation data rather than reconstructing a different argument from the final class partition. 31
The certified workspace path checks derived merges. An optimized speculative workspace may instead retain well-founded proof recipes, but it stays isolated and cannot publish facts until their proofs pass the kernel. Theorems never reference a live workspace as their evidence.
Raw term interning is not asked to simplify an application mathematically during rebuild. Any canonicalization beyond the declared computational conversion is another theorem-producing step. This prevents a congruence reason from hiding an assumption-sensitive canonicalizer call.
24.4 Equality-saturation strategy¶
Saturation is a client of the workspace interface:
- Freeze a consistent search view of the certified equality state and indexes.
- Enumerate relevant theorem instances, retaining substitutions and matching proofs.
- Submit guards as goals, or construct guarded conversion candidates without merging them.
- Materialize only instances whose guards are established in the workspace context.
- Rebuild congruence, publish checked consequences, and repeat within budgets.
A theorem guarded by G can be stored globally before G is known. It cannot join two classes in the base context for that reason alone. A branch can explicitly assume G, run its own workspace, and export a theorem afterward.
Saturation stops on quiescence or a reported limit. A finite term budget is not a proof of saturation completeness. Subsumption and scheduling affect which candidates are searched, not what an existing theorem states.
24.5 Extraction and proof reconstruction¶
The initial tree extractor works on a frozen finite workspace with nonnegative, additive integer node costs. Each selected candidate retains an immutable extraction witness referencing concrete child witnesses. Compare (cost, height, stable_tiebreak) and avoid changing a witness's children after it is selected. This prevents a zero-cost cyclic e-class from producing an infinitely recursive extracted expression.
Build the selected expression in raw termbank syntax. Use the retained equivalence and congruence evidence to prove the relation between the original input and this constructed expression. Passing through a class ID is insufficient. Check the final proof before returning a strict result.
The original input remains available as a fallback even if a search strategy subsumes its row. DAG-cost optimization is a separate strategy with its own global sharing choices; it is not implemented by changing only a local tree-cost callback. Arbitrary user cost functions require a declared termination/budget policy rather than inheriting the baseline extractor's guarantees.
25. Conversions, certified normalization, and result selection¶
25.1 Transformation request and candidate types¶
TransformRequest:
theory: TheoryId
context: ContextId
input: CheckedTerm
relation: RelationId
mode: Strict | Conditional | Piecewise
objective: ObjectiveId
allowed_trust: TrustPolicyId
budget: WorkBudget
ConversionCandidate:
input: TermId
output: TermId
relation_claim: PropId
guard: GuardId
proof: ProofCandidateId or CheckedJudgment
pending: List[GoalId]
cost: CostSummary
CheckedConversion: # no unresolved proof holes
input: CheckedTerm
output: CheckedTerm
relation_claim: PropId
guard: GuardId
implication: CheckedJudgment # guard -> relation_claim
parameter_interface: ScopeInterfaceId
A reusable CheckedConversion has no undisclosed proposition-hypothesis dependencies: all such dependencies are closed into its guard. Its free term parameters remain explicit until a theorem is universally closed. A search candidate may have holes; it is not a checked conditional result until the implication itself is proved.
The guard can include facts already available in the caller's context. Removing those facts from the displayed extra condition requires a checked relative implication, not a string operation. The globally reusable guarded theorem remains available independently of how its condition is presented to one caller.
25.2 Result variants¶
TransformResult =
StrictResult(output, checked_relation_in_request_context, report)
| ConditionalResult(output, extra_guard,
checked_implication_in_request_context, report)
| PiecewiseResult(branches, checked_coverage, checked_piecewise_relation, report)
| NoResult(unresolved_goals, stop_reason)
| InconsistentContext(checked_contradiction, report)
StrictResult requires evidence that the requested context satisfies the candidate's guard. ConditionalResult requires a checked extra_guard -> relation(input, output) in that context. PiecewiseResult needs both coverage and a valid theorem connecting the piecewise expression to the input; branch-local equalities alone are insufficient. Overlapping cases require an explicit priority semantics or agreement proofs, and the declared treatment of undefined branches must be preserved.
Every variant also carries an EvidenceLabel (section 30.2): the checking level, Checked by default or Unchecked in the explicit fast mode, and the dependency classes of its evidence. In the default generic mode of the CAS, a request's policy accepts a ConditionalResult whose extra guard consists only of finiteness and nonzero conditions on its inputs; the CAS shows the answer and keeps the guard available for display.
Validity is a hard filter. The objective ranks only appropriately checked candidates and cannot trade an unresolved validity premise for a smaller expression. Trust policy is another filter: a theorem with forbidden admitted dependencies is not selected merely because it is short.
For a reflexive equivalence relation, the input and its reflexivity proof provide a safe fallback. A transformation request for a nonreflexive relation may have no analogous fallback and returns NoResult. A known inconsistent guard may be discarded as unhelpful; absence of an inconsistency proof does not establish guard satisfiability.
25.3 Conversion combinators¶
The interface follows the proof-producing conversion idea in Isabelle but makes guards, budgets, and errors explicit. 28
identity(relation_profile) -> Conversion
then(first, second, composition_law) -> Conversion
or_else(first, second) -> Conversion
try_(conversion, reflexivity_law) -> Conversion
repeat_changed(conversion, limits) -> Conversion
under_head(head, child_conversions, morphism_law) -> Conversion
under_binder(conversion, binder_law) -> Conversion
then composes the relation proofs and combines guards. or_else chooses a search alternative; it does not derive an object-level disjunction. It may recover from NoMatch, Unsupported, or a configured resource stop, but it records an invalid proof or internal error instead of silently treating it as a normal failed match.
repeat_changed requires a checked new result at every accepted step, charges every iteration, and detects repeated syntax. A claimed reducing order must be validated or treated as a heuristic; termination does not follow from the function's name.
under_head instantiates a relation-respect theorem. under_binder opens a fresh local, transforms the body, and then closes it with the required binder-respect theorem. A guard G(x) obtained under a bound variable cannot escape as a free outer assumption. The enclosing transformation may require forall x, G(x), a domain-restricted universal condition, or another proved sufficient guard. Pointwise body evidence does not automatically establish equality of whole functions or integrals.
25.4 Sparse polynomial normalizer¶
This normalizer is the polynorm engine, built on formal polynomials as a literal kind (section 32.2). The kernel's polynomial arithmetic makes expansion a literal computation. The engine's proof only reifies each side as the evaluation of a formal polynomial, one homomorphism theorem per operator occurrence, so the proof grows with the input, not with the expanded output. The representation below is the engine's working form:
Monomial = SortedList[(VariableIndex, NonnegativeExponent)]
Polynomial[C] = SortedMap[Monomial, ExactCoefficient[C]]
ReifiedPolynomial:
variable_terms: List[CheckedTerm]
polynomial: Polynomial
domain_guard: GuardId
reification_certificate: CertificatePayload
The coefficient domain is an explicit exact-ring interface; the generic kernel does not hard-code machine floats. A practical first instance can use exact integers or rationals supplied by the CAS. Canonical monomials have unique variable indices and omit zero exponents; zero coefficients are removed by checked exact coefficient operations.
Reification accepts only the declared ring operators and literal interpretation. Unsupported subexpressions can become opaque ring variables only when their carrier/domain membership is justified. For lifted partial expressions, the normalizer retains the definedness/domain obligations needed to apply the ordinary ring laws.
The algorithm traverses the expression bottom-up. Constants and variables produce singleton maps; addition merges coefficients; multiplication combines monomials and accumulates coefficient products; natural powers use finite repeated squaring or another certified exponentiation algorithm. Compare normalized maps to test a polynomial identity, and produce a certificate of the reification and equality.
With m and n monomials, a straightforward multiplication considers m*n pairs before collection. Expanded normal forms can be exponentially larger than the input. Charge monomial counts, coefficient bit complexity, and output allocation throughout; stopping early yields an unresolved candidate, not an approximate exact identity.
25.5 Rational normalization and denominator conditions¶
A rational normalizer may compute numerator/denominator polynomial pairs and a reduced result, but it must preserve the original expression's domain under the requested semantics. A certificate records the exact algebraic identity and a sufficient nonzero/definedness guard for every division and cancellation it uses.
RationalCertificate:
original_term: TermId
proposed_term: TermId
polynomial_data: PolynomialCertificatePayload
domain_guard: GuardId
division_steps: List[CheckedDivisionObligation]
The certificate checker verifies that the guard justifies both values and the claimed relation. Equality in a rational-function field is not accepted as strict pointwise equality without the bridge. Rocq's field-normalization pattern is a useful model for making nonzero side conditions explicit, not a substitute for validating this implementation's semantics. 17
Worked trace in the scalar profile for (x² - 1)/(x - 1) under x > 2:
| Step | Concrete object or operation |
|---|---|
| 1 | A TransformRequest names the scalar profile, the session constant x, the input term, and context x > 2. |
| 2 | Reification produces polynomial data, candidate x + 1, and sufficient guard x != 1. |
| 3 | The normalizer emits evidence for x != 1 -> strict_eq(input, x + 1); all hidden embeddings/definedness obligations are checked. |
| 4 | The coordinator interns GoalKey(context, x != 1) and reuses or requests arithmetic evidence. |
| 5 | A theorem or checked arithmetic certificate derives x != 1 from x > 2. |
| 6 | TheoremStore.apply constructs the strict equality in the request context. |
| 7 | The objective compares this checked candidate with the identity fallback. |
| 8 | StrictResult returns x + 1 with the proof; a closed guarded theorem may be retained for sibling contexts. |
Without suitable assumptions, the same normalizer can return a checked conditional result with guard x != 1. At x = 1, it must not return x + 1 as an unconditionally equivalent expression. No equality workspace is required for this pipeline.
26. Persistence, failure handling, acceptance tests, and validation contracts¶
26.1 Portable theorem bundles¶
TheoremBundle:
format_version: FormatVersion
kernel_profile: KernelProfileId
theory_declarations: TopologicallyOrderedDeclarations
types_and_terms: SerializedSyntaxDAG
proof_interfaces: SerializedScopes
proofs: TopologicallyOrderedProofDAG
theorems: List[ClosedTheoremRecord]
certificate_versions: List[CheckerVersionId]
import_sources: List[ImportSourceRecord] # imported statements the theorems rest on
provenance: Optional[SourceAndDerivationMetadata]
OpenTheory articles are the second portable format: standard articles for exchange with other HOL systems and for the independent audit, and extended articles for Isabelle's theories with their classes (section 28.5). judgment_store reads and writes both.
Serialization remaps the bank's row ids to the partition's row numbers (ST9). Logical content hashes exclude process-local validation stamps and mutable workspace identities. Stable identities include the declaration interpretation, binder structure, and dependencies; a same-named constant in an unrelated theory is not the same declaration.
Import validates sizes, tags, bounds, dependency ordering, scopes, declaration compatibility, and permitted checker versions, then rechecks proofs. It never deserializes a CheckedJudgment stamp as authority. Unavailable prerequisites yield a dependency error; unsupported or resource-limited checking yields an incomplete import, not an accepted theorem.
Even a closed theorem can contain internal implication/quantifier proof nodes referring to bound hypotheses and locals. Retain or serialize the required immutable proof interfaces and declaration frames. Dropping a solver workspace is safe; dropping logical scope data still needed to replay a retained proof is not.
26.2 Ownership and garbage collection¶
The bank is append-only during a session, and its workspaces are truncated or discarded independently (TD1.12). Roots include retained theorems, checked user results, active requests, and pinned certificates. Before introducing incremental reclamation, implement a complete reachability traversal from those roots across proof, theorem, syntax, scope, and declaration references.
At a quiescent boundary, unreferenced transient candidates can be discarded. Reclaiming durable storage requires either nonreused IDs, a verified remapping of every live reference, or generations that make stale references fail. Reference counts alone do not describe all search-graph cycles, although accepted proof dependencies remain acyclic.
A dropped workspace cannot invalidate a retained theorem because no theorem depends on a workspace ID for its truth. It may invalidate a cached unknown attempt or a search representative; those entries are explicitly transient.
26.3 Error taxonomy and reports¶
CheckError = IllTyped | UnboundVariable | EscapingLocal | MissingHypothesis
| WrongConclusion | WrongRelation | WrongEndpoint | InvalidSubstitution
| IncompatibleTheory | InvalidCertificate | CyclicEvidence
| InvalidReference | UnsupportedKernelFeature
CheckStop = WorkLimit | MemoryLimit | CertificateLimit | ConversionLimit
SearchStop = Quiescent | GoalEstablished | BudgetExhausted
| Cancelled | InconsistentContext | EngineFailure
Errors include the offending node/claim and a diagnostic path without converting the error into a logical assertion. Resource exhaustion is distinguished from invalid evidence. An engine failure can coexist with useful checked results from other engines; the run report states both rather than treating the entire computation as a theorem or hiding the failure.
RunReport:
stop_reason: SearchStop
checked_results: List[ResultId]
unresolved_goals: List[GoalId]
admitted_dependencies: ProofDependenciesId
rejected_candidates: DiagnosticSummary
engine_work: Map[EngineVersionId, WorkCounters]
checking_work: WorkCounters
reproducibility: Deterministic | WallClockLimited
No count of successful rewrites, saturated classes, or solver calls is a soundness certificate. Those counters measure search only.
26.4 Adversarial and property-based acceptance tests¶
These are required tests for an implementation of the design, not reports of tests run against this note.
| ID | Test | Required outcome |
|---|---|---|
| A01 | Apply x/x = 1 without nonzero/definedness evidence. |
Keep guarded or unresolved; no unconditional certified merge. |
| A02 | Apply that theorem under x > 0, then query a sibling with x = 0. |
The sibling does not inherit the conditional equality. |
| A03 | Use not_yet_merged(a,b) as a proposed proof of a != b. |
Reject the evidence. |
| A04 | Exhaust every selected strategy for P. |
Return unknown/exhausted, not a proof of not P. |
| A05 | Cache unknown for x > 0, then publish x > 10. |
Retry the dependent obligation even if its expression classes did not change. |
| A06 | Substitute a term containing a loose bound variable under a nested binder. | Shift correctly; no capture. |
| A07 | Reuse an open-term type cache in a different binder environment. | Miss or revalidate the cache; do not accept an ill-typed application. |
| A08 | Generalize a local still free in an undischarged hypothesis. | Reject the introduction/export. |
| A09 | Use two same-named locals or same-shaped hypotheses at different binding sites. | Preserve their identities; use explicit renaming/transport when valid. |
| A10 | Assign a metavariable a term containing itself indirectly or an unavailable local. | Reject and restore the assignment trail. |
| A11 | Submit a proof recipe with an unresolved goal slot. | Reject as incomplete evidence. |
| A12 | Provide P -> Q and not P -> Q without coverage. |
Do not derive unconditional Q in the constructive profile. |
| A13 | Provide a proof of P or Q, but neither disjunct individually. |
Permit valid disjunction elimination and whole-guard activation. |
| A14 | Prune a bounded support family. | Every retained entry still proves the conclusion; no conjunct disappears without evidence. |
| A15 | Form and_i(a_i or b_i) for increasing i. |
Keep the factored guard; stop support expansion within budget. |
| A16 | Create the goal cycle P <- Q <- P without a seed proof. |
Leave unresolved; no self-supporting evidence. |
| A17 | Reconstruct congruence after additional merges obscure the original argument pairing. | Use frozen reasons; no circular reconstruction. |
| A18 | Merge different types, different relations, or relations lacking the required head law. | Reject the merge. |
| A19 | Normalize through a context-sensitive termbank canonicalizer without proof. | Detect/reject the unsupported equality step. |
| A20 | Compose two bounded-error relations at a fixed tolerance. | Produce the justified combined bound, not an exact equality class. |
| A21 | Transform a lambda/integral body under a local guard G(x). |
Close/generalize the guard appropriately; no escaping free x. |
| A22 | Extract from a cyclic or zero-cost equality graph. | Produce a finite witness and checked output, or a reported limit. |
| A23 | Import the same declaration name with different contents or a forged digest/stamp. | Reject incompatible identity or revalidate; never trust a stamp/hash as a proof. |
| A24 | Import a theorem-reference cycle or malformed certificate payload. | Reject safely within resource limits. |
| A25 | Delete every search/equality workspace and replay retained theorem bundles. | Theorems remain checkable with their logical dependencies. |
| A26 | Reach a checking limit on a valid large proof. | Report incomplete checking; do not classify the theorem as false. |
| A27 | Interpret a rational-field identity as strict partial-expression equality at a singular point. | Require the semantic bridge and domain guard. |
| A28 | Publish P and not P in one context. |
Produce an explicit inconsistency report for ordinary CAS requests. |
| A29 | Run without saturation, with congruence only, and with budgeted saturation. | All returned proofs validate; quality/cost may differ. |
| A30 | Introduce a ported upstream component without its pinned source record/notices. | Fail the development/release provenance gate. |
Additional property tests check substitution identities, alpha-renaming invariance, weakening/transport composition, theorem export followed by application, support-antichain subset invariants, and preservation of proof meaning under serialization and row renumbering. Differential tests against Isabelle or Lean are used only on a deliberately matched logical/semantic fragment. They are useful diagnostics, not a replacement for the kernel's soundness argument.
26.5 Kernel validation¶
The acceptance specification defines the kernel's regression obligations. Package builds, source boundaries, public docstrings, reference models, malformed inputs, and test variants are checked by the development gates. Validation must cover rejected inputs and resource exhaustion as well as successful proofs.
27. Independently usable packages and dependency contracts¶
27.1 Meaning of self-contained¶
The system is delivered as independently buildable and testable native packages, not merely folders inside one inseparable reasoner. A package owns a coherent responsibility, has an explicit public contract, and uses only declared lower-level dependencies. Self-contained does not mean dependency-free or that every package needs its own copy of expression storage.
The kernel, theorem store, coordinator, equality engines, and mathematical procedures remain usable without any foreign prover. The interface with Isabelle/HOL (section 28) is an optional component: a result that does not use an imported statement does not depend on Isabelle, and a replayed proof depends on it no more than any other checked proof.
Package ownership. One repository holds the native packages under one version: termbank, the judgment_core kernel, judgment_shell, the theory packages scalar and judgment_nat, the public judgment facade, and the optional judgment_search and judgment_store (packages). The Isabelle/HOL theories the system uses are not a package: they are a proof library, the judgment_mathlib library, which judgment_store opens. polynomials (poly_mojo) and isabelle_bridge are external components with their own contracts. The kernel's theory mechanisms stay in judgment_core, because literal kinds and definitional mechanisms are a closed set inside the trusted kernel. Trust follows package boundaries: a package is either in the trusted base (section 30.6) or entirely untrusted, never partly. Two further rules apply. Engines do not import concrete theories: a theory's law bundle (its constants and theorems) is passed to the engine when the application assembles them. And an algorithm package (computation only) is kept separate from the engine that turns its results into certificates.
Section 17.3's module layout is a responsibility map into these packages.
27.2 Foundational packages¶
| Package | Trusted | Owns and exposes | Explicit exclusions |
|---|---|---|---|
termbank |
yes: proof-DAG storage | Raw syntax with binders: heads, rows, atoms (bound variables, locals, type variables), the literal payload pool, structural hashing, and hash-consed identity; termbank.dag, the proof-DAG storage of terms, declarations, contexts and proof rows, with workspaces, the verified watermark and verified spill (trusted base). |
No rewriting, canonical forms, typing, or proof checking. |
judgment_core |
yes: the kernel | Types with sorts and checked terms with canonical ACU and literal construction; declarations (including type definitions, specifications, overloading, classes, and instances) and theories; contexts; proof nodes and the checker; conversion; the logic core; literal-kind implementations (exact integers and rationals, formal polynomials); the verdicts that make rows checked. No certificate checker is admitted. | No theorem search, engines, coordinator, or semantic profiles. |
judgment_shell |
no | Term views and builders; recipes and their execution; derived rules; evidence labels and dependency classes (including imported statements); matching modulo ACU, with sorts; guards and supports; the theorem store and its indexes; law bundles (also filled from class instances); conversion combinators; the engine protocol; Session proof authoring. |
No coordinator policy and no concrete theories. |
judgment_store |
no | Content-addressed identities; proof libraries of checked proof rows, with their theory bundles, checked again on every load; re-checking after a kernel fix; theory interpretations; the conversion-eliminating and OpenTheory exports; the OpenTheory reader with extended articles and import theories (section 28.5). | No search; nothing read back is trusted. |
scalar |
its axioms | The scalar semantic profile (section 17.2): the carrier, its axioms and model, literal-kind and ACU declarations, the order and domains, powers, roots, elementary functions, the polynomial theory over Scalar, a lemma library, law bundles, numeric semantics, and the model in HOL with its bridges (section 15), built over judgment_mathlib's theories. |
No algorithms; no import of judgment_store; no dependency on judgment_mathlib. |
judgment_nat |
no | The natural numbers, induction, and primitive recursion as checked definitions in a classical profile, and bridges to other structures with induction (natural numbers). | Optional; no axioms of its own; no other package imports it. |
judgment_search |
no | Concurrent proof search and lemma checking over Session forks on fp's IO runtime (concurrent proof search). |
Optional; no other package imports it, the facade included. |
judgment |
no | The public entry point: judgment_shell's authoring API and scalar's profile builders, reexported with their original types and semantics. |
Nothing of its own; no implementation package imports it; no Store. |
polynomials |
no | Pure polynomial algorithms over apn_mojo numbers, with certificates: arithmetic, division, gcd, resultants, rational functions, factorization, Gröbner bases, real roots. | Does not import judgment_core; produces no proofs. |
isabelle_bridge |
no | An Isabelle component (Isabelle/Scala and Isabelle/ML): statement and proof export from the pinned Isabelle release as extended OpenTheory articles; our results replayed in Isabelle; run-time requests to an Isabelle server (section 28). | No Mojo package; it writes articles that judgment_store reads. |
The checker's verdicts are the only route to checked status: a row is checked when a verdict has moved the watermark past it, and only judgment_core.checker constructs a verdict (CG5, CG8). Ordinary ids, raw termbank syntax, deserialized rows, and imported articles never bypass the checks. judgment_shell owns the common request and result contracts; engines must not define incompatible copies of ConversionCandidate, GoalRequest, or EngineDelta.
27.3 Engines, mathematical theories, and applications¶
These packages are parts of the design outside the current package set.
| Package or family | Responsibility | Independent use |
|---|---|---|
rewrite |
Directed, guarded simplification by theorem lookup, with matching modulo ACU against canonical spines. | Deterministic simplification without a coordinator. |
linarith |
Linear arithmetic over ordered fields, with Farkas certificates; at any type of an ordered-field class, or on scalar's reals through its bundle. |
Entailment of linear guards such as x > 2 ⇒ x ≠ 1. |
polynorm |
Polynomial and rational normalization through formal-polynomial literals (sections 25.4, 25.5, and 32.2); at any commutative ring through class-level ACU (section 16.5). | Certified expansion, cancellation, and identity testing. |
reasoner |
The coordinator: goals, derivations, scheduling, publication, evidence policies, and named strategies (simplify, expand, together, solve; section 22.2). |
Composes engines; imports none of them. |
patterns |
A matcher with wildcard, sequence, ACU, and guarded patterns, untrusted, shared by normalize, n1, user rules, and rubi (section 31.4). |
Matching without any proof machinery. |
normalize, n1 |
Tiers 2 and 3 of Symbolic normalization (section 31). | Profile-defined evaluation with recipes. |
congruence, eqsat, relational |
Contextual congruence closure; budgeted saturation and extraction; relational joins and incremental propagation. | Separate engine packages. |
calculus, rubi |
Proof-producing differentiation; Rubi integration as certified search (section 31.5). | Integration with a checked antiderivative relation. |
ore, holonomic, hypergeometric, dalgebraic |
Special-function classes (section 32.3). | Closure properties, equality, and summation with certificates. |
Abstract theories (measure, distributions, …) |
Declarations and lemma libraries for function classes (section 32.1), largely imported from Isabelle's analysis library. | Theorem proving without the CAS. |
| The CAS (named separately) | Elaboration, presentation, policies, objectives, and assembly. | The user-facing application, not the foundation. |
Keep a mathematical algorithm's direct API separate from its coordinator adapter. For example, a polynomial normalizer can expose normalize(input, domain, limits) -> normal_form_and_certificate; an adapter translates a NewGoal or TransformRequest into that call. A direct API must not recursively construct a global reasoner merely to perform its work.
When worthwhile, separate domain computation, certificate validation, and engine adaptation into targets or subpackages. Code that generates a certificate is not trusted merely because its checker ships beside it. A new checker is an explicit validation dependency unless it reconstructs ordinary B0 proofs. Mathematical declarations must not import an automation engine to acquire their meaning.
Reuse existing standard-library facilities and existing numeric packages through explicit interfaces. Modularization is not a justification for replacing standard containers or cloning number implementations into each solver.
27.4 Acyclic dependency graph¶
In the following diagram, A -> B means A imports B. The first block is the current package graph, as scripts/packages.py declares it (packages); the others show the design's external components, engines, and applications, with transitive imports omitted. Additional direct imports are allowed only downward in the graph and must be declared. apn_mojo and fp (fp_mojo) are external dependencies.
termbank -> fp
judgment_core -> termbank, apn_mojo (Integer, Rational), fp
judgment_shell -> judgment_core, termbank, apn_mojo, fp
judgment_nat -> judgment_shell, judgment_core, termbank, apn_mojo, fp
judgment_search -> judgment_shell, judgment_core, fp
scalar -> judgment_shell, judgment_core, termbank, apn_mojo (balls), fp
judgment -> judgment_shell, scalar
judgment_store -> judgment_shell, judgment_core, termbank, apn_mojo, fp
polynomials -> apn_mojo
isabelle_bridge -> Isabelle (pinned release); no Mojo imports
rewrite -> judgment_shell
linarith -> judgment_shell, apn_mojo
polynorm -> judgment_shell, polynomials
reasoner -> judgment_shell
slice assembly -> reasoner, rewrite, linarith, polynorm, scalar
patterns -> termbank
normalize, n1 -> judgment_shell, patterns
congruence -> judgment_shell
eqsat -> congruence
relational -> judgment_shell
calculus -> judgment_shell
rubi -> patterns, calculus
cas -> reasoner and selected packages
Test-only dependencies cross this graph without changing it: polynomials tests its arithmetic against the kernel's polynomial kind; scalar ships its profile through judgment_store and certifies an identity with polynomials; judgment_store reads articles that isabelle_bridge writes, and Scalar's model and bridge tests open judgment_mathlib, the proof-DAG library converted from such an article. The schema describes import direction, not permission to hide dependencies in a callback. A callback may return an abstract observation or proposal; it must not make a supposedly lower-level package require the coordinator's private state to function.
isabelle_bridge is a separately built Isabelle component, not an import into the Mojo kernel. Communication across the process boundary is a file format (OpenTheory articles, contract S-article) or a protocol (Isabelle's server). Neither native installation nor native proof checking invokes Isabelle; only exporting a new article for judgment_mathlib does.
27.5 Shared ownership and assembly¶
Share termbank.dag's syntax and proof rows through views of the bank and the typed handles of section 18. Do not require all packages to receive one giant mutable System object. A package receives only the stores, read views, builders, and capabilities its methods require.
PackageContract:
name: PackageName
api_version: Version
direct_dependencies: List[DependencyConstraint]
public_interfaces: List[InterfaceName]
standalone_tests: List[TestId]
source_references: List[SourceReference]
AssemblyPolicy:
enabled_engines: List[EngineVersionId]
allowed_profiles: Set[SemanticProfileId]
allowed_checkers: Set[CheckerVersionId]
accepted_import_sources: Set[ImportSourceId] # for example Isabelle2025-2, tier 1
allowed_axioms: Set[QualifiedAxiomIdentity]
external_services: List[ServiceConfiguration] # for example an Isabelle server
EngineFactory.create(stores, read_views, candidate_builder, configuration)
-> EngineInstance
Assembly.register_engine(instance, descriptor) -> RegistrationResult
Assembly.register_checker(checker, explicit_admission) -> RegistrationResult
Assembly.attach_theory(checked_bundle, compatibility_evidence) -> RegistrationResult
PackageContract is build/review metadata, not a source of mathematical authority. Installation, import, and static initialization do not register trusted axioms, checkers, import sources, or external executables. Admission is an explicit application action with a recorded policy identity. The factory does not receive permission to mint checked handles.
Policies for accepted import sources and checkers are distinct from semantic profiles. A caller may accept the CAS's scalar profile but demand that no result depend on an imported statement; evidence with broader dependencies then remains unavailable to that request unless its policy is explicitly changed, and it is never relabeled to match the request.
Guard and proof pruning also respect these policies. A weaker-guard proof resting on an imported statement does not make a stronger-guard native proof useless to callers that refuse imported statements. Support antichains may share logical labels, but must retain policy-distinct evidence alternatives or partition their witness indexes by acceptance policy. Proof cost alone cannot discard the last eligible witness for a supported policy.
27.6 Independent configurations and package validation¶
The following must be separately buildable and testable:
| Configuration | Required behavior |
|---|---|
| Proof replay only | Load compatible native theorem bundles and recheck them without search, e-graphs, or Isabelle. |
| Native simplification | Run directed and certified normalizing conversions without an external process. |
| Congruence only | Assert checked equalities and explain consequences without saturation or a coordinator. |
| Isabelle import only | Read Isabelle's articles into import theories, and replay proof articles, without engines or a coordinator. |
| Equality saturation only | Run supplied native theories and rules without Isabelle installed. |
| Full CAS | Compose selected engines without changing their individual proof contracts. |
A bundle whose results depend on imported statements still needs their import theory to be rechecked: it is not a native-only replay bundle merely because it was packaged offline. Once the statements' proofs are replayed (tier 2), the results replay without them.
Build checks inspect actual imports as well as package manifests, reject cycles and forbidden dependency edges, test with optional packages absent, and verify that no global active-layer state crosses public package boundaries.
27.7 Versions, pins, and contracts¶
The native packages share one version and toolchain and are built together from the checkout, so every package builds against one kernel. External dependencies (apn_mojo, fp_mojo and poly_mojo) are modular-community channel packages that Pixi installs at the versions pixi.toml pins, so everything builds against one apn_mojo. Moving a version is an explicit change that runs the gates of the packages that use it.
Every interface between components is a contract owned by its producer, whose specification is normative; consumers code against it, and a breaking change is discussed before it is made and updates the producer's specification and its consumers together. The contracts page lists each contract with its owner and normative pages: the kernel's API and theory mechanisms; polynomial values and certificates (P); judgment_shell's term views, recipes, labels, store, bundles, and engine protocol (L-terms to L-engines); judgment_store's formats (S-format), its OpenTheory reader and extended format (S-article), and the portable archive format; isabelle_bridge's exports (I-export); scalar's profile (X-profile) and bridges (X-bridge). Each component's documentation names this note as the system's architecture, and its own pages as normative for its detailed design.
28. The interface with Isabelle/HOL¶
The foreign-prover interface targets Isabelle/HOL, whose mathematical conventions the imported layer follows (section 15). The interface runs in both directions: Isabelle's theories and proofs come into the kernel, the kernel's results go back to Isabelle's kernel, and the CAS can ask Isabelle at run time. Its Isabelle side is isabelle_bridge, an external Isabelle component pinned in scripts/isabelle/isabelle.py; its kernel side is judgment_store's OpenTheory reader; its mathematics is on isabelle_bridge's theory pages (results L, R, B) and the Store page OpenTheory export and import (results OT).
28.1 Scope and the chosen model¶
| Direction | Mechanism | Trust |
|---|---|---|
| Isabelle → kernel, statements (tier 1) | the exporter writes each theory's statements, definitions, classes, and instances as an extended OpenTheory article; the reader declares the statements as axioms of an import theory, with provenance | Isabelle's kernel and the exporter's translation of each statement; visible in every label |
| Isabelle → kernel, proofs (tier 2) | the exporter translates Isabelle's proof terms into article commands; the reader replays them through kernel rules | none beyond our kernel |
| kernel → Isabelle | judgment_store exports a result as a standard OpenTheory article; an Isabelle/ML importer replays it with Isabelle's kernel |
the result is checked a second time, by an independent kernel |
| run time | the CAS sends a side condition to an Isabelle server; a proof comes back in tier 1 or tier 2 | as for tiers 1 and 2 |
The exporter must run inside Isabelle, where theorems, classes, and proof terms exist; Isabelle exports them to Isabelle/Scala (export_theory, export_proofs) 42, so the component is written in Scala and built with Isabelle's own scala_build. OpenTheory is the interchange format 40 [41], extended with commands for classes and overloading, which plain OpenTheory lacks. No exporter from Isabelle to OpenTheory existed: translating Isabelle's proofs is harder than HOL Light's or HOL4's, because Isabelle's kernel adds the Pure framework, type classes, and overloading to HOL [49].
28.2 What is read from Isabelle¶
The pinned release is Isabelle2025-2, with the matching AFP release. Its HOL session, built with export_theory, yields per theory: types, constants, constant definitions, type definitions, classes, class relations, arities, axioms, and every theorem's statement and dependency list; with export_proofs and full proof recording, also proof terms.
| Measure (Isabelle2025-2, HOL session) | Value |
|---|---|
exported theorem statements; facts visible in Complex_Main |
33,673; 30,340 |
| facts depending on an oracle | 32, all through skip_proof in Quickcheck's generator equations |
| statement export: time, peak memory, size | 4.5 minutes at 16 threads, 12 GB, 154 MB |
proof export of Main (HOL-Proofs) |
stopped at HOL.Presburger, two thirds through, at 25 GB |
the Isabelle-to-Dedukti exporter's output by HOL.Set_Interval, without sharing |
about 1 GB 44 |
Isabelle/HOL's non-definitional axioms are few: refl, subst, ext, the_eq_trivial, impI, mp, True_or_False, eq_reflection, someI, the two axioms of ind (infinity), the two axioms relating 'a set and 'a ⇒ bool, and the arities of the function type and itself. The other 3,859 entries of its axiom export are definitions. Each of these axioms, translated, is a theorem of the kernel's classical profile with two declarations (a specification for ind, a type definition for set) (Theorem R-1).
These numbers set the design: statements of whole sessions are exported at once; proofs theory by theory, with term sharing through the article dictionary, and measured as they grow.
28.3 Translation¶
types: bool, prop ↦ Prop; ⇒ ↦ arrow; itself ↦ itself; 'a::S ↦ α^(S without type); other κ ↦ the import theory's κ
terms: Trueprop P ↦ P; ⋀x. A ↦ ∀x. A; A ⟹ B ↦ A → B; s ≡ t ↦ s = t
HOL's connectives, quantifiers, The, Eps ↦ the logic core and the classical profile, through the name map
OFCLASS(τ, c) ↦ of_class_c(TYPE[τ])
other constants ↦ the import theory's declaration of the same name (one overloaded constant, its instance definitions)
schematic variables ↦ universally quantified, outermost, in order of first occurrence
proofs: ⋀- and ⟹-introduction and elimination ↦ forall_intro, imp_intro, forall_elim, imp_elim
axioms ↦ Theorem R-1's theorems; named theorems ↦ use at the translated instance (admissible substitution)
class-membership proofs ↦ of_class; Pure's equality rules ↦ eq_refl, eq_sym, eq_trans, eq_apply, eq_abstract, propext, eq_subst
β ↦ nothing (terms are built β-reduced); η ↦ an explicit step by function extensionality
The kernel identifies no η-equivalent terms (section 20.5), while Isabelle does; the proof translation therefore makes each η-step explicit. A statement keeps its meaning: every ground model of the import theory is a ground model of Isabelle's theory, in which Isabelle's theorems hold (Theorem R-2).
28.4 Two tiers, and what each trusts¶
| Tier | The kernel holds | Trusted | The label shows |
|---|---|---|---|
| 1, statements | Axiom declarations of an import theory, registered IMPORTED_STATEMENT |
Isabelle's kernel, and the exporter's statement translation (Corollary R-3) | each imported statement used, with its source |
| 2, proofs | Proven theorems, replayed |
nothing beyond our kernel (Theorem R-4) | the definitions and Isabelle axioms used (theorems of the classical profile) |
Excluded, and reported: theorems whose derivation depends on an oracle (Isabelle records the oracles of every theorem), and theorems of theories that add an axiom outside Isabelle/HOL's axioms and definitional mechanisms (some AFP entries formalize axiomatic theories). A statement-tier result moves to the proof tier without re-proof: when the proof article of a theory replays, the statement import theory is interpreted into the proof import theory, and every result derived from it moves by replay (Theorem OT-12).
28.5 The OpenTheory reader¶
judgment_store's article converter accepts format version 6 40: a stack machine with a dictionary, whose rule commands (refl, sym, trans, appThm, absThm, betaConv, assume, eqMp, deductAntisym, proveHyp, subst) and definition commands (defineConst, defineConstList, defineTypeOp) each become rows of termbank.dag: a rule command is one proof row of a sequent rule, which the kernel checks as one step, and a definition command a declaration row and the sequent rows of its theorems (sequents). A HOL theorem \(\Gamma \vdash \varphi\) denotes the closed judgment \(\vdash \forall \bar v.\, \bigwedge\Gamma \to \varphi\), and the article's subst command, types and terms together, is one inst row. The checked rows are published as a proof library (ST9). A name map sends the names of OpenTheory's bool package to the logic core, each entry justified by a theorem proved once; the three HOL axioms (η, choice, infinity) are discharged by the classical profile.
An extended article begins with version 6 and the pragma "judgment.extended.6", and may use commands that map to the kernel's K2.7 and K2.8 forms:
| Command | Kernel operation |
|---|---|
sortedVarType |
a type variable with a sort |
overloadedConst, defineInstance |
an overloaded constant; an instance definition |
defineClass |
a class and its predicate |
instance |
an instance declaration, citing its theorem |
ofClass |
the of_class rule |
source |
names the next thm or axiom, supplying provenance for an axiom |
The format is contract S-article, owned by judgment_store and specified in ST6.5. HOL Light's articles from the OpenTheory repository test the reader on a library with a different origin, whose junk values differ from Isabelle's, so HOL Light's reals and Isabelle's are separate import theories.
28.6 Import theories and provenance¶
Every article from another prover is read into an import theory named after its source. Every imported statement carries its source, written by the extended format's source command and registered with judgment_shell:
Source: prover = Isabelle
release = Isabelle2025-2 (and the AFP release for AFP entries)
session, theory
theorem = Isabelle's full name and index (e.g. Fields.division_ring_class.inverse_zero)
Names in an import theory are Isabelle's full names, qualified by the import theory, so two releases' theorems never share a declaration.
28.7 Our results in Isabelle: the second auditor¶
An Isabelle/ML importer in isabelle_bridge replays a standard OpenTheory article, as judgment_store exports it (conversion eliminated, Theorem C-12; sorts compiled away, Theorem Y-6), with Isabelle's kernel, modeled on Isabelle's importer for HOL Light [45]. Imported names map back to Isabelle's constants; our other constants are declared in a new Isabelle theory, as definitions when ours are definitions, and otherwise as locale parameters whose assumptions are our axioms, so that nothing is asserted in Isabelle without proof. A result the importer accepts is an Isabelle theorem checked by Isabelle's kernel and dependent on no oracle (Theorem B-1). Together with the OpenTheory audit by an independent HOL kernel, this is the system's independent check of its own kernel's judgments (de Bruijn's criterion), and it lets Isabelle users reuse what the CAS proved.
28.8 Run-time requests¶
Request: session, goal (in the reverse translation), methods (default: auto, simp, metis, smt), time limits, tier
Answer: PROVED(statement, article?) | NOT_PROVED(methods tried) | REFUTED(counterexample: unchecked) | ERROR
The client talks to isabelle server with its JSON protocol. A PROVED answer replays in the kernel in tier 2, or enters as an imported statement in tier 1; NOT_PROVED and REFUTED establish nothing (a Nitpick or Quickcheck counterexample is a hint for the CAS to look for its own). Methods that use an oracle are refused before sending; smt is allowed because Isabelle reconstructs its solvers' proofs in its own kernel (Theorem B-2).
28.9 Pinning, isolation, and scale¶
- One release.
isabelle_bridgerefuses an Isabelle other than the pinned release; moving it is an explicit change, and every source names it. - Isolation. Builds with export options rebuild Isabelle's heaps; every run uses an isolated Isabelle user home, so a developer's own heaps and settings are never touched.
- Memory. Proof export is memory-bound (section 28.2): it runs a theory or a small group at a time, with limited threads, and measures size, time, and peak memory per theory.
- Order. Proofs are exported first for the theories the bridges of section 15.3 cite (reals, complex numbers, the transcendental functions), then outward.
28.10 Difficulty and non-goals¶
- AFP-wide proof replay is research scale. Statements of the whole AFP (1,037 entries, about 326,500 lemmas) are within reach; replaying all their proofs is not promised.
- Classes with more than one type parameter do not exist in Isabelle; locales are predicates. A locale's theorems translate as implications from its predicate, which needs no kernel support.
- No universal proof translation is claimed. Proof constructors without a translation case stop the export of that theorem, which is reported, never approximated (
isabelle_bridge's ground rule IG3). - Code evaluation is outside. Theorems proved through code evaluation depend on an oracle and are excluded.
- Semantics never travels by name. An imported constant means what Isabelle's definitions say; it reaches the CAS layer only through the bridges of section 15.3.
29. Package and interface validation¶
29.1 Supplemental acceptance tests¶
The tests below extend A01–A30 rather than replacing their kernel, scope, and equality checks. They are specified tests to implement, not reports of tests already run. The P-series checks package independence; the H-series checks the interface with Isabelle/HOL (section 28).
| ID | Test | Required result |
|---|---|---|
| P01 | Build termbank and judgment_core without judgment_shell, engines, or Isabelle installed. |
Public APIs and package tests work without optional dependencies. |
| P02 | Introduce a reverse dependency from judgment_core to judgment_shell, reasoner, or an engine. |
The layering gate rejects it. |
| P03 | Run a domain normalizer through its direct API without the coordinator. | Produces the same validated contract as its engine adapter. |
| P04 | Run congruence without saturation, and saturation without the coordinator. | Both assemblies function independently. |
| P05 | Install or import an optional engine without registering it. | No new axioms, checkers, external services, or admitted theories appear. |
| P06 | Pass a raw or deserialized handle from another store to a package API. | Reject or require a checked import; no certified authority is forged. |
| P07 | Delete solver and workspace state and replay a native bundle. | Native theorem replay is unaffected. |
| P08 | Load a bundle that depends on an imported statement without its import theory. | Report the missing dependency; do not silently trust the statement. |
| H01 | Read an extended article declaring a class hierarchy, instances with argument sorts, and instance definitions. | The kernel accepts them with its own checks; a mutated article (overlapping instance definitions, a missing witness, a dependency cycle through a type definition) is rejected. |
| H02 | Import Isabelle's HOL session in tier 1. | Every statement imports with its classes and its source; the 32 oracle-dependent theorems are absent. |
| H03 | Replay the proofs of HOL.Fields (tier 2), citing earlier theories' statements. |
Every proof replays; the replayed theorems' labels list no imported statement of HOL.Fields. |
| H04 | Corrupt one step of a proof article, or change the stated theorem. | The replay fails at that step, or at thm. |
| H05 | Use Isabelle's a / 0 = 0 (for every division_ring) at the CAS carrier. |
Refused: the carrier is no division_ring instance, and no bridge applies at \(b = 0\). |
| H06 | Prove \(\exp(a + b) = \exp a \cdot \exp b\) for finite \(a, b\) from Isabelle's exp_add through the bridges. |
A kernel judgment with guard \(\mathrm{finite}(a) \land \mathrm{finite}(b)\), whose label names exp_add's source (tier 1) or none (tier 2). |
| H07 | Apply the Arctan bridge at \(2i\). |
Refused: the point is outside the exact guard. |
| H08 | Import a theorem from an AFP entry that adds an axiom. | Excluded, with the axiom named in the report. |
| H09 | Run the exporter against an Isabelle release other than the pinned one. | Refused. |
| H10 | Export a kernel result and replay it in Isabelle. | Isabelle accepts the exact statement; a corrupted article is rejected by Isabelle. |
| H11 | Send a run-time request that auto proves, one it cannot, one Nitpick refutes, and one naming an oracle method. |
PROVED replays in the kernel; NOT_PROVED and REFUTED add nothing; the oracle method is refused. |
| H12 | Replay HOL Light's base package from the OpenTheory repository. |
Every article replays, including the type definition of the reals; the independent opentheory tool accepts the same articles. |
| H13 | Move a stored result from a statement import theory to the proof import theory of the same source. | The result replays there, and its label loses the imported statements. |
| H14 | Run the full test suite of isabelle_bridge. |
The developer's own Isabelle home is unchanged afterwards. |
Round-trip properties compare interpreted statements, scope, and dependencies, not printed text. Property tests include α-renaming, premise permutation with explicit maps, context export and reapplication, singular points, and sort admissibility under generated substitutions.
29.2 Integration validation¶
Each component validates its public contract against its declared dependency
versions. End-to-end checks must preserve guards and evidence, for example
when deriving x/x = 1 under a sufficient nonzero condition, simplifying
(x²−1)/(x−1) where cancellation is valid, or using a guarded square-root
identity. These are obligations of the assembled CAS, not additional public
kernel operations.
Measure statement/proof import costs, article replay, sharing, and the fraction of results relying on imported statements. Keep that evidence separate from claims about native kernel performance.
29.3 Interface ownership¶
Each component owns its current specification and dependency manifest. Changes at an interface must update both its producer and consumers. The integration contracts identify those boundaries.
30. Balancing rigor and efficiency: where and when proofs are checked¶
Search produces provisional candidates. This section specifies where checking must occur before a result is returned, shared, or retained.
30.1 Principles¶
- Check what you keep, not what you try. Search may try many steps that it later abandons. Only what leaves the request, as an answer or a stored fact, is checked.
- Rigor at the boundary, speed inside. Inside a request, engines work with provisional facts and recipes. At the boundary, the kernel checks a proof.
- Check results, not algorithms. Algorithms are untrusted and return certificates whose checking is much cheaper than their computation.
- Proofs on demand. A run without wall-clock stops is deterministic (K34). A proof that was not materialized for speed can be reconstructed by replaying the run.
- Measure. Search time, checking time, and proof size are measured separately (section 30.7).
30.2 Evidence levels and labels¶
EvidenceLevel =
Provisional # derived inside a request, carrying a proof recipe; never leaves it
| Checked # a kernel-created CheckedJudgment
| Unchecked # returned by the explicit fast mode, with a recipe, without checking
EvidenceLabel:
level: Checked | Unchecked
dependencies: Set[DependencyClass] # core, profile axioms, literal kinds, ACU,
# definitions, instances, imported statements,
# external claims, checkers (section 5)
A recipe is a well-founded description of how to build a proof: which theorems, with which instantiations, in which order, citing which other facts. It is cheap to record and is expanded into proof nodes only when checked.
Every result returned to a caller carries an EvidenceLabel. Only the kernel creates Checked handles; no other package can construct one, by the opaque-handle discipline of section 20.1.
30.3 The request lifecycle¶
- Open. A request opens a session: a workspace owned by that request. It reads the durable stores (checked theorems and facts) freely.
- Search. Engines derive provisional facts, each with a recipe, and share them with each other through the session. A provisional fact is a valid search input inside the session only.
- Select. The coordinator selects the result candidate under the request's objective.
- Check. The recipe of the selected result, together with the recipes of the provisional facts it cites, is expanded into a proof and checked by the kernel. Only the dependency cone of the answer is checked, not everything the search derived.
- Return. The result is returned with its label. Checked lemmas worth keeping (section 22.4) may enter durable stores now.
- Close. The session and all its provisional state are dropped.
In the explicit unchecked mode, step 4 is skipped, the result is labeled Unchecked, and step 5 writes nothing to any store.
30.4 Three gates¶
The soundness of this scheme rests on three gates, each enforced by the API rather than by convention:
| Gate | Rule | Enforcement |
|---|---|---|
| Return | Nothing is labeled checked unless the kernel returned a CheckedJudgment for it. |
Labels are computed from the handle type; an Unchecked result has no handle. |
| Store | Durable and shared stores keep only results the checker accepted. | A library change takes a TheoremExport, which Session.export makes from a checked fact; its fields are public, so it can be forged, and publication replays every exported row through the construction engine while the library's load rechecks it. A forged or altered export is refused at publication (test_forged_export). |
| Confinement | Provisional state belongs to one session and dies with it (K30). | The session owns its workspace; no API passes provisional facts between sessions. |
30.5 Risks and mitigations¶
| Risk | Consequence | Mitigation |
|---|---|---|
| An engine derives a wrong provisional fact | The answer's check fails, or the fact was not used | Recovery (section 30.8). Wrong search can cost time, never soundness |
| A provisional fact leaks into another request or a store | Unsound | The confinement and store gates (section 30.4) |
| An unchecked result is presented as checked | Unsound in the user's eyes | The return gate and the label |
| A kernel bug | Unsound | A small kernel; the inventory of section 30.6; adversarial tests (A-series, V-series); property tests of the canonical-form theorems on generated terms; the OpenTheory audit by an independent HOL kernel and Isabelle's replay of exported results (section 28.7) |
| A wrong literal implementation | Unsound | Differential tests against the reference implementation and apn_mojo's own tests (K33) |
| A wrong axiom, or a rule without proof | Unsound relative to the intended semantics | No rule is admitted on numeric evidence: rules are proved, or imported from Isabelle with their provenance; the numeric filter (section 31.3) finds mistakes before either is attempted; the dependency class appears in every label |
| A mistranslated imported statement (tier 1) | Unsound relative to Isabelle's meaning | Exact translation cases or refusal; provenance in every label; replaying the proof (tier 2) checks the translation (section 28.4) |
| A cycle through overloaded definitions and type definitions | An inconsistent theory | The kernel's termination check over both kinds of items (section 16.3), the condition whose absence made Isabelle inconsistent once |
| A bridge used outside its guard | A false CAS answer | Bridges are theorems with exact guards; the guard is a premise, discharged or kept in the answer (section 15.3) |
30.6 The trusted base¶
| Component | Why it is trusted |
|---|---|
termbank.dag storage |
Hash-consed identity is row identity; references only to earlier rows, immutable rows, the watermark and the verdicts that move it, workspaces, and verified spill (trusted base) |
The judgment_core kernel |
Type checking, the instruction set, conversion, canonical construction, export |
apn_mojo Integer and Rational |
They implement the exact literal kinds |
| The kernel's literal-kind implementations | Including the formal-polynomial arithmetic |
| The axioms of admitted theories | Profile axioms (for example scalar's), literal laws cited as axioms, classical principles |
| Type definitions, specifications, overloading, classes, sorts | The definitional checks of section 16: witnesses, orthogonality and termination, membership and coregularity, admissible substitutions, sort hypotheses, class-level ACU |
| Imported statements | Theorems of the pinned Isabelle release used without a kernel-checked proof: trusted as proved by Isabelle's kernel and translated faithfully, and named in every label; replayed proofs are not in this row (section 28.4) |
| Admitted checkers, if any | Each one an explicit, recorded extension (section 7.4) |
Everything else is untrusted: judgment_shell, judgment_search, judgment_store (its OpenTheory reader included), the prebuilt core's generated shims and clients, every engine, the coordinator, the matcher, Rubi, the polynomial algorithms, the Isabelle exporter for replayed proofs, and the CAS. A bug in them can cause a failed check, a missing answer, or a poor answer, but not an accepted false judgment.
30.7 Measurements¶
Measurements report, per workload: search time, checking time, recipe size, proof size, and the ratio of checking time to search time. The working target for simplification workloads is a ratio of at most 10–20%. Set workload targets from measured baselines and retain the methodology with the results.
30.8 Recovery after a failed check¶
A failed check is a bug report against an untrusted component, not a user-visible error. The coordinator:
- checks the recipe step by step, to find the first failing step and the engine or rule that produced it;
- quarantines that rule or engine for the rest of the request, and records a diagnostic;
- reruns the search without it, within the remaining budget;
- returns the best checked result found, or
NoResultwith the diagnostic.
30.9 Boundary acceptance tests¶
| ID | Scenario | Required behavior |
|---|---|---|
| V01 | Compare a+(b+c) with (c+a)+b, and 0·x with 0, for + and · declared ACU |
The first pair is the same canonical term; the second is not convertible |
| V02 | Build 2+3, (1/2)·2·x, and 0⁻¹ from literals |
5, x, and an unevaluated inverse (the operation declines) |
| V03 | Declare ACU with a commutativity theorem of the wrong shape, or for ∧ |
Reject the declaration |
| V04 | Instantiate a theorem scheme over α at two types; at a type whose variables clash; with the wrong number of type arguments |
Accept the first; reject the others |
| V05 | Define a constant whose body mentions itself, or whose body has a type variable absent from its type | Reject the definition |
| V06 | Apply the ξ-rule to a local that a hypothesis mentions | Reject |
| V07 | Pass a forged or altered export to a durable store | Refused at publication; the store is unchanged (test_forged_export) |
| V08 | Run in unchecked mode | The result is labeled Unchecked; no store changes |
| V09 | Derive a provisional fact in request 1, then query it in request 2 | Invisible in request 2 |
| V10 | Inject a wrong rewrite step into an engine | The answer is not returned as checked; the step is identified and quarantined; the report names it |
| V11 | Simplify x/x in generic mode, and in strict mode without assumptions |
1 with guard x ≠ 0 (and finiteness); in strict mode, no unconditional result |
| V12 | Evaluate 1/0, 0/0, 0·∞, and x − x in scalar |
ComplexInfinity, Indeterminate, Indeterminate by axioms; x − x = 0 only under finite(x) |
| V13 | Run the literal-kind differential tests | Kernel and reference implementations agree on all generated inputs |
| V14 | Replay a deterministic run | The same answer and the same proof digest |
| V15 | Certify a deliberately wrong antiderivative | Certification fails; Rubi's answer is not returned as checked |
| V16 | Propose sqrt(x²) = x without a guard |
The numeric filter refutes it at a negative point; nothing is admitted |
31. Symbolic normalization, rule libraries, Rubi, and certified algorithms¶
The CAS combines explicit normal forms, specified behavior for built-in functions, and Rubi for integration. This section places them in the architecture without adding anything to the trusted base: every rule is proved, or imported from Isabelle with its provenance. These engines are parts of the design, not packages of this repository; the integration contracts state which evidence may cross their trust boundary.
31.1 Three tiers of normalization¶
| Tier | What it does | Package | Proof cost |
|---|---|---|---|
| 1. Conversion | Associativity, commutativity, units, and exact literal arithmetic | judgment_core |
none: conversion is free |
| 2. Normalizer | Automatic simplifications: collecting like terms (x + x → 2x), powers (x·x → x²), and the evaluation of built-in functions at special values |
normalize |
a recipe, replayed into a proof on demand |
| 3. Rule library | The behavior of built-in functions (sin(pi/6) → 1/2, log(E) → 1, …), as theorems applied by rewriting |
n1 (bundle) and rewrite |
one theorem application per step |
Display in the application's chosen order is a printing concern, outside all three tiers: the kernel's order is a structural one, and any order is equal by conversion.
31.2 The normalizer¶
The normalizer is a compiled Mojo engine. Each of its rules is a theorem of the scalar lemma library. Rules that hold everywhere on the carrier are unguarded. Rules that hold only where the operands are finite or nonzero carry those guards, which generic mode accepts. Every code path that applies a rule tags its output with that rule's theorem, so a normalization run produces a recipe, and the proof is built by replaying the recipe. The normalizer never decides anything the kernel cannot check.
31.3 Rule libraries and the numeric filter¶
A rule library (n1, a user's rule set, MetiTarski's bound axioms once guarded) is a bundle of guarded theorems. Each rule is proved, from the profile's axioms and lemmas, or imported as an Isabelle theorem through the bridges of section 15 (an imported statement with its provenance until its proof is replayed). No rule is admitted on numeric evidence, and imported statements remain visible in the dependencies of the results that use them. Rubi's rules need neither: Rubi is search, and its answers are certified by differentiation (section 31.5).
Before anyone tries to prove or import a rule, the numeric filter tests it; it cannot admit a theorem:
- Sample points, chosen deterministically: one exact point in each cell of the plane cut by the branch cuts of the functions in the rule; one exact point on each piece of each cut and at each branch point; the exact zeros of each denominator and of each argument at which a function has a pole or a branch point, where they can be found exactly; points on both sides of the boundary of the rule's guard; and random points from a fixed seed, in boxes of several scales.
- Certify the guard at each point by ball evaluation, discarding points where it fails and counting those where it is undecided.
- Evaluate both sides with apn_mojo balls, deciding each branch (a cut, a zero test, an infinity test) exactly or at higher precision, and giving up rather than guessing.
- Verdict:
REFUTEDwith a witness point, if at some point the two sides' balls are disjoint, one side is finite and the other provably not, or both are certified distinct nonfinite values;INCONCLUSIVEif no guard-satisfying point was checked conclusively or too large a fraction of points stayed undecided;PASSEDotherwise.
REFUTED means the rule is false in the carrier, so no proof of it exists; PASSED establishes nothing. Exact points on cuts matter: a ball straddling the negative real axis cannot refute \(\log(1/z) = -\log z\), which fails exactly there, but an exact point on the axis does. The scalar package specifies the filter (numeric semantics, Algorithm N-4), and the conformance corpus (section 31.6) tests the rules against the profile's specified behavior.
31.4 One pattern matcher¶
patterns supports single-term wildcards, nonempty and possibly empty sequence wildcards, matching modulo associativity, commutativity, and units, conditions, predicate tests, and optional arguments with defaults. It is untrusted and shared by the normalizer, n1, user rules, and Rubi. Matching modulo ACU works directly on the kernel's canonical spines: a sum is one spine whose arguments form a multiset, so cos(x)² + sin(x)² → 1 matches inside sin(x)² + Gamma(z) + cos(x)² by selecting two of the three arguments. A match proposes an instantiation; the theorem application is checked by the kernel.
31.5 Rubi: integration as certified search¶
Rubi's rules are used as an untrusted search procedure, in Rubi's own order: the first applicable rule fires, as in Rubi. Rubi's utility functions are implemented as ordinary functions of the search. A Rubi run proposes an antiderivative F for an integrand f. The proposal is certified, not trusted:
- the
calculusengine provesD[F, x] = gby proof-producing differentiation; - the normalizer and
polynormproveg − f = 0under guards; - the result is the checked claim that
Fis an antiderivative offon the domain where the guards hold, stated as a derivative relation on that domain.
Ball arithmetic can quickly refute a wrong F before any proof is attempted, but it never certifies one. Rubi's test suite serves as the regression suite of rubi.
31.6 The conformance corpus¶
The conformance corpus is a versioned set of expressions and expected outputs that tests tiers 2 and 3 and the matcher against the profile's definitions. Each case records the applicable guards. A disagreement is investigated as an implementation defect, a reference error, or a proposed specification change; the specification changes only explicitly. The scalar package's behavior checklist collects the special values, branch-cut closures, and values at infinity fixed by its definitions, together with their mathematical sources and validation scope. Numeric agreement does not establish a theorem.
31.7 Certificates for common algorithms¶
| Algorithm | Certificate | Checking |
|---|---|---|
| Polynomial identity, expansion | Reification as formal polynomials | Literal equality of formal polynomials |
| Polynomial gcd | Bézout cofactors and cofactors of division | Polynomial multiplication and comparison |
| Factorization | The factors | Multiplication; irreducibility is a separate claim |
| Gröbner basis membership | Cofactors | Multiplication and addition |
| Linear arithmetic | A Farkas combination | Rational arithmetic |
| Antiderivative | F |
Differentiation and simplification to zero |
| Definite sum (holonomic) | A Wilf–Zeilberger pair or creative-telescoping certificate | Rational-function identities |
| Equality of holonomic functions | The common operator and initial conditions | Operator arithmetic and one uniqueness theorem |
32. Mathematical scope: abstract theories, polynomials, and special-function classes¶
32.1 Abstract mathematics¶
The kernel contains what abstract mathematics needs: polymorphic higher-order logic, the HOL Light and Isabelle/HOL foundation, in which large parts of analysis have been formalized. The design supports extension to function classes such as bounded variation, Sobolev spaces, measures, and Schwartz distributions:
- Function classes are predicates on function types:
bounded_variation(a, b): (Real → Scalar) → Prop,sobolev(k, p, Ω): (Vec(n) → Scalar) → Prop. - Measures are functions on sets of a type with a σ-additivity predicate; distributions are linear functionals on test functions, with a continuity predicate.
- Structures are classes, or explicit arguments. A structure on a type is a type class (section 16), as in Isabelle: a theorem about groups is stated once for the class and applies at every instance. A structure not determined by its type, such as a group on a subset or several orders on one type, is passed as an explicit argument or a locale predicate.
- Classical principles (excluded middle, choice, extensionality, infinity) are admitted axioms of these profiles, as in HOL.
- Induction and subset types. Type definitions require nonemptiness evidence (section 16.2). Induction and primitive recursion over the natural numbers are definitional, in the optional
judgment_natpackage (natural numbers); Isabelle's natural numbers also come with their theorems (section 28). - Totalized theories bridge to
scalar. As in Isabelle/HOL and judgment_mathlib, analysis is stated with total functions (an integral or a derivative returns a default value where it is undefined) and definedness predicates such asintegrableanddifferentiable_at. Theorems connect these predicates to the finiteness guards ofscalar, so abstract results can justify CAS steps. The system makes this concrete: the totalized theories are Isabelle's own (its analysis library), imported through section 28, and the connecting theorems are the bridges of section 15.
Propositional extensionality is already in the logic core; function extensionality, excluded middle, choice, and infinity are the profile axioms meant above.
32.2 Polynomials as first-class objects¶
Formal polynomials are a type of their own, Poly, whose values are literals of the FormalPolynomial kind (section 20.6). Arithmetic on them is literal arithmetic, done by the kernel. The kind's laws are those of a commutative ring with a coefficient homomorphism from the rationals and the power laws (Q1–Q8); with them, every model has exactly one interpretation of the polynomial literals, so the kind is conservative. Equality of two distinct literals is not evaluated to False, because distinctness does not hold in every model of the laws; it is proved by evaluating at a point when needed. Evaluation, a constant peval of the polynomial theory over Scalar with axioms, connects them to scalar:
peval: Poly → (Scalar → Scalar) → Scalar # ρ is read on integer arguments
peval(P + Q, ρ) = peval(P, ρ) + peval(Q, ρ) # guarded: ρ(i) finite for every integer i
peval(P · Q, ρ) = peval(P, ρ) · peval(Q, ρ) # guarded likewise
peval(X(i), ρ) = ρ(i) # i an integer
peval(pconst(c), ρ) = c # c a finite real
The environment is a function on the integers rather than a list, because lists need inductive types; its entries are packed with a balanced chain of conditionals. To prove (a+b)² = a² + 2ab + b² for finite a and b, polynorm proves that each side equals peval(P, ρ) for the environment ρ holding a and b and a formal polynomial P, one homomorphism step per operator, and the kernel's literal arithmetic computes both Ps, which are then the same literal. The proof is linear in the input; the expansion is done by the trusted, simple arithmetic.
The untrusted polynomials package is the place for the algorithms: sparse multivariate and dense univariate arithmetic, gcd, factorization, resultants, and Gröbner bases. Their results come back with the certificates of section 31.7.
32.3 Special-function classes¶
Each class follows the same pattern: an object kind (a data representation), an untrusted algorithm package, a certifying engine, and a theory package with the defining axioms and lemmas.
| Class | Object | Certificate or checking route |
|---|---|---|
| Polynomials | Poly literals; sparse multivariate and dense univariate |
Literal arithmetic (section 32.2) |
| Ore operators | Polynomials with a noncommutative product (∂·x = x·∂ + 1), using the same polynomial code |
Operator arithmetic |
| Holonomic functions | An annihilating operator, initial conditions, and an expansion point | Equality by a common operator and matching initial conditions, plus one uniqueness theorem; sums by Wilf–Zeilberger and creative telescoping |
| D-algebraic functions | A differential polynomial with initial conditions | Numeric refutation; certified equality is open (section 33) |
Generalized hypergeometric pFq |
Canonical parameter multisets | Through its holonomic ODE of order max(p, q+1) |
| Meijer G | Grouped parameter multisets | The Adamchik–Marichev convolution theorem, proved or imported, with its parameter conditions as guards; results checked holonomically, with numeric refutation as a filter |
Numerical values and the numeric filter use apn_mojo balls. They never admit a theorem: a rule is proved, imported under the trust policy of the integration contracts, or stated as an explicit hypothesis.
33. Open specification work¶
The table distinguishes established architecture from obligations of the wider system. Current kernel mechanisms and their proofs are specified in the implementation reference and theory chapters.
| Area | Concrete baseline in this note | Still to formalize or validate |
|---|---|---|
| Logical calculus | Section 20's natural deduction, universal quantification, homogeneous kernel equality with the ξ-rule, defined ∃; classical principles admitted per profile; type definitions, specifications, overloading, classes (section 16); induction and primitive recursion as definitions in the optional judgment_nat package (Theorems NR-1 to NR-6), related to Isabelle's nat by a checked bijection. |
Well-founded recursion. |
| Type system and conversion | Polymorphic simple types with sorts, n-ary spines, lambda/let syntax, conversion with ACU (also at a class) and literal kinds. | Resource accounting for conversion; η-steps in replayed Isabelle proofs (section 28.3) measured; whether a kernel rule for type instantiation of closed judgments is needed (section 28.5). |
| Partial semantics | The scalar profile: extended complex carrier, total operations, finiteness as definedness, domains as predicates, generic answers; the extended real order; elementary functions from exp and log; bridges to Isabelle/HOL and the model in HOL, where the profile's axioms are theorems (section 15). |
Validation of the specified values in the profile behavior checklist. |
| Contexts and export | Immutable frames, typed maps, explicit hypothesis discharge and parameter closure. | Complete context-interface normalization. |
| Kernel and certificates | Proof rows checked locally, checking at the request boundary with evidence labels; stored proofs rechecked on every load. No certificate checker is admitted. | Checker implementations, validation caching, and formal certificate soundness for each algorithm of section 31.7. |
| Goal coordination | Exact-context interning, hyperedges, fair deterministic queues, versioned unknown attempts. | Memory-pressure policy, request-sharing details, and optimized dependency granularity. |
| Source-guided implementation | Mandatory upstream inspection, pinned provenance, notices, and correspondence tests (section 6.5). | Per-component source review and licensing review of each actual imported file, including AFP entries' licenses (BSD or LGPL per entry). |
| Engine implementations | Common event/result protocol; relational, normalizing, and equality engines are separate; generic engines per class (section 16.6). | Complete method contracts, native Mojo trait/ownership design, and engine-specific algorithms. |
| Guards and supports | Factored formulas, checked normalization, bounded witness-carrying antichains. | Measured retention policies, logical implication caching, and optional decision-diagram thresholds. |
| Equality and materialization | Certified contextual assertions, frozen congruence reasons, disposable workspaces. | Efficient adaptation of existing layers and indexes; proof-reconstruction complexity measurements. |
| Results and extraction | Strict, conditional, piecewise, and relation-aware variants; finite tree witnesses. | Objective APIs, piecewise expression semantics, DAG-cost strategies, and user-facing presentation. |
| Persistence and lifecycle | Content-addressed proof libraries, loads that recheck every row, statement-only imports, interpretations (judgment_store). |
Garbage collection and store-version upgrades. |
| Packaging | One repository and version for the native packages; external dependencies at pinned channel versions; contracts owned by their producers (section 27.7). | Publication as conda packages. |
| Symbolic normalization | Three normalization tiers; rule libraries proved or imported from Isabelle, filtered numerically; Rubi as certified search. | The conformance corpus; which of n1's and MetiTarski's rules Isabelle's library already proves; Rubi's utility functions. |
| The interface with Isabelle/HOL | Tier 1 statements and tier 2 proofs as extended OpenTheory articles; results back to Isabelle; run-time requests (section 28). | Proof export at scale (memory per theory, sharing); the AFP release and entries to import first; the reverse translation's handling of our profiles' constants as locale parameters. |
| Special functions | Formal polynomials as literals; Ore, holonomic, D-algebraic, hypergeometric, and Meijer G object kinds. | Representations and certificates for each class; D-algebraic equality. |
| Validation and performance | A01–A30, V01–V16, P01–P08, H01–H14, and dependency-ordered gates (section 29). | Executable tests beyond the kernel's acceptance specification, formal proofs, benchmark implementations, and measured targets. |
A general dependent type theory, unrestricted proof-search completeness, globally weakest guards, eager minimal-support enumeration, and mandatory BDD/ZDD indexes remain outside B0. The source-guided implementation requirement does not mean copying an entire prover or inheriting all its axioms: Isabelle's theorems are imported with their provenance and, progressively, their proofs, and its conventions stay in the logical core, separated from the CAS layer by the bridges of section 15.
34. Architectural conclusion¶
The system is a proof-producing symbolic reasoning core, not an e-graph with proofs added around it.
The kernel determines which judgments are accepted. The theorem bank stores reusable logical knowledge. Proof rows record its evidence. Guards describe what is needed to apply a theorem, and contexts supply that evidence. A goal-and-derivation coordinator organizes incomplete reasoning. Specialized engines construct candidate proofs and transformations; contextual e-graphs are one efficient way to organize established equalities and explore alternative representations.
A successful CAS derivation becomes a reusable program for producing proofs. Supplying a new context means supplying arguments to that program. Combining derivations means composing proof programs. Learning a lemma means retaining a new checked program. Context export makes the dependencies explicit rather than tying knowledge to a discovery workspace.
Source-guided development grounds these abstractions in mature implementations without importing their entire runtime. Baseline B0 makes the contracts concrete: typed syntax and contexts, a small proof checker, guarded theorem operations, a dependency-aware coordinator, and specialized engines whose results cross one explicit validation boundary.
Proofs are checked where results leave a request. Search can share provisional candidates internally. The kernel's conversion absorbs the bookkeeping of associativity, commutativity, units, and exact arithmetic. Algorithms stay untrusted and return certificates that are cheap to check. The application assembles those packages into the path from a request to a checked answer.
The system connects the foundation to the largest body of checked mathematics in the HOL family, without giving up the CAS's semantics. The logical core follows Isabelle/HOL: type definitions, overloading, and type classes are kernel mechanisms, so Isabelle's theorems are read as they are stated, stored once per class, and applied by a membership check. Isabelle's library enters as statements with their provenance and is progressively replaced by replayed proofs that the kernel checks. The CAS follows the scalar profile's definitions: its carrier, with its infinities and Indeterminate, stays a separate layer, built inside HOL from Isabelle's complex numbers and connected to them by bridge theorems whose guards exclude exactly the points where the two conventions differ. Nothing is admitted on numeric evidence; Isabelle's kernel and an independent HOL kernel check the system's own results in return. The supporting packages own these integration contracts and their validation.
Modularity, interoperability, and the layering of conventions are mechanisms for extending the system without changing the meaning of established judgments.
References¶
These works motivate the logical and data-structural choices; no single one of them implements the complete design.
1 Theorem Proving in Lean 4, “Propositions and Proofs.” Propositions-as-types and implication as proof transformation.
2 Lawrence C. Paulson, Tobias Nipkow, and Makarius Wenzel. From LCF to Isabelle/HOL. Formal Aspects of Computing 31(6), 675–698, 2019. The kernel/automation separation and the LCF lineage.
3 Johan de Kleer. An Assumption-Based TMS. Artificial Intelligence 28(2), 127–162, 1986. Alternative supporting assumption environments.
4 Todd J. Green, Grigoris Karvounarakis, and Val Tannen. Provenance Semirings. PODS 2007, 31–40. Algebraic provenance for relational and Datalog inference.
5 Tyler Hou, Shadaj Laddad, and Joseph M. Hellerstein. Towards Relational Contextual Equality Saturation. EGRAPHS 2024; preprint arXiv:2507.11897, 2025. Context-sensitive equality reasoning over shared structures.
6 Theorem Proving in Lean 4, “Axioms and Computation.” Constructive reasoning, classical principles, and their explicit logical role.
7 Kensuke Kojima. BDDs Naturally Represent Boolean Functions, and ZDDs Naturally Represent Sets of Sets. arXiv:1806.10261, 2018. The distinction between Boolean-function and set-family representations.
8 Max Willsey et al. egg: Fast and Extensible Equality Saturation. POPL 2021; preprint arXiv:2004.03082. E-graphs, rebuilding, analyses, and equality-saturation search.
9 The Isabelle/Isar Implementation, “Primitive logic.” Certified syntax, theorem values, the inference kernel, and the logical framework.
10 The Isabelle/Isar Implementation, “Structured proofs.” Proof contexts, assumptions, fixed variables, and context export.
11 The Isabelle/Isar Implementation, “Preliminaries.” Theory infrastructure, context management, and foundational implementation organization.
12 The Isabelle/Isar Implementation, “Equational reasoning.” Proof-producing conversions and simplification.
13 Lean Language Reference, “Elaboration and Compilation.” Separation of surface elaboration, automation, and kernel checking.
14 Lean API Reference, Lean.Expr. Core expressions, variable classes, and cached structural information.
15 Lean API Reference, Lean.Meta.DiscrTree.Main. Discrimination-tree indexing for expressions and theorem candidates.
16 Lean Language Reference, “The grind tactic.” Cooperation between congruence closure, propagation, theorem instantiation, and theory reasoning with proof production.
17 Rocq Reference Manual, “ring and field: solvers for polynomial and rational equations,” version 9.2.0 documentation. Reflection, polynomial normalization, and field side conditions.
18 Rocq Reference Manual, “Generalized rewriting,” version 9.2.0 documentation. Relations, morphisms, and rewriting beyond ordinary equality.
19 Lean Language Reference, “The Type System.” Dependent typing and definitional equality.
20 JudgmentMathlib Documentation, JudgmentMathlib.Algebra.GroupWithZero.Defs. Totalized inverse conventions, including inverse at zero.
21 Lean Language Reference, “The Simplifier.” Directed, proof-producing simplification.
22 Isabelle core, COPYRIGHT. Three-clause BSD copyright, redistribution conditions, and disclaimer. The full distribution may contain separately licensed components.
23 Lean 4 repository, LICENSE. Apache License 2.0. Check actual file headers and dependency licenses before source adaptation.
24 Apache Software Foundation, Apache License, Version 2.0, particularly the redistribution, patent, and trademark provisions.
25 Isabelle official distribution page. Distinguishes the BSD-style main codebase from the multiple licenses in complete application bundles.
26 Isabelle source, src/Pure/thm.ML, revision e0dcafccecdeabcb59480b3948d487c9197c6756. Certified terms/types, abstract theorem values, inference interfaces, and theory/dependency handling.
27 Isabelle source, src/Pure/assumption.ML, same revision. Scoped assumptions and explicit inner-to-outer export transformations.
28 Isabelle source, src/Pure/conv.ML, same revision. Proof-producing conversion combinators, composition, alternatives, and binder traversal.
29 Lean 4 source, src/Lean/Expr.lean. Expression representation and structural operations. The link follows master; pin the source revision before a port.
30 Lean 4 source, src/Lean/MetavarContext.lean, revision c29b6dda4f7c20e3eeaa717c4e565663c5cfa364. Metavariable scope, ownership, nested reasoning, and assignment management. See also its generated API documentation.
31 Lean 4 source, src/Lean/Meta/Tactic/Grind/Types.lean, same revision. Cooperating-solver types and the documented need to preserve congruence argument pairing during proof reconstruction.
32 Rob Arthan. HOL Constant Definition Done Right. ITP 2014, LNCS 8558, 531–536. Loose specifications of constants, OpenTheory's defineConstList.
33 Ondřej Kunčar and Andrei Popescu. A Consistent Foundation for Isabelle/HOL. Journal of Automated Reasoning 62(4), 531–555, 2019. Orthogonality and termination of overloaded definitions; ground semantics.
34 Ondřej Kunčar. Correctness of Isabelle's Cyclicity Checker: Implementability of Overloading in Proof Assistants. CPP 2015, 85–94. The checker, its completeness under orthogonality, and the cycle through a type definition that once allowed a proof of False.
35 Arve Gengelbach and Johannes Åman Pohjola. A Verified Cyclicity Checker: For Theories with Overloaded Constants. ITP 2022, LIPIcs 237. A verified checker for overloading in HOL4.
36 Florian Haftmann and Makarius Wenzel. Constructive Type Classes in Isabelle. TYPES 2006, LNCS 4502, 160–174, 2007. Classes as locales with class predicates.
37 Markus Wenzel. Type Classes and Overloading in Higher-Order Logic. TPHOLs 1997, LNCS 1275, 307–322. Classes and overloading add no logical strength to HOL.
[38] Tobias Nipkow. Order-Sorted Polymorphism in Isabelle. In Logical Environments, Cambridge University Press, 1993. Sorts, arities, and coregularity.
39 Ondřej Kunčar and Andrei Popescu. Comprehending Isabelle/HOL's Consistency. ESOP 2017, LNCS 10201, 724–749. Consistency again, by translation into HOL with comprehension types.
40 Joe Leslie-Hurd. OpenTheory Article File Format, version 6, 2014. The stack machine, its commands, and the theorems defineTypeOp and defineConstList produce.
[41] Joe Hurd. The OpenTheory Standard Theory Library. NASA Formal Methods 2011, LNCS 6617. Packages exported from HOL Light and HOL4.
42 The Isabelle System Manual (isabelle doc system), Isabelle2025-2: components, isabelle build, theory exports, and the Isabelle server.
43 Isabelle2025-2 source, src/Pure/Build/export_theory.scala and export_theory.ML. What the theory export contains: types, constants, definitions, classes, arities, theorems with dependencies, and proof terms.
44 Deducteam. isabelle_dedukti, an Isabelle component exporting Isabelle proofs to Dedukti. Measurements of proof export for HOL's first theories.
[45] Cezary Kaliszyk and Alexander Krauss. Scalable LCF-Style Proof Translation. ITP 2013, LNCS 7998. Isabelle's importer for HOL Light, the model for replaying our articles in Isabelle.
[46] Robert M. Corless, David J. Jeffrey, Stephen M. Watt, and James H. Davenport. "According to Abramowitz and Stegun" or arccoth needn't be uncouth. ACM SIGSAM Bulletin 34(2), 2000. Branch cuts and their closures for computer algebra.
47 NIST Digital Library of Mathematical Functions, chapter 4. Principal branches of the elementary functions.
[48] Fredrik Johansson. Arb: Efficient Arbitrary-Precision Midpoint-Radius Interval Arithmetic. IEEE Transactions on Computers 66(8), 2017. Ball arithmetic, as apn_mojo implements it.
[49] Ramana Kumar and Joe Hurd. Standalone Tactics Using OpenTheory. ITP 2012, LNCS 7406. OpenTheory as an exchange format, and why Isabelle/HOL's kernel is harder to translate than HOL4's or HOL Light's.