eyemind

DOI npm

A dependency-free Logic Script (LS) reasoner with forward and backward reasoning, checkable proofs, and support for RDF 1.2, Notation3 (N3), SPARQL 1.2 queries, SPARQL 1.2 RL (SRL), SHACL 1.2, Logical English (LE) and Logisch Nederlands (LN).

LS is a rule language with JavaScript syntax. eyemind draws conclusions from facts, rules and queries, and every conclusion can come with a proof that a separate checker verifies against your program. It runs as a command-line program, a JavaScript library and a browser application.

Contents

Why eyemind?

Quill asks why the assessment changed. Mind points to the second study. In March it reports an unclear result. In April a corrected report says it found cooling, so both studies now support the conclusion.

A thermometer correction changes the answer. Can you show exactly why? eyemind can give you a proof you can check for each review, using the reports available at the time and the rules used to assess them. You can reopen an old decision, see what supported it, and test which changes to the evidence or rules would lead to a different answer. Try the fictional research example.

Logic Script (LS) is the assembler level for rule languages. N3, SRL, SPARQL queries, Logical English and the OWL 2 RL, SKOS, QUDT, SHACL and ODRL profiles of RDF 1.2 keep their own syntax and meaning, and compile to ordinary LS programs that one engine runs and one checker verifies. A new language gets reasoning and checkable proofs as soon as it compiles to LS.

Install and run

eyemind needs Node.js 18 or later and nothing else. Install the command with npm install --global eyemind, or run node bin/eyemind.js from a checkout:

eyemind examples/socrates.js

prints

// Answers: each instance of a query() that holds.
type('socrates', 'mortal')
type('socrates', 'human')

Ask for the explanation, and check it:

eyemind --proof examples/socrates.js > /tmp/socrates-proof.js
eyemind --check-proof /tmp/socrates-proof.js examples/socrates.js

The report ends with verdict('checked'). eyemind -c examples/socrates.js does both in one command.

Your first program

Logic Script sources use the .js extension. Save this LS program as /tmp/family.js, or paste it into the playground:

fact(parent('alice', 'bob'))
fact(parent('bob', 'carol'))

implies(parent(X, Y), ancestor(X, Y))
implies([ancestor(X, Y), parent(Y, Z)], ancestor(X, Z))

implied_by(related(X, Y), ancestor(X, Y))
implied_by(related(X, Y), ancestor(Y, X))

query(related('alice', 'carol'))

eyemind /tmp/family.js prints related('alice', 'carol'). The implies rules run forward, adding conclusions until nothing new follows; the implied_by rules run backward, only when a goal asks for them. Without a query, a run prints the facts it derived; --goal asks a question from outside:

eyemind --goal "ancestor('alice', Who)" /tmp/family.js

Now add fact(parent('carol', 'dave')), or remove a rule, and watch which answers appear or disappear.

Writing programs

Call Meaning
fact(...Heads) Each head holds.
implies(Premise, Conclusion) A forward rule: whenever Premise holds, conclude Conclusion.
implied_by(Conclusion, Premise) A backward rule: Conclusion holds when Premise does, decided when a goal asks.
restricted(Premise, Conclusion) A forward rule whose new values are made only where no known ones satisfy Conclusion.
query(...Body) Publish every instance of Body that holds.
contradiction(...Body) Stop with exit code 65 when Body holds: an integrity constraint.
facts_from(path), facts_from({text}) State every expression of a document as a fact, without running it.

An array is a conjunction: implies([p(X), q(X)], [r(X), s(X)]). Disjunction is or(A, B), negation is not(G), and collection is findall(T, G, L), or findall_sorted(T, G, L) for the same list in the standard order of terms, alongside call and once.

Text is atoms: atom_chars, atom_concat and atom_length take them apart, atom_lower and atom_upper change their case, regex_match(P, T), regex_find(P, T, Groups) and regex_replace(P, T, R, U) search them with ECMAScript regular expressions, digest('sha256', A, Hex) hashes them, and term_text(T, A) writes a ground term as its canonical text.

Terms and names

for (let level = 1; level <= 10; level++) {
  implied_by(type(X, `n${level}`), type(X, `n${level - 1}`))
}

Deriving rules

A rule’s conclusion may contain rules, written with the same calls:

fact(enabled('demo'), p('a'), q('a'))
implies(enabled(Name), [
  implies([p(X), q(X)], [r(Name, X), s(Name, X)]),
  implied_by([known(Name, X), available(Name, X)], r(Name, X)),
])
query([known('demo', X), available('demo', X)])

This reports and(known('demo', 'a'), available('demo', 'a')). Name is captured from the generating rule; X, mentioned only inside the templates, is fresh each time a derived rule is applied. Every potential derived rule takes part in stratification before reasoning starts, and a proof cites the generator’s premises directly. See the derived rule deck and SPEC §6.2.

Inspecting rules

In a premise, the same calls match the program’s own rules as data:

fact(a('b'))
implies(a(X), c(X))
implies(implies(X, Y), test(X, Y))
query(test(X, Y))

The answer is test(a(A), c(A)), with the shared variable preserved. Inspection sees ordinary source rules only, not facts, queries, generators or itself, and its proof step names the source rule it matched. See the rule inspection deck and SPEC §6.3.

Other formats

Every other input compiles to an ordinary LS program, so its conclusions get the same checked proofs, and --program prints that program as standalone LS. The file extension selects the format; proofs and check reports are always .js.

Logical English

