Skip to content

Latest commit

 

History

History
1030 lines (928 loc) · 75.2 KB

REQUEST-PROTOCOL.md

File metadata and controls

1030 lines (928 loc) · 75.2 KB

Stateful calculus request protocol

The verifier reconstructs, from a source's Fragment tree and the types the front computes, one request of the stateful calculus per code unit, and the single pass checks it. This is a consumer boundary for lowered programs; it does not certify TypeScript text by itself.

This document owns the verifier's command line, the wire text every document uses, and the request and node-evidence structures in their JSON spelling; FRAGMENT owns the source AST encoding, SOURCE-CLAIMS the claims' shape and the execution graph document, certified imports and the stage store the module interfaces, and diagnostics the failure metadata. The codecs are RequestJson.lean, over the constructors of Calculus.lean; the tables below list every constructor they spell.

Run the verifier

Build from lean with lake build; the executable is .lake/build/bin/verifier. Its modes (lean/Main.lean):

verifier --check-unit 8             <unit-input.json>
verifier --unit-worker 8
verifier --lower-control-flow       <ast.json>
  • --check-unit 8 <unit-input.json> checks one canonical self-relative SCC UnitInput by the single pass (UnitCheck.checkUnitFile, FilePlans.passGroupMode8), printing its UnitOutput JSON line (verdict, published UnitInterface, and caller-side assumed row tables) and exiting 0 on an accepted verdict or 1 on a refusal.
  • --unit-worker 8 is a persistent JSON-line worker (UnitCheck.unitWorker) serving inspect-module, unbound-imports, project-unit, check-unit, match-rows, and render-refusal over standard input/output for pipeline/unit-scheduler.mts (the stage store).
  • A file's units are the strongly connected components of its functions that reach each other by name, its initialization among them where its mentions place it (units). A unit is named by its leader, name@offset for a function and init for the initialization. A run's request names its roots (UnitSelection.select), and the scheduler checks every unit those roots reach across the file and its imported modules; a unit depended on with no verdict leaves its dependents unverified.
  • <depth> limits a step's expression proof-search depth; it is not an execution budget and is not part of the request or the safety theorem. With TSCERT_PASS_REFUSALS=raw the pass also writes its raw refusal to standard error. Controls supply adversarial proposals in UnitInput.force (or --force-proposals name[,name…] before --check-unit 8). TSCERT_COUNTS, TSCERT_OBSERVE, TSCERT_PROFILE, and TSCERT_DUMP print diagnostic counts, point states, timings (work.jsonl), and walk traces.
  • --lower-control-flow prints the execution graphs Lean builds from the Fragment (SourceFlow.document, the execution graph); make lowering runs it.

--subtype-rounds <n> before any mode sets the frontier-unfolding budget of every subtype comparison, including declared bounds and instance-image equality during lowering and checking; the default is 4096 rounds. A frontier may contain any finite number of comparisons. The budget is execution policy, absent from every document. The acceptance soundness theorem quantifies over every budget, so a smaller budget can prevent verification and cannot authorize a typing step.

Exit status: 0 on success; 1 on a refusal, which prints reject: <reason> and then end of refusal on standard error (RequestCli.refuse); 2 on a usage error; 3 on an operational failure (a file it cannot read or write, any exception), with a first line error: .

The file worker