A .le file is Logical English (LE), the controlled natural language of Robert Kowalski and his colleagues for legal and business rules. eyemind reads the core that the original implementation and Logical English 2 share and compiles it to LS, as the LE specification describes. A document declares its sentence patterns, states a knowledge base of facts and rules, and asks queries, optionally in scenarios:

the templates are:
    *a thing* is human,
    *a thing* is mortal.

the knowledge base socrates includes:

a person is mortal
    if the person is human.

Socrates is human.

query mortal is:
    which thing is mortal.

eyemind examples/socrates-le.le prints the answers as sentences:

% query mortal
Socrates is mortal.

Templates and variables. A template such as *a person* is born in *a place* on *a date* is a relation whose name joins its words (is_born_in_on); a sentence matches the template with the most words. In a sentence, a person (or an, some, each, which) introduces a variable and the person refers back to it; a definite phrase that refers to nothing, such as the UK, is a name. a person X names the variable X, and a capital letter with optional digits is a variable on its own. Numbers, dates (2021-10-09), quoted text and lists ([a, b]) are values. % starts a comment.

Conditions. A rule is conclusion if conditions. Conditions join with and and or; a deeper indentation binds tighter, and lines at one indentation read from the top. it is not the case that, for all cases in which ... it is the case that ... and the aggregates R is the sum of each X such that ... (also count, average, min, max, list) take the more deeply indented lines below them. Arithmetic uses =, <, >=, +, *, / and the like, and built-in templates compare dates (is after, is before or equal to), count days (is N days after) and take list members (is in).

Meaning. Rules are backward LS rules, as in LE’s Prolog target: aggregates count every solution they find, and a negation whose variable no condition has bound succeeds when no instance holds. When a document has scenarios, every relation takes the scenario as its first argument, so one program and one proof answer every query in every scenario. A scenario can state the answers it expects, q expects answers ["..."].; the output then notes any answer set that differs. Proofs and check reports are .js and check the compiled LS; that the program reads the English as intended is a matter of the compiler. --explain writes each answer with the derivation its checked proof records, in English: the answer, then because and the conditions it rests on, each explained in turn below it. Several .le files form one document, without RDF logic switches.

RDF data. LE and LN runs also take RDF data as an eyemind extension. the prefixes are: declares prefixes, and the RDF properties are: binds templates to RDF properties. Each triple of a property states a sentence of its template with the subject first and the object second.

the prefixes are:
    lib is https://example.org/library#.

the RDF properties are:
    *a loan* is due on *a date* is lib:dueOn.

Use a third place to read triples from named graphs and keep the graph name. An LE or LN run can also read a quoted graph from a .n3 data file and test which triples it contains. Named graphs in LE · Benoemde grafen in LN · Quoted report in LE · Geciteerd rapport in LN

A prefixed name such as lib:loan1 is an IRI, an xsd:date an LE date and a string its text, and answers write IRIs as prefixed names. With --stream-messages, the rules run over each RDF Message of a log, such as a Jelly stream, with the other RDF inputs as background, and each message’s answers follow % message N. See the library loans and badge requests decks, and RDF data in the LE specification.

Of Logical English 2, eyemind also reads constants, functions, included files and web addresses, Prolog resources and embedded Prolog goals with LE2’s system predicates, rule labels, numbered and grouped conditions, only if rules, the template additions synonym and opposite, provenance with source-scoped proof, abduction with negation and integrity constraints, and flip queries. LPS, s(CASP), decision tables and services are reported as unsupported. Every npm test scores the Logical English 2 examples that state their expected answers, as coverage: a wrong answer fails the run, a file that uses an unsupported feature is counted as not passed.

LE formulas also accept Logic Script’s named arithmetic functions, including atan2(Y, X), log(X, B), and gcd(A, B, C). Arithmetic in the LE specification

For more examples, try British citizenship, GDPR breach notification, international data transfers, temporal policy conflicts, evolving research evidence, sliding-window message repair, ontology competency questions, exoplanet validation, the right to erasure, withdrawing from an online purchase, inheritance without a will, library fines, an election tally, a three-out-of-five checklist, ABO blood groups, molar masses, field nitrogen balance, beam bending, a critical path, a Gray code counter, Boolean minimization, Markov-chain steps, Euclid’s algorithm, Euclid’s algorithm in the complex plane, complex numbers, the Pythagorean theorem, Heron’s formula, the fundamental theorem of algebra, the fundamental theorem of arithmetic, shortest paths, an Eulerian circuit, the diamond property, dining philosophers or river-crossing plans.

Logisch Nederlands

Schrijf sjablonen, feiten, regels, scenario’s en vragen in een .ln-bestand. Logisch Nederlands gebruikt dezelfde compiler en bewijscontrole als Logical English. Dit programma leidt af dat Socrates sterfelijk is.

de sjablonen zijn:
    *een persoon* is mens,
    *een persoon* is sterfelijk.

de kennisbank socrates bevat:
    een persoon is sterfelijk als de persoon is mens.
    Socrates is mens.

vraag sterfelijk is:
    welke persoon is sterfelijk.

De opdrachtregel en de playground geven antwoorden in het Nederlands. Met --explain krijg je de afleiding in het Nederlands. Bewijzen en controlerapporten gebruiken dezelfde JavaScript-vorm als bij LE.

De demo Mobiliteitsdossiers vraagt scores op en beoordeelt fictieve dossiers voor een voorbehouden parkeerplaats en een EU-handicaptenkaart. Beide voorzieningen gebruiken dezelfde regels met eigen criteria. De drempels zijn verzonnen voor de demo. Het boek volgt één dossier van score tot gecontroleerd bewijs. De referentie beschrijft de Nederlandse taalvormen, ook voor bronnen (volgens), aannames en minimale wijzigingen. De kunst van Logisch Nederlands · Taalreferentie

De demo Bezwaartermijn kiest per peildatum de regelwerkversie en laat in de uitleg zien waarom het bijzondere artikel voor een verblijfsbesluit vier weken geeft. De voorbeelden Bijstand in Diemen en Erfgrens in Amsterdam tonen hoe een plaatselijke regel een landelijke regel aanvult. Onbekende feiten laat zien wat een open veld voor de uitkomst betekent. Proeftegemoetkoming en Zorgtoeslag 2025 laten de berekening van bedragen controleren.

In Deelvoorwaarden met bewijs volgt dezelfde leeftijds- of inkomensvoorwaarde uit gegevens of uit een bevestiging van een externe verifier. De demo gebruikt fictieve bevestigingen en controleert welke bij de persoon, aanvraag en toets passen.

RDF 1.2

.ttl, .trig, .nt, .nq, .rdf (RDF/XML), .jsonld (JSON-LD) and .jelly (Jelly) files are read with the formats’ own grammars, as data: their quads become rdf(Subject, Predicate, Object, Graph) facts. --to turtle, trig, n-triples, n-quads, rdf-xml, json-ld or jelly writes the conclusions back; Turtle, N-Triples and RDF/XML refuse named graphs, which they cannot hold, and JSON-LD refuses triple terms. Jelly is a binary format of Protocol Buffers, read and written without a library: eyemind reads Jelly-RDF 1.2 (the column layout) and Jelly-RDF 1.0 and 1.1 (the row layout), and writes Jelly-RDF 1.2. JSON-LD follows the JSON-LD 1.2 draft of the Processing Algorithms and API, in the processing mode json-ld-1.2, or json-ld-1.1 or json-ld-1.0 through parseRdf of eyemind/rdf, which also takes expandContext, rdfDirection and produceGeneralizedRdf; a JSON-LD context that is not in the document is read from its file, or fetched as Notation3 documents are. JSON-LD keeps a base direction only with its rdfDirection option, as the specification has it. writeRdf writes expanded JSON-LD, with the useNativeTypes, useRdfType and rdfDirection options.

RDF 1.2 eyemind term
IRI iri('https://example.org/bob')
Blank node bnode(Scope, Label), the scope naming the file
xsd:integer with a canonical lexical form an integer, 42, exact at any size
Other literal literal('1.50', datatype(Iri)), or literal('chat', lang('fr')), with an optional direction
Triple term triple(S, P, O)
Default graph, named graph 'default_graph', iri(Name)

All 1262 W3C RDF 1.1 and 1.2 tests pass, RDF/XML included, all 522 toRdf and fromRdf tests of the W3C JSON-LD API, and all 367 Jelly-RDF conformance tests. The Jelly codec benchmark measures retained reads and writes alongside rdfjs-jelly.

Notation3

A .n3 file compiles to LS with the N3 built-ins it uses written as LS rules, and its conclusions are written as N3: => becomes implies, <= implied_by, { ... } => false a contradiction, and scoped negation and collection not and findall. Quoted formulas are graph terms, as in D. Arndt and P.-A. Champin, “Notation3: Graph Terms for RDF”; a rule with existentials in its conclusion is restricted, making Skolem witnesses only where none is known. RDF named graphs join N3 as graph:content formulas, and log:semantics documents are read before compiling. All 1163 cases of the Notation3 test suite pass.

eyemind examples/family-n3.n3                            # the derived triples as N3
eyemind -c examples/family-n3.n3                         # with a checked proof

RDF Messages

eyemind reads RDF Message logs in Turtle, TriG, N-Triples, N-Quads, RDF/XML, where an rdfm:MessageLog holds one rdf:RDF per message, NDJSON-LD (.ndjson), a JSON object per line, and Jelly streams of RDF Messages; writeRdfMessages of eyemind/messages writes them. By default rules see the whole log replayed as ordered envelopes in the eymsg: vocabulary, with proofs; --stream-messages instead runs the rules once per message, reading files, standard input or HTTP(S) incrementally. See the message-boundaries and message-alerts decks. All 35 RDF Messages tests pass, and every npm test runs them.

Mind applies the same rule to three separate sensor messages, reading 21, 29 and 22 degrees. The alarm rings only for the middle message, which exceeds 25 degrees.

With an RDF logic profile, --stream-messages treats the other inputs as a background graph and writes, for each message, the triples it adds to what the background alone concludes. The background is closed once. Each shape of message, its properties and whether its values are IRIs or literals of a datatype, gets the rule instances that can use one of its triples, with background facts unfolded where they fix a property or class; later messages of that shape only add their own facts. The result is the same as running the whole program over the background and the message, and the whole program runs instead when new triples could have any property, as owl:sameAs between individuals makes, or when a negation could retract a background conclusion. With --qudt, the compiler reads the units and metadata of each message: a message whose units need catalog facts the background lacks runs the whole program, compiled with its own units, and the others, such as those of QUDT’s builtin units, use the specialized rules. --program prints the specialized program of each new shape, and --stats says whether each message used one. --to writes each message’s triples as turtle, trig, n-triples, n-quads or jelly; Jelly messages, one per message, form one Jelly stream. Streamed messages have no proofs.