--file-worker 8 prepares the file as --verify-interface-stage 8 does (RequestCli.prepareUnitsFile: the fragment and interfaces decoded, the file's claims and front lowered), or refuses as it does, before any line. With TSCERT_TRACE_PROPOSALS set, each checked group emits its unit identity and ordered proposal answers on standard error. A named empty answer is JSON null. A proposed callable reports the normal and exceptional bounds, the returned footprint and the return alias.

It then prints its preparation line, and reads request lines from standard input until it ends; for each it checks the units it names, one after another, each by the check --verify-interface-stage 8 makes of it (PreparedFile.check: the unit's group planned, then checked), and prints each unit's verdict line as its check ends, flushed. It exits 0 at the end of its input. The lines (lean/Verification/Source/WorkerWire.lean; the same types in pipeline/stage-execution.mts, WorkerPrepared, VerdictLine, WorkerRequest):

  • the preparation line {"selected","established"}: the units the selection checks in the order their checks run, each {"unit","members"}, and the module units the interfaces establish;
  • a request line {"units"}: the identities of the units to check, each one the preparation line names, or null for every one in order;
  • a verdict line, {"unit","members","accepted","depends","elaboration","contracts"} or {"unit","members","refusal","elaboration","contracts"}, as --verify-interface-stage 8 prints it; elaboration the first elaboration refusal among the unit's group, or null. The first non-null one in the order the checks run is the file's refusal, which --verify-interface-stage 8 reports as its refusal. contracts lists the contracts the group's check read, each once (SourceElaboration.ContractRead), which no verdict reads: a member, {"member":{"declaration","key"}}, the key of the declaration whose row states it, the declaration by the identity {"module","name","span"} the declaration document gives it and the key as that document writes one (a string, or {"symbol"}), recorded where the walk or the lowering computes the member's type (SourceElaboration.recordMember); a value of the declaration document, {"value":{"module","name","specifier","imported","local"}}, its declaration and binding, for a name the walk types or the lowering reads a prototype through (SourceElaboration.recordName).

For stage-store lookup the driver sets TSCERT_SLICE_DRIVER=1. Preparation and the units request retain their formats. The worker prints slice-order <JSON array of unit IDs>, a callee-first permutation of the request. Each unit ends with slice-verdict <materialized verdict line>. Between these lines the worker and driver exchange one lookup at a time in the worker's private execution directory.

  • The worker writes the complete relative input to slice-input and flushes slice-lookup check-slice or slice-lookup propose-slice.
  • The driver hashes the program line and each consumed result line and atomically renames a complete reply to slice-reply. JSON null requests execution. A hit supplies the stored object with fields operation, members, answers, resolution and line. Members and local dependencies identify initialization or a declaration and overload ordinal. A module dependency identifies its provider through a reached declaration. A stored located refusal carries its heading, site, reason and raw checker line. A node record adds the member, optional closure, graph label and checker witness. An edge adds its exit, target, required knowledge and optional handler type reference. An expression claim identifies its obligation in the member by index and records whether the subtype search exhausted its budget. For exhaustion the public record carries the current source span in both the judgment and the source map. A member elaboration failure names the member whose plan supplies its message. The worker resolves these references when printing the public verdict. The resolution holds the ordered computed stand-ins or a planning error. A check that finds a standalone proposal receives {"resume":object}. A proposal lookup that finds a completed check receives {"checked":object}. The worker consumes and removes the reply before proceeding.
  • A miss produces slice-result <JSON object> after the proposals and verdict are available. A validated hit produces slice-hit. The worker materializes source coordinates locally in both cases.
  • An unrequested dependency first probes with slice-lookup probe-check-slice. A miss receives null and ends with slice-skip before the proposal-only lookup. A complete check can supply its named answers on a hit.

The operation key and publication rules are those of worker stages.

When --module-interface runs with TSCERT_SLICE_DRIVER=1 (and without force containing "imports"), it uses the same slice-input / slice-lookup / slice-reply / slice-result / slice-hit / slice-skip exchange per reachable group against the shared "pass" slice store, then prints the closed interface document on one line prefixed with interface-result <json>. The driver strips the protocol lines and delivers only <json>\n as the stage's output.

A line of another shape, or a unit the selection does not check, is an operational failure (exit 3). A unit's verdict line is a function of the command's arguments, its input files and environment, and the unit: the units checked before it in the process do not change it (worker stages). Its acceptance is mode8Accepted_sound's, case main (the single pass's theorem).

Wire text

Every document the tools exchange (the parser's fragment and declarations, the module interfaces and their requests, the flow, a diagnostic record) is JSON text in UTF-8, and every string it holds, key or value, is well-formed Unicode: a \u escape of a surrogate is one of a pair. Each reader refuses a document breaking either before it reads a value: Lean (RequestCli.readJson refuses bytes that are not UTF-8, and RequestCli.loneSurrogate a lone surrogate escape, which Lean's JSON parser would read as U+FFFD; it reads the text's characters only where its bytes hold a backslash, u and d or D in a row, the start of every surrogate escape, RequestCli.wireSurrogate_eq) and the TypeScript tools (wireText for the bytes, requireWellFormed for the strings). A writer refuses such a string before writing it: the parser's gate a source string holding a lone surrogate (source fragment).

Lean compares decoded keys while reading each object, refusing the document if a key occurs twice. Key order, whitespace and equivalent escapes give the same value. A natural number is an integer literal, in exponent form too (0e0, -0), never a fraction (0.0).

Decoding is strict: it decodes, re-encodes and compares, so every field is required, an unknown field is refused, recursively, and a field whose absence is its one spelling of "none" (stated below where it applies) is refused when written empty. A document either has the current shape or is refused; the refusal names, by its path from the document, the first field where the document and its re-encoding differ. The JSON parser and codecs are part of the input-meaning boundary; round-trip tests are not a proof of fidelity to external source text.

Request fields

Field Meaning
types The type graph: a finite array of rows (below). Its array positions are type labels.
program A finite array of nodes {expression, continuation, handler}. Its positions are control-flow labels.
claims One point claim {context, type} per program node, in the same order: the entry context and the expression-result type.
result The required result type of the graph.
start The designated control-flow entry label.
inputs External argument types in slot order. The designated entry context must equal this contract; [] for closed invocation. The input contract is a premise of the safety theorem, never inferred from point claims.
codes The graph code the program creates (code requests); [] when there is none.
entrySeparation The separation the request assumes of its inputs beside their types, {depth, facts} as a knowledge's (separation facts), {"depth": 0, "facts": []} for none: a premise of the safety theorem, as inputs is; the entry's knowledge may state what follows from it.
promise null, or a guard's promise [asserts, [slot, T]]: the returns establish a type guard's true or false (asserts false) or an assertion function's undefined (true), each true or undefined with the input in entry slot slot a value of T; result is then the plain result.

A type is a list of type labels, interpreted as their union; the empty list is bottom. Every label, including labels in unused type definitions and intermediate certificate types, must index the request's types array, so a dangling label is refused rather than given the total Lean graph's default interpretation. Control-flow target existence and expression scope are checked by the graph consumer.

Rows

A row is one of:

  • a clause row, the array of its clauses (below);
  • a scheme row {"scheme": {"binders": [p, …], "signatures": [contract, …]}}, a generic callable $\forall\vec p.\,\Sigma$ whose signatures are contract records (below) over types that may mention its binders, with "bounds": [[p, type], …] when a binder is bounded (the bound is read outside the binders), "variadic": [restContract, …] for variadic signatures, whose rest may be a binder or a packed parameter, "resolution": [{"input": i, "observation": o, "result": r}, …] when binders form resolution descriptors, each naming three positions among the binders, or two with r null for an observation, and "construct": true for a construct scheme, a generic constructor type whose signatures are construct signatures with receiver []; each of these four left out when empty or false;
  • a parameter row {"param": i, "name": n, "kind": k}, which names its own label $i$, in n the binder it stands for (the name has no meaning), and its mandatory kind "value", "arguments" or "packed" (packed binders), preserved by instantiation and binder renaming;
  • a meet row {"meet": p, "clauses": [...], "also": [...]}, the value parameter row $p$ within the clauses (V & DepSafe), and the value parameter rows also as well (U ⊓ T for U extends T; left out when none).

Only a clause row has clauses. The graph of a table $T$ (StoreView.graph) is

$$G.\mathit{rows}(i)=\begin{cases}\vec c & T[i]=\vec c\\ [\,] & \text{otherwise}\end{cases} \qquad G.\mathit{schemes}(i)=(\vec p;\Sigma)\iff T[i]=\mathsf{scheme}(\vec p,\Sigma) \qquad G.\mathit{parameterKinds}(i)=\mathsf{some}(k)\iff T[i]=\mathsf{param}(i,n,k), \qquad G.\mathit{params}(i)\iff G.\mathit{parameterKinds}(i)\ne\mathsf{none}, \qquad G.\mathit{meets}(i)=(p;\vec c)\land G.\mathit{meetParams}(i)=\vec q\iff T[i]=\mathsf{meet}(p,\vec c,\vec q).$$

with the meaning given in Parameter and scheme rows. RequestJson.validRequest requires every type the request states to name labels the store holds (StoreView.valid) and the store to be well formed (StoreView.wellFormed). A checked request's store (EquationStore.Checked) holds equations the equation validator accepted, every template scoped and constructor-headed and every parameter of a declared kind, and its labels are labels of their signature, so both checks hold of it by construction; a store that still grows is well formed when every head it holds has a body. A subtype instantiation choice names a scheme row and its image types. A table with no scheme rows has no quantified signature to instantiate.

Clauses

A clause row is a union of clauses (PositiveNormalization.Clause). The request holds normalized clauses: the grammar has no conjunction above the clause level, and a writer holding positive formulas normalizes them itself (normal form). No string, generic or unsupported-type fallback is supplied by this protocol. Operands ([4] below) are types, lists of labels; references and arrow operands may point back into the same finite graph, representing guarded regular recursion.

Clause JSON
Top: every value, permitting no operation "top"
Every closed JavaScript value, internal spines excluded "source"
Null; undefined "nul"; "undef"
Booleans; one Boolean "bool"; {"boolLit":{"value":true}}
Numbers; one number, by the bit pattern of its double as an unsigned 64-bit decimal string; a tag set of numbers "num"; {"numLit":{"bits":"4607182418800017408"}}; {"numIn":{"bits":["…","…"]}}
The safe integers "int"
Strings; one string; a tag set of strings "str"; {"strLit":{"value":"a"}}; {"strIn":{"values":["a","b"]}}
Bigints; one bigint, a JSON number of any length "bigint"; {"bigintLit":{"value":-5}}
Symbols; one symbol, by the identity a symbol key {"symbol":0} carries (no term introduces it) "symbol"; {"symbolLit":{"id":0}}
Record: invariant reference contracts first and rest, and readonly views, fields read at a sound upper bound with no write permission through this contract {"refs":{"first":[["value",[1]]],"rest":[],"views":[["seen",[1]]]}}
A record's optional fields: a key constrained only where the object has it "optional":[{"key":"field","readonly":false,"type":[4]}]
A record's methods, host-relative members (methods): fixed and variadic signatures, the quantified ones as scheme types, and the types the member's host must meet (a this parameter's) "methods":[{"key":"m","calls":[…],"rests":[],"schemes":[],"receivers":[]}]
A record's own-key bounds: each says the object's own keys are among its keys, or, with among false, none of them; a key one does not admit is not the object's own, and a read of it continues at the prototype "bounds":[{"among":false,"keys":["map"]}]
A record's stable keys, each one of its readonly members (stable keys) "stable":["kind"]
Plain object: a record's contracts and readonly index views [class, operand], class "strings" (every string key), "numeric" (the canonical numeric keys) or "symbols" (every symbol key), each constraining every present own field under a key of its class {"dict":{"first":[],"rest":[],"views":[],"indexes":[["strings",[1,3]],["numeric",[1]]]}}
A plain object's writable index contracts, a mutable index signature's: every present own field under a key of the class holds exactly the operand; each is also listed in indexes "cells":[["strings",[1,3]]]
Intersection of callable contracts, fixed and variadic {"arrs":{"arrows":[contract, …]}}
Callable object: invariant bag contracts first and rest, fixed and variadic signatures, and methods as a record's {"callable":{"first":[["value",[1]]],"rest":[],"arrows":[contract, …]}}
Class value: construct signatures, receiver {}, which new meets and no call does; variadic ones; its static fields as invariant first and rest and readonly views {"ctors":{"signatures":[contract, …]}}
Array spine: simultaneous tuple contracts, each with required, optional and rest positions; readonly contracts give element read capabilities {"list":{"first":{"required":[[4]],"optional":[],"rest":[4],"readonly":false,"presence":"readable"},"rest":[]}}
Argument list: simultaneous tuple contracts on the actuals a rest parameter receives, positions compared covariantly {"pack":{"first":{"required":[[4]],"optional":[],"rest":[0],"readonly":false,"presence":"dense"},"rest":[]}}

The rows marked as a record's fields are fields of refs and of dict. A field left out when empty: optional, methods, bounds and stable of refs and dict, cells of dict, variadic of arrs, callable and ctors, methods of callable, and first, rest and views of ctors. A variadic signature ("variadic": [contract, …]) has arguments [params, rest] and takes the actuals past params according to the argument-list contract rest.

A literal's identity is the bit pattern of the double it denotes, so distinct spellings of one value are one clause; two spellings a codec failed to identify would be two singletons, which costs completeness and never soundness. A tag set lists two or more elements, sorted and distinct, its one spelling (tag sets). Tuple contracts require presence with exactly "dense", "readable" or "sparse"; for argument packs it has no semantic effect, and lowering writes "dense" and readonly: false.

Contracts and effects

Every signature is a contract record {"receiver": R, "arguments": A, "result": B, "effect": e}: A the list of argument types ([params, rest] for a variadic one), R the value a call passes as this, undefined for a plain call; a signature indifferent to it names a "top" row, and there is no missing-field default. The receiver is contravariant, like the arguments. A class value's and a method's signatures have receiver {}, a construct scheme's []. Effectful contracts use these records in graph rows, scheme rows, code entries and subtype certificates; a code entry must discharge both safety and its effect (the definition rules).

The effect e is the serialized effect.

The serialized effect

Every document that carries a callable's effect (the Fragment's declaration document, a request's types tables, the claims document, module interfaces, diagnostics) writes it in this one shape: its two exits, a normal return's and a throw's, each a frame and postconditions; its promise; and its preconditions (CallEffects.Effect). Arrays are ordered lists; every field is required but atEntry; an object of a union has exactly one of the alternatives' tags, at every depth.

type Nat = number;            // a safe integer at least 0
type Integer = number | string; // a safe integer, else its canonical decimal
type Bits64 = string;         // 16 lowercase hexadecimal digits
type Change = "keep" | "init" | "scalar" | "extend" | "grow" | "any";
type Key = string | { symbol: Nat };
type Selector = { value: boolean; array: boolean; view: boolean };
type Region =
  | { field: { x: Nat; key: Key } } | { fields: { x: Nat } } | { cells: { x: Nat } }
  | { cls: Selector } | "all"
  | { path: { x: Nat; fields: string[]; key: Key } }
  | { pathFields: { x: Nat; fields: string[] } } | { pathCells: { x: Nat; fields: string[] } }
  | { spine: { x: Nat; fields: string[] } };
type Frame = { region: Region; change: Change }[];
type Path = { root: Nat; fields: string[] };
type Literal = "null" | "undefined" | "true" | "false"
  | { num: { bits: Bits64 } } | { str: { value: string } }
  | { bigint: { value: string } } | { sym: { id: Nat } };
type Witness = { path: Path } | { literal: Literal };
type WitnessSeq = { fixed: { xs: Witness[] } } | { restFrom: { first: Nat } }
  | { append: { left: WitnessSeq; right: WitnessSeq } };
type TransportSchema = { shift: Nat; overrides: [Nat, Witness][]; boxed: boolean; stable: Nat[] };
type LinearTermKind = "value" | "length" | "view" | "strLength" | { bitMask: { mask: Nat } };
type LinearTerm = { kind: LinearTermKind; slot: Nat; path: string[]; atEntry?: true };
type StepVar = { before: { t: LinearTerm } } | { after: { t: LinearTerm } };
type LinearFact<V> = { le: { form: [V, Integer][]; bound: Integer } }
  | { ne: { form: [V, Integer][]; bound: Integer } };
type Clause<V> = LinearFact<V> | { either: { left: Clause<V>; right: Clause<V> } };
type IndexShift = { terms: [LinearTerm, Integer][]; offset: Integer };
type ElemTarget = { self: { path: string[] } }
  | { parallel: { slot: Nat; path: string[]; shift: IndexShift; elemPath: string[] } };
type BodyVariable = "index" | "elem" | { offset: { delta: Nat } }
  | { project: { kind: LinearTermKind; path: string[] } }
  | { parallel: { slot: Nat; path: string[]; shift: IndexShift; kind: LinearTermKind; elemPath: string[] } }
  | { free: { t: LinearTerm } };
type IndexBound = { base: LinearTerm | null; offset: Integer };
type BodyClause = Clause<BodyVariable>
  | { guarded: { target: ElemTarget; tag: "null" | "undefined" | "true" | "false" | "notNull" | "notUndefined" | "notTrue" | "notFalse"; body: BodyClause } }
  | { bodyEither: { left: BodyClause; right: BodyClause } };
type IndexFact = { index: { slot: Nat } } | { int: { slot: Nat } } | { pastSafe: { slot: Nat } }
  | { length: { array: Nat; length: Nat } } | { bound: { array: Nat; index: Nat; strict: boolean } }
  | { linear: { fact: LinearFact<LinearTerm> } } | { either: { left: IndexFact; right: IndexFact } }
  | { guarded: { slot: Nat; path: string[]; tag: "null" | "undefined" | "true" | "false" | "notNull" | "notUndefined" | "notTrue" | "notFalse"; body: IndexFact } }
  | { element: { value: Nat; array: Nat; index: IndexShift } }
  | { fieldRead: { value: Nat; object: Nat; field: string } }
  | { every: { slot: Nat; path: string[]; start: IndexBound; stop: IndexBound; body: BodyClause[] } }
  | { atIndex: { slot: Nat; path: string[]; index: IndexShift; guard: "null" | "undefined" | "true" | "false" | null; body: Clause<BodyVariable> } }
  | { apart: { slot: Nat; path: string[]; other: Nat; otherPath: string[] } }
  | { spineApart: { slot: Nat; path: string[]; other: Nat; otherPath: string[] } }
  | { elemSpineApart: { slot: Nat; path: string[]; other: Nat; otherPath: string[] } }
  | { same: { slot: Nat; other: Nat } };
type ElementKinds = ("null" | "undefined" | "boolean" | "number" | "string" | "bigint" | "symbol" | "object")[];
type OperationPost =
  | { arith: { op: Arith; left: Witness; right: Witness; result: Path } }
  | { stringLength: { string: Path; result: Path } }
  | { stringRead: { string: Path; index: Witness; result: Path } }
  | { lengthsKept: { x: Nat; exit: Nat } } | { boundedWrite: { x: Nat; i: Nat; exit: Nat } }
  | { push: { x: Nat; exit: Nat; args: WitnessSeq } }
  | { fact: { phase: "before" | "after"; lift: Nat; fact: IndexFact } }
  | { freshSpine: { x: Nat } } | { freshObject: { x: Nat } } | { freshRegion: { x: Nat } }
  | { shallowCopy: { src: Nat; dst: Nat } }
  | { elementsWhen: { x: Nat; value: Literal; y: Nat; predicate: ElementKinds } }
  | { spineExtends: { x: Nat } }
  | { viewWrite: { x: Nat; i: Nat; v: Nat; format: "uint8" | "uint16" | "int32" | "float64" | null } };
type Formula = { transition: { effect: Frame } } | { operation: { post: OperationPost } }
  | { linear: { fact: LinearFact<StepVar> } } | { defined: { v: StepVar } }
  | { transport: TransportSchema } | { and: { left: Formula; right: Formula } } | "truth" | "falsity";
type ExitSchema = { frame: Frame; ensures: Formula[] };
type Exits<A> = { normal: A; exceptional: A };
type CallPromise = { guards: { param: Nat } } | { asserts: { param: Nat } };
type CallEffect = { exits: Exits<ExitSchema>; promise: CallPromise | null;
  requires: ElementKinds | null; pre: IndexFact[] };

Arith is the calculus's binary operator by its name. Each record is the Lean structure of the same fields in the same order, and each single-key object the constructor of that name, exit naming x', a region's fields its path, cell's name its binder. The formulas are exactly the constructors of FormulaF WitnessSeq TransportSchema that reference no assertion-arena node: a contract states no assertion (self-contained formulas). A literal is one of the eight primitive constants of the calculus, a number by its double's bits and a symbol by its identity: no object identity, spine or executable term is a literal. An integer is a JSON number in the safe range and a decimal string, with no leading zero, plus sign or negative zero, outside it; a bigint literal is always its decimal string.

Positions and ordering

Entry position 0 is the receiver and i + 1 the i-th actual; at both exits 0 is the returned or thrown value, 1 the receiver and i + 2 the i-th actual. A promise's param is the actual's index. Frames and transitions read entry positions; arithmetic and string posts, freshness and elementsWhen exit positions; push reads its sequence at the entry, x at the entry and exit at the exit; spineExtends and viewWrite entry positions. A fact's positions are those of its phase raised by lift, its entry terms the invocation's entry; a StepVar names its phase, so its term has no atEntry. restFrom first is the supplied actual positions from first on, the receiver excluded; append concatenates.

A transport's override is the first one for its slot; repeated and reordered overrides are kept as written. Frame entries combine by the largest change admitted at a location, formula lists and and are conjunction, and neither is sorted, merged or simplified: the serialized form is the structure the effect holds. An elements predicate alone is a set, written in the order of the grammar with no kind twice.

Reading

The reader reads a value and writes it again: an effect that is not exactly that writing (an unknown, missing or repeated field, a second tag, a wrong scalar, a malformed pair, a noncanonical integer or literal) is refused at the first place it differs, by its path in the document. A document stating an object key twice, its keys compared as the strings they state with their escapes decoded, is refused when its text is read, before its objects are read into maps. A decoded effect references no assertion, states primitive literals only and nests at most 256 deep (EffectCodec.decode_sound); every effect of that kind is read back as written (EffectCodec.decode_encode). An effect is admitted as a contract where every exact view write it states (viewWrite at a format, at either exit and at any depth of and) has its element type's range facts (ElementKind.preFacts) among pre, which its callers establish (EffectJson.admit, Effect.exactWrite_pre). A symbol key and a symbol literal name a unique symbol of their document's symbols and are read at its canonical number before the effect is (certified imports). The front end's reader of a types table (decodeCallEffect) reads a subset of that grammar: the same records and unions, each field an own field, the same nesting limit, bits as sixteen lowercase hexadecimal digits, a bigint as its canonical decimal string and an integer as a safe number or the canonical decimal string of another; a position (Nat) only in the safe range. It reads parsed values, so a number written 1.0 reads as 1. Scope at a callable's arity, canonical transports, the independence of a conjunction's second exit and the stability of a rest allocation are checked where a decision reads them (the design).

A declaration's statement (Modifies<P, T>, Fresh<T>, the Fragment's stated) is its exits in the same form, and so are the claims document's proposed exits of a function (exits) and of the function it returns (resultExits), and a module interface's established ones.

Terms

The JSON codecs use Lean's derived constructor encoding: a nullary constructor is a string, any other a single-key object whose value holds its named fields. For example, the plain call of slot zero with the one actual null:

{ "invoke": { "f": { "var": { "i": 0 } }, "r": "undef", "args": ["nul"] } }

The encoding follows the term grammar, writing t for a nested term:

Term JSON
slot $i$ {"var":{"i":0}}
null, undefined, true, false "nul", "undef", "tru", "fls"
a number, by its bits {"num":{"bits":"…"}}
a string {"str":{"value":"a"}}
a bigint {"bigint":{"value":-5}}
a symbol, by its identity {"sym":{"id":0}}
$\mathsf{let}(t,t)$ {"letE":{"a":t,"b":t}}
$\mathsf{invoke}(t,t,[t,\ldots])$: callee, receiver, actuals {"invoke":{"f":t,"r":t,"args":[t]}}
$\mathsf{construct}(t,[t,\ldots])$: new {"construct":{"f":t,"args":[t]}}
allocation with call code and ordered initializers {"makeAt":{"call":c,"names":["value"],"inits":[t]}}
allocation from parts, the keys drop left out {"merge":{"drop":["k"],"a":t,"b":t}}
allocation at a key known only at run time {"makeKey":{"key":t,"init":t}}
field read {"readAt":{"field":"value","a":t}}
computed string-key read {"indexAt":{"a":t,"key":t}}
field write {"writeAt":{"field":"value","a":t,"b":t}}
$\mathsf{test}_k(t)$ {"test":{"k":"isNul","a":t}}
$\mathsf{if}\;t\;t\;t$ {"ite":{"c":t,"t":t,"e":t}}
binary operator {"arith":{"op":"add","a":t,"b":t}}
array spine with initial elements {"arrLit":{"inits":[t]}}
element at a numeric index {"elemAt":{"a":t,"i":t}}
spine with an element set {"setElem":{"a":t,"i":t,"v":t}}
length of a spine or a string {"lenOf":{"a":t}}
spread actual {"spread":{"a":t}}
throw {"throw":{"a":t}}

A field key is a string or {"symbol":i}. The operators (Arith) are add, sub, mul, div, pow, xor, rem, bitAnd, bitOr, shl, shr, ushr, lt, le, gt, ge, eq (strict equality) and looseEq (abstract equality). objAt (an object identity), arr (a spine's locations), goto and frame (a running graph code) are runtime forms: no evidence rule types them, so no supplied program holds one, in unused branches and closure bodies included, and a location never appears in a supplied program.

The tests (Tag) are:

Test JSON
null; undefined; null or undefined "isNul"; "isUndef"; "isNullish"
a Boolean; a number; a string; a bigint; a symbol "isBool"; "isNum"; "isStr"; "isBigint"; "isSymbol"
an object; an object with call code ("function") "isRef"; "isFun"
typeof v === "object": null, or an object without call code "typeofObject"
Array.isArray: an object owning the spine key "isArray"
JavaScript's ToBoolean "truthy"
equality with one number, string, Boolean or bigint {"numEq":{"bits":"…"}}, {"strEq":{"value":"a"}}, {"boolEq":{"value":true}}, {"bigintEq":{"value":5}}
key in v: an own key or one the prototype chain reaches {"hasKey":{"key":"k"}}

Nodes, continuations and targets

A node is {"expression": t, "continuation": k, "handler": T | null}, T a target {"label": n, "mapping": [i, …] | null}. A mapping acts after the result is pushed: {"label": 3, "mapping": [0, 2]} gives target slot zero source slot zero and target slot one source slot two; null means identity selection, and a missing mapping is refused. A handler is where a throw out of the node's expression goes, the thrown value pushed first as a bind pushes a value (handlers).

Continuation JSON
return "ret"
bind the result and continue {"bind":{"next":T}}
discard the result and continue {"effect":{"next":T}}
branch on a Boolean {"branch":{"yes":T,"no":T}}
branch on a Boolean, binding it {"branchBind":{"yes":T,"no":T}}
test the result, bind it, branch {"tagBind":{"test":"isNul","yes":T,"no":T}}

Code descriptors

A descriptor c is the call code an allocation gives its object:

  • "absent": a plain object.
  • {"bound":{"target":t,"receiver":t,"pre":[t]}}: what .bind creates. It holds the target, the receiver and the argument prefix as values and allocates no field; its invocation drops the receiver it is called with and invokes the target with the saved one and the prefix before the new actuals.
  • {"graph":{"arity":1,"exprs":[t],"conts":[[k,T]],"start":0,"caps":[t]}}: code whose body is a control-flow graph, as a program is: its node expressions, each node's continuation and handler (null for none), the entry label and the captured values. "kind" is "construct" for a class's construct-only code, which only new runs, and "sloppy" for a sloppy function that reads its receiver, whose call binds an object receiver unchanged and has no step for another; "rest": true marks code collecting a rest. Each is left out for call code and for code without a rest, its one spelling.

Invocation starts graph code at start in the environment [this, parameter_0, …, parameter_{arity-1}] ++ captures ++ [self], self the invoked object; new passes undefined for this. Code with a rest first allocates the spine of the actuals past its parameters, found in slot zero, before the receiver. The node expressions are scoped by that environment alone. Every closure a source program creates is graph code.

Code requests

A request's codes lists the graph code its program creates, one {"entry": {"arity","exprs","conts","start","captures","row","spine"}, "claims": [...], "async": b} per code and signature, nested code before the code creating it: captures the captured values' types, row the signature as a contract record, spine, for code with a rest, the rest-spine type its frame starts with (null otherwise), claims one point claim per node of the code's graph, as claims is for the program, and async whether the source declares the function async.

Evidence

The evidence for a request (Response) is {"certificate": [...]}, a list of node evidence per program node, and, when the request has codes, "codes": one such list per code request, in its order; and, when its derivations use any, "readSummaries", the request's read summaries. The summaries are checked first, each once; the codes then, in order, each at its entry [spine, receiver, parameters…, captures…] (no spine without a rest) and its row's result, each seeing the codes before it; the program is then checked seeing them all. The request's expression obligations in the unit use the same summaries.

A node's evidence (NodeEvidence) has the fields below, given here as the values they denote:

  • ordinary: the ordinary typing derivation of its expression, whose root is the node's sequent: {"proof": {"tree": d}}, a derivation tree d, each node {"node": {"claim": {context, term, type}, "rule": r, "premises": [...]}}; "effect", the proof its step evidence carries; or null, none, where the step evidence establishes the step alone, which a node without step evidence never is;
  • sequent: {context, term, type}, the node's sequent where ordinary is null and the step evidence carries no proof, and null otherwise, where the sequent is the root of ordinary's derivation or of the step's proof. The steps carrying a proof at the node's sequent are ordinary, pure, reading, created, typedRead, allocated and written (step evidence); a slicedRead's proof is at the location's contract. A node spelling its sequent otherwise is refused;
  • edges: one subtype-evidence list per outgoing edge, one entry per destination slot;
  • knowledge, effect, output: the heap facts at entry, the step evidence, and the facts after the step;
  • handler: null, or [T, p] for a node with a handler: the type the thrown value is bound at, which must have a top clause, and the handler edge's subtype-evidence list;
  • implies, yields, arguments, promise: the promise facts, empty or null unless the request has a promise.

Expression sequents repeat their contexts, terms and result types; the consumer checks these against the request, so this redundancy cannot substitute a different program or different claims. Every label in the evidence is bounds checked.

Rules

A derivation node names the typing rule it applies: var, nul, undef, tru, fls, truLit, flsLit, numLit, num, strLit, str, bigintLit, bigint, funGraph, funGraphSelf, ctorScheme, ctorGraph, callableGraph, app, letE, alloc, read, readView, write, arith, test, readDict, indexDict, readOptional, readProto, arrLit, elem, setElem, len, lenStr, elemStr, elemOpt, elemAny, ifBool, ifTrue, ifFalse, ifKnown, ifBoolVar, unionVar, callCallable, readCallable, readBagView, writeCallable, arrParts, callRest, callPacked, bindE, bindRestE, bindMember, construct, constructRest, sub, throw, merge, makeKey, lenView or readSummary. RequestJson.lean derives the codec of Rule, so the rules are the inductive's constructors and a rule added there extends the protocol; tests/rule-inventory.mts holds the two to the same set. By kind:

  • Values. var, nul, undef, tru, fls; truLit and flsLit, the Boolean singleton introductions; numLit and num, a literal at its own singleton and at the family; strLit and str; bigintLit and bigint.
  • Binding and control. letE; ifBool, an ite with three premises (the Boolean condition and the two arms, each at the root's context and requested type; Boolean singleton unions are allowed, null or mixed conditions refused); ifTrue and ifFalse, the two answers of the single shape-test rule ifTag, split so that the evidence records which answer it relies on; ifKnown with its answer; ifBoolVar with trueType, falseType and two arm premises, an ite whose condition is a slot at a Boolean, the lists expanding to the corresponding singleton clauses, each arm at the root context with that slot replaced, narrowing no other binding; unionVar with its slot, eliminating a union member by member; sub with its subtype proof; throw, whose one premise types the thrown operand.
  • Objects. alloc at a record type, whose fields, where one is the array spine key, are an array of the graph's built-ins (allocBuiltins), and whose stable keys are among its fields, held as views, with no array spine beside them (stable keys); at a dictionary type the typing rule allocDict, a literal allocated at a dictionary with no own-key bound, naming neither the prototype key nor the spine key; merge, an allocation from parts, whose two premises type the accumulator and the source, with subtype proofs subs for copied fields (allocation from parts); makeKey, whose two premises type the key and the initializer (at a computed key); read, write; readOptional with element and undef; readDict with keys, element and undef; indexDict with keys, keyKeys, element and undef; readView, a field named among a record's or a dictionary's views, at the bound the view states (no rule writes through a view); lenView with its slot, a view of length of the object in a context slot, by the term that tests it for an array; readProto with proto, a key one of a record's own-key bounds does not admit read from the prototype the record holds under [[proto]]; readSummary with its index, no premises, a read readAt f (var x) at entry index of the request's read summaries, whose key and result are the read's and whose receiver is the context's type at x.
  • Operators and tests. arith, a binary operator on two operands whose types it answers for pair by pair: arithmetic on two numbers or two bigints, a comparison on two numeric operands or two strings, equality where either operand is a primitive or an object with a field, into the family of its result kind; test, a tag test whose answer the operand's type does not settle, as a Boolean holding both literals, for ifBool to branch on.
  • Arrays and strings. On a spine, the value an array object holds in its spine field: arrLit allocates one location per element under the positions of a tuple contract; elem reads a required position named by a literal index at its contract, elemOpt (with undef) an optional or rest position at its contract or undefined, and elemAny (with undef) any numeric index into a homogeneous array at the element contract or undefined, independently of readonly and presence mode; setElem writes a named position, into its location or a fresh one the spine records; len reads the length as a number. lenStr reads a string's length, and elemStr (with str and undef) a string's code unit at any numeric index or undefined. arrParts (with elem and spreads) names the element type and flags the parts that are spreads, with one premise per part as callRest's further parts; its result is fresh storage with the element contract, either readonly flag and any chosen presence mode, the values filling every position, explicit undefined read from source holes included.
  • Code. funGraph (with arrays) creates graph code: its premises are the captures, each a slot of the node's context at the type the code was checked with, and every signature the created type offers must be an entry of the checked codes with those capture types; it checks no body, since the code's own certificate did. Code without a rest offers each row of its type's offerRows: each fixed signature, then each variadic signature's receiver, fixed parameters and result, in that order, each offering at least the code's arity. Code with a rest offers the variadic signatures only, each taking exactly the code's parameters, and arrays name their rest-spine types in order, each the spine of that signature's entry. At a scheme row the signatures are the scheme's. funGraphSelf creates a recursive closure of fixed arity at an arrow type, as funGraph, each entry's capture types followed by the created type, the self entry's. ctorGraph (with undef) creates a class value's construct-only code: an entry per construct signature, its receiver the undefined type, its effect the signature's (a variadic signature's effect is plain), with the code field, then one initializer premise per static field, then the captures. Rule.ctorScheme carries undef and creates construct-only code with the code field and capture premises. Its scheme has fixed signatures checked at the scheme's parameter rows. The capture types are independent of those rows. callableGraph (with arrays) creates a callable object: one initializer premise per field, then the captures, its code's entries as funGraph's, one per advertised overload; its result has a single initial bag contract, to which subtyping can add equivalent invariant requirements.
  • Calls. app and callCallable carry the selected signature's effect and take the callee premise, then the receiver premise at the selected signature's receiver, then the actuals, then one premise per position the signature declares and the call omits, each proving undefined at that position's contract: the term is invoke f r args, and a plain call's receiver is undefined. callRest (with effect, fixed, omitted, spreads and rest) carries the callee premise, the receiver premise, one premise per fixed actual, one undefined premise per fixed position the call omits, then one per further part: the actual at the element type, or, for a spread, the spine it reads, at a type whose elements that element type admits. callPacked (with effect, fixed, packed and rest) names how many actuals are fixed, the packed binder and the rest type, with premises for the callee, the receiver, each fixed actual and the value whose spine the last actual spreads. construct (with effect, which is plain) takes the constructor's premise, then one per actual and one undefined premise per position the signature declares and the construction omits. constructRest (with fixed, spreads and rest) is callRest without a receiver; its signature's effect is plain. readCallable and writeCallable use the first invariant bag operand, a callable object's or a class value's, and readBagView a class value's readonly static field, a view.
  • Binding methods. bindE has no premises: its term is makeAt (bound (var t) (var r) pre) [] [] with every prefix entry a slot, and the rule reads the target's type, the receiver's and the prefix's from the context. One fixed signature of the target must be the receiver slot's type, the prefix slots' types followed by the result's parameters, and the result's result; the result is one signature at any receiver. bindRestE binds a variadic target likewise. bindMember (with proofs, rests and receivers) has no premises: its term is letE (readAt k (var i)) (makeAt (bound (var 0) (var (i + 1)) []) [] []), which reads the member k from the object in slot i and binds it to that same object. The object's type must have one object clause with a method of key k; each fixed signature of the result must be covered by one of the method's, at any receiver, by the subtyping proofs the rule carries, one per parameter, then the result; each variadic one likewise, one per fixed parameter, then the rest, then the result; and the object's type must be within each type the method's host must meet, by one more proof each, in the method's order. With no proofs, the result may instead be one of the method's quantified signatures, a scheme row (HasTyUsing.bindScheme), which a call instantiates by sub.

Read summaries

readSummaries lists entries {"receiver": C, "field": f, "result": B, "arms": [...]}, one arm per member of C in members order, each {"view": A, "proof": p}: the view the member states for f and the subtype choices comparing A to B, or null where A is B. An entry is checked once against the request's graph and image check: exactly one arm per member, each member's view of f at A (a view of length only at a type shown to exclude some number, as readView requires) and each comparison accepted by the ordinary subtype checker (read summaries). An entry states no location, heap fact or cached value, and a summary field beside these is refused.

Subtype certificates

Subtype arrow certificates use ordered lists of argument types. A source certificate's p is the complete contract record. A union certificate contains pre, a, b, suffix, left, and right: pre and suffix are lists of unchanged argument types, and the selected argument splits from a ++ b into the two branches. combine retains its result types b and b', the two premise effects effect and other, and two branches; the meet of those effects must imply the target effect, and each source or rest covering must also imply it. empty requires an empty type at some argument position, not merely a zero-length argument list; emptyRecv requires the target's receiver to be empty, so that no call is named; recvUnion splits the target's receiver a ++ b into two branches, like union for an argument. A rest certificate's s is a variadic source signature with arguments: [params, rest] covering the target arrow: its first positions within params, the rest within the rest contract. Graph subtype search supports native argument lists and splits any position. There is one accepted certificate shape.

Heap facts

knowledge and output each contain cells, values, links, separation and elems (checked expression postconditions).

  • cells and values are lists of {slot, contents, field} facts: for a cell, about the named field of the object in the slot; for a value, about the slot itself. contents is a value set (ValueSets.lean), one component per kind of value: nul, undef, tru, fls, sym and arr are Booleans; num, str and big are {"these": {"xs": […]}} or {"allBut": {"xs": […]}}, the literals admitted or excluded (a number as its 64-bit pattern in decimal); obj is null, admitting no object, or a list of clauses, each a list of {"tag": k, "answer": b}, admitting an object meeting every clause, a clause being met where one of its tags answers so or reads a prototype for it.
  • links is a list of {cell, value, alias, field, optional} objects: alias: true means equal slot values; alias: false means the named field currently contains the other slot's value (a read link), or, with optional: true, that the object lacks the key and the other slot holds undefined.
  • separation is {depth, facts}, each fact {slot, fields, partners} addressed by level, level l naming slot depth - 1 - l: the fields fields of the object at level slot (null: every own location of it) and the fields of each partner [level, [field, …]] are different locations (separation facts), a timeless fact established by allocation and the reason a write to one cell keeps facts about another. A separation stating no fact is {"depth": 0, "facts": []}.
  • elems is a list of {slot, pred, cond, negated} elements facts: every present element of the array in slot slot is a value of a kind pred admits, pred being one Boolean per kind, {nul, undef, bool, num, str, big, sym, obj}. cond is null, or a slot: then the fact is stated where that slot holds a truthy value, or a falsy one where negated is true.

These are finite state assertions, not extra type labels. Current-content predicates are checked on every incoming edge; a predicate the rules do not support still requires a proof that the storage contract implies the claim.

The effect checker binds to the root expression sequent and runs on the view of the node's knowledge; the output it computes must establish output. Each outgoing edge reads output through its view and checks that its facts establish the destination's knowledge (knowledge-edge), in addition to ordinary type coverage. Effect-only continuations drop the result slot before transferring facts. External entry requires empty knowledge. Within a source statement, the pass derives checked facts along administrative paths, and the source consumer enforces the exact entry interfaces.

Step evidence

effect: null selects ordinary expression evidence; a non-null effect selects one of the checked StepEvidence constructors:

  • ordinary, with a proof: any expression; it keeps the value facts and the stable links, and no cell fact;
  • pure, with a proof of a pure term: keeps every fact, and states the result's value where the term is a slot or a literal;
  • reading, with a proof of a term built by field and element reads over variables and values: keeps every fact;
  • created, with a proof: graph code creation;
  • typedRead, with slot and proof: a nonempty expansion of plain or callable bags whose first invariant operand each has the field read, or plain records stating it as a readonly view other than length, at any type; empty expansions and non-bag alternatives are refused; its stored read links retain the receiver descriptor;
  • observedRead, with slot and a value set contents: a read of a location a cell fact states;
  • slicedRead, with tag, answer, slot, proof and sub: every value of one of the location's facts answers the tag so, or reads a prototype for it (ValueSet.answers), and sub proves that the ordinary read contract's slice by that answer fits the requested type, or the slice is Array.isArray's, whose array the requested type holds;
  • knownValue, with slot and a value set contents: a slot whose value facts state its contents;
  • linkedRead, with slot, value and sub: a read of the slot's field where a read link says the field holds the value of slot value, at that value's type, below the claim by sub (linked reads);
  • allocated, with a proof, for either descriptor: it requires make code (var slot) and checks the entire term's scope and creation proof; the code descriptor is part of the requested term, so changing it invalidates the evidence;
  • written, with receiver, value, contents and proof: the written value's value set, or null where it is not a known primitive;
  • boundedWrite, with receiver, index, value and sub: a write into the spine of the array in receiver at an index bounded by its length, with sub taking the value's type to the element type;
  • boundedRead, with receiver, index and sub: a read of the spine of the non-sparse array in receiver at an index bounded strictly below its length, with sub taking the element type to the claimed type.

Promise facts

implies lists {test, target, type}: where the Boolean in slot test is true, slot target holds a type; incoming edges must establish them. yields lists {conditional, target, type, evidence, onFalse}: what the node's result promises of slot target, where it is true (conditional), where it is false (onFalse) or wherever the expression returns, with the subtype evidence a tag test's slice needs. arguments lists the entry slots holding the promised input. At a return, promise is null or [slot, proof]: one of those slots and a subtype proof that its type, refined by the yields, is within the promise.

Equations and tree labels

A type can also be read from recursive equations (RECURSIVE-EQUATIONS), whose labels are trees over the equations' heads. The source path checks every request over them.

Source path. The pass reads no equations from the wire. Lean lowers the declarations and the claims to heads, grows them while it elaborates every unit of the file, and validates them with Equations.ofRaw once elaboration is done (EquationStore.freeze). Each request is then checked over the equations' Equations.graph. A tree is decoded through the validator (Label.ofTree?), and no checked request holds a name placeholder.

Tree spelling. Each tree form has exactly one spelling (Tree.toJson, Tree.fromJson in Types/EquationJson.lean):

Tree Spelling
nullary application of head h h
application with arguments {"app": h, "args": [[…], …]}, args non-empty
owned parameter {"bound": h, "args": [[…], …], "slot": j}, args left out when empty
meet {"meet": [L, …]}: flat, at least two parts, canonical order
template placeholder (bodies only) {"arg": i}, {"local": j}
family variable (inside its entry only) {"var": k, "owner": o, "kind": "value" | "arguments" | "packed"}

Decoding refuses an unknown or missing field and a second spelling of one tree, such as {"app": h, "args": []} for h. Heads become equations only through the validator. It checks scope, arity and lexicality, constructor-headed templates binding exactly their locals, meet normal form, and a kind per parameter. A refusal names the head and the position (Equations.ofRaw, Types/EquationValidator.lean). Variances are not on the wire: the checker computes them from the equations when a check compares two applications of one head (Equations.variances, RECURSIVE-EQUATIONS §4.3).

Subtype choices. A subtype evidence object has exactly two fields: instantiation, an instance object or null, and members, a list of supporting instance tuples for bound comparisons and prototype members. An instance carries its finite domain, table, instances and free. Each tuple retains the source type, fixed and variadic signatures, and the instance object. The checker selects the rule and discovers the comparison dependencies. A nested bound comparison selects its candidate from these tuples and validates its kinds, images and bounds before using it. Candidate presence is not a proof.

The source path accepts an instance image when either proved image check holds: the finite table check, or the substitution check EquationStore.exactImages, which requires every claimed image to be the structural substitution image (EquationStore.eitherImages). A step's search proposes the substitution images (CertificateProducer.Instantiates); a target signature the claim spells otherwise is related to its image by the instance rule's inclusion premises.

Var. Two applications of one head are related by the checker using the head's validated variance. Each argument premise is discharged by label inclusion or another checked variance instance. Structural coverage also uses these premises and shares recursive dependencies up to binder renaming (compareUsing, RECURSIVE-EQUATIONS §4.2–4.3).

Diagnostics show labels through a projection onto a finite table, bounded by depth, with names for applications (the label projection).

Proved boundary and validation

SourceClaimJson.PassUnit.mode8Accepted_sound (PassUnitRun.lean) proves that a unit --verify-interface-stage 8 prints accepted (Mode8Accepted) is safe (PassUnitSafe): every member's plan crosses the exhaustive conversion to CertifiedPlan (FunctionPlan.certify), and its request is safe (RequestSafe): at every admitted assignment of the parameter rows, for any argument environment satisfying inputs, admissible world and satisfying heap, its graph is safe, and it meets its footprint, fresh result, postcondition, regional bound and stated assertions (its statement). It rests on the graph theorem run_sound_single_pass (TolerantFramesSinglePassSound.lean), which reuses graph safety, including cycles, heap changes and explicit slot maps. The pass is incomplete; a refusal is not a proof of untypability.

TypeScript wire decoders

The TypeScript front end mirrors the Lean wire datatypes with strict JSON decoders checked by tools/tsconfig.json:

  • tools/type-graph.mts declares Clause, Arrow, Row, and TypeGraph against PositiveNormalization.Clause and RequestJson.lean (decodeGraph validates every constructor, field, and label reference).
  • tools/calculus.mts declares Term, CallCode, and Tag against Semantics/Calculus/Calculus.lean (decodeTerm, decodeTag, showTerm, showTag), keeping native slot indices beside source-map context tables.
  • tools/control-flow.mts declares Target, Continuation, and ProgramNode against Programs/ControlFlow.lean (decodeNode).
  • tools/diagnostic.mts and tools/diagnostic-view.mts decode and render failure records (OBLIGATION-DIAGNOSTICS.md).