An output contract prunes the specialized rules to those that can contribute to a triple it asks for, following premises back to the rules concluding them. A value counts only where a reader uses it: a triple that owl:sameAs copies to an equal object serves no rule that reads only its subject. See the observations deck.

SHACL shapes state both contracts, which are trusted and not validated, and plan the rules as rdfjs-inference-engine does, by property and class. A rule whose schema premise, such as rdfs:domain or owl:FunctionalProperty, the background lacks is left out. --shacl-in FILE reads the input shapes: each property shape is a pattern of message triples, its path the property and its value what sh:datatype, sh:nodeKind, sh:class, sh:hasValue or sh:in allows, in the default graph; other paths allow triples of each of their predicates. Only rules that can read a property or class of the background, the messages or a kept rule stay, and they are specialized to these patterns when the background loads; a message whose triples are all instances of them uses that program, and one with other triples gets rules of its own shape. When every input shape is closed, a message triple whose property no shape names or ignores is dropped first; --stats reports conforms and dropped per message. --shacl-out FILE reads output shapes as an output contract. Each property shape asks for triples of its path with the values it allows. Planning keeps rules that conclude those triples and rules they depend on. A variable property or class in a rule takes the values its schema premise has in the background, as partial evaluation gives them. Planned rules derive what the shapes lead to, not every OWL 2 RL consequence: equality that the output does not ask for is not derived. See the shape-planning deck, and the readings deck for SKOS and QUDT over messages in Jelly.

eyemind --owl2rl --stream-messages ontology.ttl messages.trig               # each message's new triples
eyemind --owl2rl --stream-messages ontology.ttl contract.js messages.trig   # only those the contract asks for
eyemind --owl2rl --stream-messages --shacl-in in.ttl --shacl-out out.ttl ontology.ttl messages.trig

SPARQL 1.2 RL

A .srl file is a SPARQL 1.2 RL rule set over the RDF data given with it; the result is the inference graph, as Turtle (--all adds the base graph). Rules become implies, NOT becomes not, GROUP becomes findall_sorted, and a SPARQL error is a goal that fails. Local variable names in NOT and GROUP cannot be bound again elsewhere in the same rule. Decimals are exact (0.1 + 0.2 is 0.3) and floats are binary64. WHERE DATA and NOT DATA match only the supplied base graph. eyemind also accepts GROUND in those positions for W3C test suite compatibility. NOW() and UUID() use a clock and seed captured at compilation, which a saved proof retains. All 367 cached W3C SPARQL 1.2 RL tests pass.

eyemind -c rules.srl facts.ttl                           # the inference graph, with a checked proof

SPARQL 1.2 queries

A .rq file is a SPARQL 1.2 query over the dataset of the RDF data given with it: the default graph, and the named graphs of TriG or N-Quads inputs. eyemind compiles it to LS over rdf(S, P, O, G) facts. SELECT and ASK write SPARQL JSON by default and accept --to sparql-xml. SELECT also accepts --to csv and --to tsv. CONSTRUCT and DESCRIBE write Turtle by default and accept other RDF formats. SELECT rows are one findall_sorted over the pattern, so SPARQL’s duplicate solutions stay; DISTINCT removes them and REDUCED keeps them. An unbound variable holds 'undef'. OPTIONAL, UNION, MINUS, GRAPH, VALUES, BIND, FILTER with EXISTS and NOT EXISTS, subqueries, triple terms and SELECT expressions follow the SPARQL algebra; a nested group is evaluated on its own and joined, and a FILTER applies to its whole group. Property paths take sequences, inverses, alternatives, negated property sets and ?, * and +, whose distinct pairs forward closure rules give, cycles included. GROUP BY, HAVING and the aggregates COUNT, SUM, AVG, MIN, MAX, SAMPLE and GROUP_CONCAT, with DISTINCT, summarize groups; ORDER BY sorts rows in SPARQL’s order of terms, and OFFSET and LIMIT slice them. Expressions use the function library of SPARQL 1.2 RL, with MD5 and the SHA functions. REGEX and REPLACE accept i, s, m, x and q when the pattern and flags are constant. Proofs check as for any program. NOW(), UUID() and RAND() use the clock and seed a saved proof keeps.

FROM and FROM NAMED name the dataset: a graph is the input’s named graph of that name, or else the document the IRI names, read as a file for a file: IRI and over HTTP(S) otherwise. DESCRIBE writes the triples of the default graph about each resource it names or binds, and those about the blank nodes they reach. With RDF logic profiles, such as --owl2rl or --skos, the query runs on their working graph, entailments included, in one program and one proof. Use the RDF inputs to supply the dataset when a profile is active. SERVICE is not supported. Every npm test scores the cached W3C SPARQL 1.0, 1.1 and 1.2 query manifests and fails on incorrect results. All 1,085 cases in the current cache pass. EARL report and suite scope

eyemind query.rq data.ttl                                # SPARQL JSON results
eyemind --to tsv query.rq data.trig                      # TSV results over a dataset
eyemind -c query.rq data.ttl                             # the answer, with a checked proof
eyemind --owl2rl query.rq ontology.ttl data.ttl          # the query on the OWL 2 RL entailments

See the staffing, org chart and species decks for SELECT. The public catalog builds RDF with CONSTRUCT. The reviewed temperature and inspection decks show ASK returning true and false. The scheduled airports deck runs SELECT over 112,899 triples from a public OurAirports snapshot.

RDF logic profiles

Four switches add standalone LS rules to RDF inputs; vocabulary alone never enables one. They combine, inference closes before validation, and the output is Turtle with the new triples and reports.

A .js input is an output contract: a Logic Script program whose statements are query(rdf(S, P, O)) or query(rdf(S, P, O, G)). The output then holds only the new triples matching one of them, and a proof answers those queries. --shacl-out FILE gives the same contract as SHACL output shapes.

const sosa = (name) => iri('http://www.w3.org/ns/sosa/' + name);
query(rdf(O, sosa('madeBySensor'), S));
query(rdf(O, iri('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), sosa('Observation')));
eyemind --qudt --shacl examples/measurement-shacl.ttl
eyemind --owl2rl -c examples/family-owl2rl.ttl

ODRL snapshots

--odrl evaluates a snapshot of ODRL policies, candidate requests and their state of the world, selected by an eval:Evaluation resource: one Turtle file, or the union of several RDF inputs. The report gives each request’s decision (Allowed, Prohibited, NotApplicable or Undetermined) and the permission/prohibition conflicts. Each rule has one assignee, action and target. The snapshot compares state properties with scalar or DPV category constraints and combines constraints with odrl:and, odrl:or or odrl:xone. Permissions can require duties, with fulfillment evidence attached to each request.

With --stream-messages, each RDF Message of a log, such as a Jelly stream, joins the other inputs as a snapshot of its own and gets its own report: the policies can be a background file and each message a request with its evaluation and state of the world. See the research requests deck.

--odrl combines with --owl2rl, --skos, --qudt and --shacl, though then not with --stream-messages, --shacl-in or --shacl-out. The snapshot then reads the given triples, what the profiles entail about each request’s state, such as an observation a property chain derives, and entailed SKOS links between categories, such as a skos:broadMatch to DPV. Other entailments, such as an rdfs:Resource type for every node, stay out of the snapshot, whose validation would reject them. The output is the ODRL report with the profiles’ own reports, such as a SHACL validation report. Handicap-card example · Research snapshot · Research access with OWL 2 RL and SKOS · Research portal with OWL 2 RL · Package holiday with SHACL

How eyemind reasons

The statement chooses the direction:

Strategy Stated with How it works
Forward implies, restricted, query, contradiction From the facts, round after round, until a round adds nothing new.
Backward implied_by, fact When a goal asks: depth-first, left to right, in the order the clauses are written.

Forward rules suit closures and classifications: implies([path(X, Y), edge(Y, Z)], path(X, Z)) terminates on a cyclic graph. A variable only a forward rule’s conclusion mentions gets a fresh value, a Skolem term, for each firing. restricted makes one only where none is known: restricted(human(X), [father(X, F), man(F)]) gives no new father to a human whose known father is a man. Its other rules run first in each stratum, a restricted rule whose conclusion can satisfy another’s runs before it, a run whose new value later facts make unneeded stops with an error, and its proof shows each new value is needed, as the restricted chase of N. Küchenmeister, A. Ivliev, D. Arndt and M. Krötzsch, “Stratified Negation in RDF Rules”, requires. Which firings it makes can depend on the order of rule applications, so call fidelity stays an obligation. Backward rules suit computations driven by their inputs, such as arithmetic recursion and list processing. Backward chaining keeps no table of answers, so a backward rule that calls itself with the same goal runs until a bound stops it; such recursion belongs in a forward rule.

The two work together: a forward rule’s premise can call a backward definition, and a backward goal sees the facts forward rules derived. Forward rules run stratum by stratum, so a negation or collection waits until everything it inspects is final. A rule with a variable in every position, such as implies([rdf(P, 'spo', Q), rdf(X, P, Y)], rdf(X, Q, Y)), reaches every negation of its relation, and a cycle through it has no strata. Such a program is still accepted when it is chain-stratified, as Küchenmeister, Ivliev, Arndt and Krötzsch define it: no chain of rule applications from a rule with a negation can make one of its negated goals true without also satisfying a contradiction. Its rules then run in ranks, the Datalog rules first, and a rule fires only while no lower-ranked rule has a firing left (SPEC §6.4). --max-depth, --max-iterations and --max-inferences bound a run, and exceeding one is an error, never a partial answer. SPEC §8 defines the details.

Proofs, and what checking one means

A proof holds the claims, the certificate that answers the program’s questions, and the recorded firings behind derived facts as step(...) records. Every input writes the same JavaScript proof: an N3 document or SRL rule set is compiled to an LS program, and its proof cites that program’s clauses, with triples as rdf(S, P, O) (an SRL inference as inf(S, P, O)) over iri(...) and literal(...) terms:

eyemind --proof examples/socrates-n3.n3 > /tmp/socrates-proof.js
eyemind --check-proof /tmp/socrates-proof.js examples/socrates-n3.n3
eyemind --proof examples/socrates-srl.srl > /tmp/socrates-proof.js
eyemind --check-proof /tmp/socrates-proof.js examples/socrates-srl.srl

Check reports are JavaScript term documents too, or JSON with --json.

The proof of examples/socrates.js shows its parts:

// Answers: each instance of a query() that holds.
type('socrates', 'mortal')
type('socrates', 'human')

// Steps: each derived fact and what it rests on: the clause or control that
// justifies it, the bindings and the goals it uses.
step(type('socrates', 'mortal'), clause(3), {S: 'socrates', A: 'human', B: 'mortal'}, [type('socrates', 'human'), subclass_of('human', 'mortal')])
step(type('socrates', 'human'), clause(1), {}, [])

// Certificate: the derived facts and every answer of each call the questions make.
derived(type(A, B), [type('socrates', 'mortal')])
called(type(A, B), [type('socrates', 'mortal'), type('socrates', 'human')])

Checking is one procedure. The checker answers each original question by searching it against the program, one level at a time, with every inner call answered from its call table, and checks each table the same way, so a wrong table shows up as a disagreement. Each listing must be closed under the forward rules, and each listed fact must replay its recorded firing: the checker re-runs the rule from no bindings, with primitives computed and negations, collections and first answers taken from the tables at the bindings they had when they ran, and each witness bound to the Skolem term of its firing. The claims must then be exactly the answers: a claim the question does not return fails, and so does an answer the proof leaves out. A step, table or listing the check does not use fails it too, so nothing in a proof goes unchecked.

The checker follows the certificate: it never calls the reasoner, so missing evidence fails rather than being quietly re-derived. The source is the authority: the proof cites clauses by number, read from the program. Proofs are read as data, so checking someone else’s proof runs none of their code, and every proof eyemind generates is checked before it is returned. The report is a document too:

// Checked answers: these follow from the input program and are every answer of its questions.
type('socrates', 'mortal')
type('socrates', 'human')

// Proof check (SPEC 11.2-11.6):
// Questions: every claim is an answer, and every required answer is claimed.
// Call tables: every consulted table matches its one-level expansion against the program.
// Derived listings: every consulted listing is closed under the forward rules.
// Replay: every required firing replays from no bindings; primitives, controls and
// Skolem witnesses are checked at the bindings where they run.
// Evidence: every recorded step, call table and listing is used by the check.

verdict('checked')

A checked verdict establishes that every claim follows from the program and every required answer of the original questions is claimed. When the run reports only derived facts, source facts and backward-only answers are not required conclusions. A failed check lists failure(Detail) facts, ends with verdict(failed(N)) and exits with code 2. A halted run’s proof establishes that its claims follow, without establishing answer completeness. To check answers to --goal questions, pass the same goals when checking. SPEC §11 defines the check.

Mind reports that Socrates is mortal. Checker asks for the other answer. The program also requires the answer that Socrates is human.

The report’s comments explain which checks succeeded, with references to SPEC Sections 11.2–11.6. They distinguish complete answers from a halted proof’s replayed claims. A failed report keeps its claims unverified and lists the failures. These explanations are JavaScript comments: reading the report with facts_from still gives just its claims, failures and verdict.

Some results cannot be certified by this format, and --proof then reports an error while a plain run still gives the answers:

JSON check reports

With --json, checking modes write a JSON report instead of a term document: valid (boolean), claims and steps (the numbers read), answers (the claims’ canonical texts, including unverified claims when valid is false), halted (whether the claims contain 'false') and failures (a list of {detail, subject?}, where subject is the canonical text of the term concerned). Its variables keep the names the document gives them.

Why negation and collection are safe

A negation not(G) concludes from what is absent and a collection findall(T, G, L) from everything present, so both are only right once nothing more can be derived:

Checking the translation

A checked proof shows that conclusions follow from the program, not that the program says what the law or the textbook says. --unused points at the clauses that make no difference, where a translation is most likely decorative, incomplete or untested:

fact(p('a'))
fact(q('b'))
implied_by(s(X), q(X))
fact(z('c'))
implies([p('a'), not(s('a'))], ok)
$ eyemind --unused program.js
unused(line(2), fact(q('b')))
unused(line(3), implied_by(s(X), q(X)))
unused(line(4), fact(z('c')))

A clause is listed when no conclusion’s proof uses it; a clause only a negation consults, as not(s('a')) consults q('b'), is listed only if leaving it out changes no conclusion.

Examples and the playground

The examples range from classics (Ackermann, the zebra puzzle) to planning, policy reasoning, mathematics, RDF 1.2 data and a hundred-thousand-level taxonomy. Each has its conclusions saved in examples/output/, all but the three streamed examples their proof and check report in examples/proof/ and examples/check/, and each a card deck for a wide audience. Change a fact, run it, and compare with the saved output.

The playground runs eyemind in a worker in your browser, so Stop ends a long run. Choose an example, edit it, pick an output (conclusions, proof, checked answers, check of a saved proof, unused clauses, LE or LN explanations, or independent RDF Messages) and press Run or Ctrl+Enter. A line an error names is marked red, the options panel shows the equivalent command, and Share link copies a link with the program and options.

Command line

eyemind [OPTION ...] [FILE ...]
Option Meaning
(none) Load the files, or standard input, as one program and print its conclusions. .js files and standard input are Logic Script, .ttl, .trig, .nt, .nq, .rdf (RDF/XML), .jsonld (JSON-LD), .ndjson (NDJSON-LD message log) and .jelly (Jelly) files RDF data, .n3 Notation3, .srl a SPARQL 1.2 RL rule set, .rq a SPARQL 1.2 query, .le Logical English and .ln Logisch Nederlands.
-p, --proof Print the proof instead.
-c, --prove-and-check Generate a proof, check it, and print the checked answers with the report.
--check-proof FILE Check a saved proof (- for standard input) against the program.
--json With a checking mode, print the report as JSON.
--goal GOAL Ask GOAL after forward reasoning; may be repeated.
--unused List the clauses that make no difference to the conclusions.
--explain Explain each LE or LN answer in its own language, from its checked proof.
--stream-messages Read an RDF Message Log and run the rules independently per message; Node reads files, stdin and HTTP(S) incrementally. With an RDF logic profile, the other inputs are a background closed once and the rules are specialized per message shape. LE, LN and --odrl read each message’s triples with the other inputs.
--shacl-in FILE With --stream-messages and an RDF logic profile, trust the SHACL shapes in FILE to describe the messages: the rules are planned and specialized for them before the first message, and a closed shape drops triples of other properties.
--shacl-out FILE With an RDF logic profile, plan only the rules that conclude triples the SHACL shapes in FILE describe, or what those rules read, and write only those triples.
--stats Print reasoning statistics as JSON to standard error.
--max-depth N, --max-iterations N, --max-inferences N Bound backward depth (1000000), forward rounds per stratum (1000) and goals started (1000000). Compiled N3, SRL, SPARQL query, ODRL and RDF profile programs use 1000000, 100000 and 1000000000.
--to FORMAT Write conclusions as turtle, trig, n-triples, n-quads, rdf-xml, json-ld, jelly, n3 (N3 only), le (LE only), ln (LN only) or eyemind. SELECT and ASK default to sparql-json and also accept sparql-xml. SELECT also accepts csv and tsv. SRL, ODRL, RDF profiles, CONSTRUCT and DESCRIBE default to Turtle. LE, LN and N3 default to their own formats. Other runs and --goal default to eyemind.
--all With RDF or N3 output, write the given data too.
--program Print the program the inputs compile to.
--odrl Add the ODRL snapshot profile’s validation and evaluation LS to a snapshot: one Turtle input, or the union of the RDF inputs; with --stream-messages, each message and the other inputs. With RDF logic profiles, the snapshot is one input and also reads what they entail about its states, not with --stream-messages, --shacl-in or --shacl-out.
--owl2rl Add the documented OWL 2 RL inference rules, including RDFS, and RDF conflict reports to RDF inputs.
--qudt Normalize supported QUDT/CDT quantities, with source provenance.
--skos Add positive SKOS Core entailments.
--shacl Compile supported SHACL Core shapes to LS and output RDF validation reports.
--base IRI Resolve relative IRIs of the inputs against IRI instead of each file’s location.
-v, --version, -h, --help Print the version or the usage.

--proof, --prove-and-check, --check-proof and --unused are mutually exclusive. --json needs a checking mode. --goal reads each goal as a data document, with an array denoting conjunction. With --check-proof, supply the original goals the proof answers. An option that takes a value requires it immediately afterward; another option, including a short alias such as -v, is reported as a missing value. With --goal, answers default to eyemind terms even for LE, LN, N3, SRL, ODRL and RDF profile inputs; use --to to request another output format.

With --prove-and-check, reasoning bounds and --stats apply to proof generation; an invalid check returns 2, otherwise the run’s halt code is retained. Input with a line starting with step( or called( is recognized as a proof document; when supplied as a program, it produces an error explaining how to check it instead.

--stats writes inferences (goals started), rounds (forward rounds over all strata), and derived (facts added during reasoning). derived excludes source facts, query answers and 'false'. A run that exceeds a reasoning bound writes no conclusions to standard output, including answers found before exhaustion.

Exit code Meaning
0 Success, including a valid proof check.
1 An error, printed to standard error as eyemind: message.
2 An invalid proof check; the report is printed as usual.
65 The run concluded 'false' and halted.

The command line, JSON output, additional input formats, library API and browser interface describe this implementation. They are outside the language and proof specification.

Resource limits

The JavaScript implementation defaults to a depth limit of 1000000, an inference limit of 1000000 and a limit of 1000 forward rounds per stratum. Compiled N3, SRL, ODRL and RDF profile programs use 1000000, 1000000000 and 100000 respectively. Each supplied bound must be a positive integer no greater than 9007199254740991.

Arithmetic also limits integer growth: pow(A, B) with integer B > 0 and abs(A) > 1 raises an error when B times the bit length of A exceeds 2^26. An integer left shift shl(A, B) raises an error when B exceeds 2^26. These limits protect the process from excessively large allocations.

Making a proof’s call tables is bounded per question by the smaller of the run’s inference limit and 500,000 calls plus answers, and by 8,388,608 UTF-16 code units of answer text. Exceeding these bounds makes --proof report an error; it does not change the answers of a plain run.

Unused clauses

A clause is unused when no conclusion’s recorded derivation cites it, unless a negation or collection in the proof could consult it and its omission changes the conclusions or halt code, or causes an error. The clauses a negation or collection could consult are those whose heads have the name and arity of a goal it reaches through the program’s bodies. Running the program without a clause leaves every other clause its number (Section 3.5), so the Skolem terms of the other rules (Section 8.2) do not change.

Unused clauses are reported one per line, in clause order, as unused(line(L), Display), where L is the source line where the statement call begins; facts read by facts_from use that call’s line. Display is as in Section 10.2; with several scripts, clause order tells which script a line belongs to. The listing is the result whether or not the program halts with 'false', and the command exits with code 0 after it.

A clause compiled from a template inherits its generator’s source line.

“Unused” is relative to the recorded derivations, which are the first ones found (Section 8.7). A clause that only offers a second derivation of a conclusion, such as a duplicate rule, is unused, though leaving out the clause that offers the first one would make it used; leaving out several unused clauses together can therefore change the conclusions. A contradiction rule that never fires changes no conclusion and is unused, though it guards the program against data that would make it fire; so are the clauses only its negations or collections could consult, since they are not in the proof.

Troubleshooting

What you see What to do
operators do not apply to terms Write add(X, 1) or gt(X, 1) instead of X + 1 or X > 1, and [g1, g2] for a conjunction.
true is not a term JavaScript decided 1 < 2 itself; write lt(1, 2).
fcat(...) on its own states nothing Wrap it in fact(...) or fix the spelling.
negation requires a goal whose variables are bound Bind the variables before not(...), or use _.
unstratified negation or collection dependency A negation or collection depends on its own conclusion; see why negation and collection are safe.
exceeded max_depth or another bound Usually a left-recursive backward rule; make it forward, or raise the bound.
the called variable p must be bound In goal text a bare name is a variable; write p() or 'p'.
this is a proof document, not a program Check it with --check-proof PROOF PROGRAM.

JavaScript library

import { checkProof, loadText, run } from 'eyemind';

const socrates = loadText(`
fact(human('socrates'))
implies(human(X), mortal(X))
`);
const goals = ['mortal(X)'];
const result = run(socrates, { goals, proof: true });
console.log(result.answers);
console.log(result.bindings);
console.log(checkProof(socrates, result.proof, { goals }).valid);

run() returns conclusions, answers, bindings, inferred, stdout, proof, proofReport, stats and haltCode, and takes goal, goals, proof, maxDepth, maxIterations and maxInferences; exceeding a bound throws an EyemindError. conclusions holds the answer terms; answers, bindings and stdout are rendered when first read. Ground N3 conclusions are written directly from their terms. loadSources([[text, filename], ...], io) loads several sources as one program; pass nodeIO from eyemind/node as io to let facts_from(path) read files. checkProof(program, document, { goals }) checks a proof. checkReport, readTerm, readTerms and write format reports and read and write the canonical text. compileLe([[text, filename], ...], io) returns the compiled LS program and standalone JavaScript text, reading included files with io.readFile when given; writeLe(run(loaded.program), loaded) writes the answers as LE sentences, given the value loaded that compileLe returned, and explainLe(loaded, run(loaded.program, { proof: true }).proof) explains each answer in English, as --explain does, after checking the proof.

Further entry points serve applications built on the formats and profiles:

Import Gives
eyemind/rdf parseRdf(text, { format, base }) and writeRdf(quads, { format, prefixes }), RDF 1.2 to and from eyemind terms
eyemind/messages parseRdfMessages(text), RdfMessageReader and writeRdfMessages(messages), for RDF Message logs
eyemind/formats loadInputs(inputs, io, options) and loadMessageReasoner(inputs, io, options), the command line’s loading of [text, name] inputs with the options of the RDF profiles, such as { qudt: true, shaclIn, shaclOut }
eyemind/cli main(argv, io), the command line itself, with io as in eyemind/node
eyemind/qudt unitConversion(from, to) and quantityKinds(unit), from the QUDT catalog of --qudt
eyemind/shacl shaclRules(quads, shapes), the triples SHACL 1.2 inference rules infer, and shaclOrder(shapes, { context, nodeShape, propertyShape, role }), a SHACL 1.2 UI ordering: 'presentation', 'role' or 'columns'
eyemind/sparql loadSparql(text, { data, base, load }), a SPARQL 1.2 query compiled over RDF quads with its nativeProgram; sparqlResult(loaded.query, run(loaded.nativeProgram)) gives its rows, boolean or triples, and writeSparql(loaded.query, result, { format }) its results

unitConversion takes two QUDT unit IRIs and returns { scale, offset, dimensionVector, sharedQuantityKinds }, where a value in the second unit is the value in the first times scale plus offset, or null when either unit is unknown or the dimensions differ. An empty sharedQuantityKinds marks a conversion between quantity kinds, such as from irradiance to radiance, that a caller may refuse.

What is deliberately absent

Cut, conditional commitment, mutable databases, attributed variables, constraint libraries, tabling, and filesystem or network built-ins. Without cut and a mutable database, a derivation is a function of the program and its input, which is what makes a certificate meaningful. Undefined predicates fail.

Development

eyemind is authored and maintained by Jos De Roo. Codex and Claude Code are development tools used by the author.

npm test                                              # unit, examples, conformance, MobiBench, command line, playground
npm test -- -k skolem                                 # only tests whose line contains "skolem"
EYEMIND_PROPERTY_SCALE=20 npm test -- -k properties   # deeper generated tests
node tools/update-examples.js                         # regenerate example artifacts after an intended change
npm run sync                                          # refresh the cached upstream suites, QUDT catalog and benchmark inputs
node conformance/run.js --command "my-eyemind"        # test a Logic Script implementation
node le-conformance/run.js --command "my-le"          # test a Logical English implementation
npm run bench                                         # the RDF reasoning and Jelly codec benchmarks; see bench/README.md
./release patch "Describe the changes"                # test, tag and publish a release
node tools/submit-reports.js                          # submit the release's EARL reports to the W3C suites

The full suite needs a few GB of memory; on a small machine run it under a cap, such as systemd-run --user --scope -q -p MemoryMax=3G -p MemorySwapMax=0 -- npm test. The playground tests need Chrome (CHROME names it). A full run writes REPORT.md. Full and filtered runs write the W3C EARL reports from the upstream suites cached in Git-ignored .cache/.

The example tests reproduce every saved conclusion and proof, then check the proofs from disk. The deck tests check the documented claims and run commands with extra goals, conversions or redirects. The corpus and CLI tests cover the standard example commands.

The name

eyemind joins eye and mind: facts and rules lead to conclusions whose reasoning can be inspected and checked.

Logic Script (LS) names the language: facts, rules, and queries written in JavaScript syntax. eyemind is the reasoner that runs LS programs and checks their proofs.

MIT licensed; see LICENSE.md.