eyemind 0.5.13 → 0.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ eyemind is a **JavaScript rule language** with forward and backward reasoning an
7
7
 
8
8
  [Playground](https://eyereasoner.github.io/eyemind/playground/) · [Specification](https://eyereasoner.github.io/eyemind/SPEC) · [Conformance](https://eyereasoner.github.io/eyemind/conformance/) · [Examples](https://eyereasoner.github.io/eyemind/examples/)
9
9
 
10
- The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 128 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1356 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
10
+ The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 135 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1369 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
11
11
 
12
12
  ## Contents
13
13
 
@@ -120,6 +120,7 @@ Now add `fact(parent('carol', 'dave'))`, or remove a rule, and watch which answe
120
120
  | `fact(...Heads)` | Each head holds. |
121
121
  | `implies(Premise, Conclusion)` | A forward rule: whenever `Premise` holds, conclude `Conclusion`. |
122
122
  | `implied_by(Conclusion, Premise)` | A backward rule: `Conclusion` holds when `Premise` does, decided when a goal asks. |
123
+ | `restricted(Premise, Conclusion)` | A forward rule whose new values are made only where no known ones satisfy `Conclusion`. |
123
124
  | `query(...Body)` | Publish every instance of `Body` that holds. |
124
125
  | `contradiction(...Body)` | Stop with exit code 65 when `Body` holds: an integrity constraint. |
125
126
  | `facts_from(path)`, `facts_from({text})` | State every expression of a document as a fact, without running it. |
@@ -204,7 +205,44 @@ eyemind --program examples/family.n3 > /tmp/family.js # the compiled program,
204
205
  eyemind -c examples/family.n3 # a proof of it, checked
205
206
  ```
206
207
 
207
- Triples are `rdf(Subject, Predicate, Object)`, with IRIs, blank nodes and literals written as in the RDF table above. N3 integers and decimals become eyemind numbers; float and double literals retain their RDF datatype, including numbers written with an exponent. Decimals use binary64 storage; `math:sum` adds their canonical decimal values before rounding its result. `=>` becomes `implies`, `<=` becomes `implied_by`, `{ ... } => false` becomes `contradiction`, and scoped negation and collection become `not` and `findall`, so an N3 run has a proof that eyemind checks like any other. Derived rules can trigger inference fuses too.
208
+ Triples are `rdf(Subject, Predicate, Object)`, with IRIs, blank nodes and literals written as in the RDF table above. N3 integers and decimals become eyemind numbers; float and double literals retain their RDF datatype, including numbers written with an exponent. Decimals use binary64 storage; `math:sum` adds their canonical decimal values before rounding its result. `=>` becomes `implies`, or `restricted` when the conclusion has blank nodes of its own, `<=` becomes `implied_by`, `{ ... } => false` becomes `contradiction`, and scoped negation and collection become `not` and `findall`, so an N3 run has a proof that eyemind checks like any other. Derived rules can trigger inference fuses too.
209
+
210
+ Quoted formulas are graph terms, read as in D. Arndt and P.-A. Champin,
211
+ ["Notation3: Graph Terms for RDF"](https://arxiv.org/abs/2610.31266).
212
+ `@forAll` and `@forSome` declare IRIs as universal and existential variables
213
+ of the formula they open, before its first statement and with `@forAll`
214
+ first. A declaration reaches the formulas inside it unless one declares the
215
+ same IRI again. A `?x` belongs to the whole document, and a blank node to the
216
+ innermost formula that holds it. So `@forAll :x . :x :p :o .` and
217
+ `?x :says { ?x :is :wise } .` are facts about everything. A document
218
+ existential is one individual, in rules and quoted formulas alike. Within the
219
+ scope of universals it becomes a witness of them, so
220
+ `?x :loves _:y .` gives each individual its own beloved. A rule whose
221
+ conclusion has existentials is restricted: a firing makes Skolem witnesses
222
+ only where no known individuals satisfy the conclusion. A
223
+ conclusion that declares universals of its own becomes backward rules, which
224
+ state it for every individual, and `{ ... } => ?g .` asserts the formula bound
225
+ to `?g`.
226
+
227
+ A graph term is opaque: `owl:sameAs` does not rewrite it. It is closed and
228
+ compared as a set, up to a one-to-one renaming of its own variables, each
229
+ kind to its own kind. A rule's graph pattern therefore matches only formulas
230
+ with the same triples, and its own blank nodes match only the formula's own
231
+ blank nodes. A rule variable never stands for one of them, but it can stand
232
+ for a quoted universal, as rules stated as data quote their variables.
233
+ `log:includes` never instantiates the universals of its subject. Matching in
234
+ nested graph terms below the first level is by unification, so it depends on
235
+ the order of their triples. See
236
+ [universal instances](https://eyereasoner.github.io/eyemind/examples/deck/universal-instances),
237
+ [a shared existential](https://eyereasoner.github.io/eyemind/examples/deck/shared-existential),
238
+ [an existential rule](https://eyereasoner.github.io/eyemind/examples/deck/explicit-existential-rule),
239
+ [quantifier scopes](https://eyereasoner.github.io/eyemind/examples/deck/quantifier-scopes) and
240
+ [graph terms](https://eyereasoner.github.io/eyemind/examples/deck/graph-terms).
241
+
242
+ The Notation3 test suite case `static/success-literal-22.n3` expects the
243
+ pattern `{ _:X :B :C }` to match `{ :A :B :C }`. eyemind's scorer checks
244
+ instead that the conclusion is absent, because a quoted blank node is the
245
+ formula's own variable.
208
246
 
209
247
  N3 has no named-graph syntax. When RDF data joins an N3 run, eyemind represents
210
248
  each named graph as a quoted formula through `graph:content`, where `graph:`
@@ -351,12 +389,12 @@ The statement chooses the direction:
351
389
 
352
390
  | Strategy | Stated with | How it works |
353
391
  | --- | --- | --- |
354
- | **Forward** | `implies`, `query`, `contradiction` | From the facts, round after round, until a round adds nothing new. |
392
+ | **Forward** | `implies`, `restricted`, `query`, `contradiction` | From the facts, round after round, until a round adds nothing new. |
355
393
  | **Backward** | `implied_by`, `fact` | When a goal asks: depth-first, left to right, in the order the clauses are written. |
356
394
 
357
- Forward rules suit closures and classifications: `implies([path(X, Y), edge(Y, Z)], path(X, Z))` terminates on a cyclic graph. 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.
395
+ 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, 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"](https://arxiv.org/abs/2607.28778), 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.
358
396
 
359
- 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. `--max-depth`, `--max-iterations` and `--max-inferences` bound a run, and exceeding one is an error, never a partial answer. [SPEC §8](https://eyereasoner.github.io/eyemind/SPEC#8-evaluation-and-conclusions) defines the details.
397
+ 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](https://eyereasoner.github.io/eyemind/SPEC#64-chain-stratification)). `--max-depth`, `--max-iterations` and `--max-inferences` bound a run, and exceeding one is an error, never a partial answer. [SPEC §8](https://eyereasoner.github.io/eyemind/SPEC#8-evaluation-and-conclusions) defines the details.
360
398
 
361
399
  ## Proofs, and what checking one means
362
400
 
package/SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The eyemind Rule Language and Proof Format
5
- Version: eyemind 0.5.13
5
+ Version: eyemind 0.5.15
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
@@ -39,6 +39,7 @@ proof.
39
39
  - [6.1 Dependencies and stratification](#61-dependencies-and-stratification)
40
40
  - [6.2 Inline rule templates](#62-inline-rule-templates)
41
41
  - [6.3 Source rule inspection](#63-source-rule-inspection)
42
+ - [6.4 Chain stratification](#64-chain-stratification)
42
43
  - [7. Semantics](#7-semantics)
43
44
  - [7.1 Herbrand interpretation](#71-herbrand-interpretation)
44
45
  - [7.2 Variables and witnesses](#72-variables-and-witnesses)
@@ -413,12 +414,13 @@ The basic statement forms are:
413
414
  | `fact(T)` | State one fact with head `T` and no body. |
414
415
  | `implies(Body, Head)` | State a forward rule. `Body` is a goal or a non-empty array of goals; `Head` is one head or a non-empty array of heads. |
415
416
  | `implied_by(Head, Body)` | State a backward rule with one head. `Body` is a goal or a non-empty array of goals. |
417
+ | `restricted(Body, Head)` | State a restricted forward rule: as `implies`, but a firing whose heads some known values already satisfy is not applied ([Section 7.2](#72-variables-and-witnesses)). |
416
418
  | `query(G)` | Report the successful instances of `G`. An array denotes one conjunction. |
417
419
  | `contradiction(G)` | Halt with conclusion `'false'` when `G` succeeds. An array denotes one conjunction. |
418
420
  | `facts_from(Path)` | Read a document from a path and state one fact per expression. |
419
421
  | `facts_from({text: Text})` | Read a document from a string and state one fact per expression. |
420
422
 
421
- `implies` and `implied_by` require exactly two arguments. The variadic forms
423
+ `implies`, `implied_by` and `restricted` require exactly two arguments. The variadic forms
422
424
  of `fact`, `query` and `contradiction` are also defined:
423
425
 
424
426
  ```js
@@ -720,13 +722,19 @@ dependency. Forward rules run in order of rank ([Section 8.2](#82-forward-evalua
720
722
 
721
723
  A program MUST be rejected when:
722
724
 
723
- - no such assignment exists, because a closed dependency lies on a cycle;
725
+ - no such assignment exists, because a closed dependency lies on a cycle,
726
+ and the program is not chain-stratified ([Section 6.4](#64-chain-stratification));
724
727
  - a forward rule can reach, through dependencies, a clause with a body goal
725
728
  that is a variable.
726
729
 
727
730
  Because dependencies compare whole terms, two relations sharing a predicate
728
731
  name MAY have different ranks.
729
732
 
733
+ The guard of a restricted rule ([Section 7.2](#72-variables-and-witnesses)) is a body goal whose
734
+ dependencies are open, though it is a negation: the rule ranks at least as
735
+ high as every clause that derives its heads, itself included, without a
736
+ closed dependency on itself.
737
+
730
738
  ### 6.2 Inline rule templates
731
739
 
732
740
  Nested `implies(Body, Head)` and `implied_by(Head, Body)` calls construct rule
@@ -846,6 +854,98 @@ Inspection uses a fixed source catalogue, so its own results do not depend on
846
854
  forward rounds. Other goals using derived patterns still participate in
847
855
  stratification. Negation and collection keep their own justifications ([Section 10.3](#103-steps)).
848
856
 
857
+ ### 6.4 Chain stratification
858
+
859
+ A rule whose head has a variable in every argument, such as
860
+ `implies([rdf(P, 'spo', Q), rdf(X, P, Y)], rdf(X, Q, Y))`, unifies with every
861
+ negated goal of its relation, so a cycle through it and a negation defeats
862
+ [Section 6.1](#61-dependencies-and-stratification)'s ranks. Many such programs still have one intended result:
863
+ no sequence of rule applications that starts at a rule with a negation can
864
+ make one of its negated goals true without also satisfying a
865
+ contradiction's body. N. Küchenmeister, A. Ivliev, D. Arndt and
866
+ M. Krötzsch, "Stratified Negation in RDF Rules: A Correct Approach"
867
+ (arXiv:2607.28778), call such programs chain-stratified under constraints.
868
+ This section defines the decision eyemind makes, which errs towards
869
+ rejection: a program it accepts is chain-stratified in the paper's sense.
870
+ It is made only for a program [Section 6.1](#61-dependencies-and-stratification) rejects for a closed cycle.
871
+
872
+ **Rules.** The rules are the forward clauses and the backward clauses with a
873
+ body. A program with templates or captures, a rule body goal `or`, `once`,
874
+ `call` or a variable, or a backward rule with a negation or collection, is
875
+ not chain-stratified. A rule has:
876
+
877
+ - **positive goals**: its body goals other than primitives, negations,
878
+ collections and `'true'`, and other than a restricted rule's guard
879
+ ([Section 7.2](#72-variables-and-witnesses));
880
+ - **negated groups**: for each `not(G)` and `findall(T, G, L)` body goal,
881
+ the goals of the conjunction `G` other than primitives; a group with a
882
+ control or a variable makes the program not chain-stratified, and an
883
+ empty group is left out;
884
+ - **heads**: a forward rule's heads other than `'true'` and `'false'`, or a
885
+ backward rule's head.
886
+
887
+ A rule is **Datalog** when it has no negation or collection and is not
888
+ restricted; a Datalog rule without primitives is **pure**. A contradiction is
889
+ a forward rule whose head is `'false'`.
890
+
891
+ **Closure.** Chain facts are terms whose variables are treated as distinct
892
+ constants. The closure of a set of chain facts adds, for each pure Datalog
893
+ rule renamed apart and each way its positive goals unify with facts of the
894
+ set, its heads that the unifier makes ground, repeatedly until nothing is
895
+ added. The set is **contradictory** when a contradiction's positive goals
896
+ match it.
897
+
898
+ **States.** A chain state is formed from a rule `r`, its heads `H`,
899
+ **conditions** `C` and **caused facts** `K`. Let `B` be the closure of `C`
900
+ and `F` the closure of `C ∪ K ∪ H`; there is no state when either is
901
+ contradictory. The state's facts are the facts of `F` whose variables all
902
+ occur in `H`, each marked **caused** when it is not in `B`. Two states are
903
+ the same when they have the same rule and, after renaming their variables
904
+ to `V0`, `V1`, ... in order of first occurrence in `H`, the same heads and
905
+ the same facts with the same marks.
906
+
907
+ **Chains.** Each forward rule `s` that is not Datalog starts a search with
908
+ the state of `s` with `C` its positive goals, `K` empty and `H` its heads,
909
+ renamed apart. A state `S` is **extended** by a rule `r` with heads, renamed
910
+ apart, for each positive goal `g` of `r` and each caused fact `c` of `S`
911
+ whose most general unifier with `g` is `σ`. Let `D` be the facts of `S` and
912
+ the positive goals of `r`, under `σ`. The extension is discarded when the
913
+ closure of `D` is contradictory, when the heads of `r` under `σ` match facts
914
+ of `D` with only their variables absent from `D` free, or when the goals of
915
+ a negated group of `r` under `σ` match facts of `D` in the same way.
916
+ Otherwise it gives the state of `r` with `H` its heads under `σ`, `K` the
917
+ caused facts of `S` under `σ`, and `C` the other facts of `S` under `σ`
918
+ together with the positive goals of `r` under `σ` that are not among `K`.
919
+ Each search visits a state once.
920
+
921
+ **Edges.** A rule `s` has an edge to a rule `t` with a negated group when a
922
+ state of `s`'s search has a caused fact that unifies, by `τ`, with a goal of
923
+ a negated group of `t` renamed apart, and the facts of the state under `τ`
924
+ have a closure that is not contradictory. The program is
925
+ **chain-stratified** when no rule reaches itself through edges. A search
926
+ that visits more than 4096 states in total, or a closure of more than 2048
927
+ facts, makes the program not chain-stratified.
928
+
929
+ **Ranks.** A Datalog forward rule has rank 0. Another forward rule has rank 1,
930
+ or one more than the greatest rank of a rule with an edge to it. Forward
931
+ rules then run by these ranks as [Section 8.2](#82-forward-evaluation-and-witnesses) specifies for chain strata. For
932
+ example, with constraints that the examiner relation is no subproperty of
933
+ the participant relation, of `spo` or of the type relation:
934
+
935
+ ```js
936
+ implies(rdf(C, 'participant', P), rdf(P, 'type', 'Student'))
937
+ implies([rdf(C, 'teacher', P), not(rdf(P, 'type', 'Student'))], rdf(C, 'examiner', P))
938
+ implies([rdf(P, 'spo', Q), rdf(Q, 'spo', R)], rdf(P, 'spo', R))
939
+ implies([rdf(P, 'spo', Q), rdf(X, P, Y)], rdf(X, Q, Y))
940
+ contradiction(rdf('examiner', 'spo', 'participant'))
941
+ contradiction(rdf('examiner', 'spo', 'spo'))
942
+ contradiction(rdf('examiner', 'spo', 'type'))
943
+ ```
944
+
945
+ is chain-stratified: every chain from the second rule that could make
946
+ `rdf(P, 'type', 'Student')` true satisfies a contradiction's body. Without
947
+ any one of the three contradictions it is not.
948
+
849
949
  ## 7. Semantics
850
950
 
851
951
  ### 7.1 Herbrand interpretation
@@ -876,6 +976,35 @@ unless it is a scoped inspection variable ([Section 6.3](#63-source-rule-inspect
876
976
  including captured template values. Body variables absent from that context
877
977
  do not distinguish witnesses; shared head variables share a witness.
878
978
 
979
+ A restricted rule, `restricted(Body, Head)`, with head-only variables
980
+ `W1, ..., Wk` has one more body goal after `Body`, its **guard**:
981
+
982
+ ```js
983
+ not([H1', ..., Hm', not_unify([_A1, ..., _Ak], [S1, ..., Sk])])
984
+ ```
985
+
986
+ `H1', ..., Hm'` are its heads with each `Wi` replaced by a distinct
987
+ anonymous variable `_Ai`, numbered `_0`, `_1`, ... as the first such names
988
+ the clause does not use; `Si` is `skolem(N, 'Wi', Frontier)`, the witness a
989
+ firing of clause `N` gives `Wi` ([Section 8.2](#82-forward-evaluation-and-witnesses)), where `Frontier` is the list of
990
+ the heads' other variables in order of first occurrence. The guard holds when
991
+ nothing but the firing's own witnesses satisfies its heads. Before a
992
+ firing, that is when no known values satisfy them, so a satisfied rule does
993
+ not invent new values, as the restricted chase does; after it, that is when
994
+ the firing's witnesses are needed, which the search certificate shows like
995
+ any negation. A restricted rule without head-only variables has no guard and
996
+ behaves as `implies`. For example:
997
+
998
+ ```js
999
+ fact(human('jo'), father('jo', 'bob'))
1000
+ restricted(human(X), [father(X, F), man(F)])
1001
+ implies(father(X, Y), man(Y))
1002
+ ```
1003
+
1004
+ concludes `man('bob')` and invents no father for `'jo'`, since `'bob'`
1005
+ already satisfies the heads once the third rule has run. A restricted
1006
+ rule's display omits its guard ([Section 10.2](#102-clause-displays)).
1007
+
879
1008
  This gives the specified Skolemized reading of existential conclusions.
880
1009
  The original existential rule need not have a least model over its original
881
1010
  vocabulary. A witness is an ordinary compound in subsequent reasoning; it
@@ -1007,6 +1136,23 @@ and `p(2)` publishes `a(1)`, `b(1)`, `a(2)`, `b(2)`. For each head:
1007
1136
  When the run asks its own goals ([Section 8.4](#84-external-goals)), rules whose heads are all
1008
1137
  `'true'` are not run.
1009
1138
 
1139
+ A program accepted by chain stratification ([Section 6.4](#64-chain-stratification)) runs its forward
1140
+ rules by chain strata instead of stratum by stratum. Rules of rank 0 run in
1141
+ rounds; a round of the rules of a rank `k > 0` runs only after a round of
1142
+ each lower rank, in increasing order, that added nothing; after a round of
1143
+ any rank that adds something, rank 0 runs again. Reasoning ends after a
1144
+ round of the highest rank that adds nothing, all lower ranks' latest rounds
1145
+ having added nothing. A rule thus never fires while a rule of a lower rank
1146
+ has a firing left.
1147
+
1148
+ A stratum with restricted rules alternates two kinds of round. Its other
1149
+ rules run in rounds as above; a round of its restricted rules, in clause
1150
+ order, follows only a round of the other rules that adds nothing, and is
1151
+ followed by rounds of the other rules again when it adds something. The
1152
+ stratum ends with a round of its restricted rules that adds nothing. The
1153
+ other rules of a stratum thus run before its restricted rules, whose guards
1154
+ see what they derive.
1155
+
1010
1156
  For a generator, use its scope projection ([Section 6.2](#62-inline-rule-templates)) as its head when
1011
1157
  constructing witnesses. For an appended forward clause of [Section 6.2](#62-inline-rule-templates),
1012
1158
  prepend one element to
@@ -1259,8 +1405,9 @@ A checker MUST treat every statement that is neither `clause/2`, `step/4`,
1259
1405
  ### 10.2 Clause displays
1260
1406
 
1261
1407
  `Display` shows clause `N` in normalized statement form: `fact(Head)`,
1262
- `implies(Body, Head)`, `implied_by(Head, Body)`, `query(G1, ...)` or
1263
- `contradiction(G1, ...)`, where `Body` is the clause's one body goal, or the
1408
+ `implies(Body, Head)`, `restricted(Body, Head)`, `implied_by(Head, Body)`,
1409
+ `query(G1, ...)` or `contradiction(G1, ...)`, where `Body` is the clause's
1410
+ one body goal without a restricted rule's guard, or the
1264
1411
  array of its body goals when it has several, `Head` likewise the head or the
1265
1412
  array of heads, and `G1, ...` are the body goals themselves. Displays are not
1266
1413
  authority: a checker MUST compare each with the program it checks against.
@@ -1984,6 +2131,9 @@ in that closure. To use a listing for C10:
1984
2131
  - Every backward head variable MUST be grounded by its body.
1985
2132
  - Every forward head variable MUST either be grounded by its body or be a
1986
2133
  head-only witness checked by C8.
2134
+ - A restricted rule's guard is a negation, so a closure with a restricted
2135
+ rule that has head-only variables is not supported: which firings a
2136
+ restricted rule makes can depend on the order of rule applications.
1987
2137
 
1988
2138
  Supported facts and closed listings then establish the least ground
1989
2139
  positive closure. More general forward execution requires publication
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.13",
3
+ "version": "0.5.15",
4
4
  "description": "A dependency-free JavaScript rule language with forward and backward reasoning and checkable proofs.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/chains.js ADDED
@@ -0,0 +1,333 @@
1
+ // Chain stratification: an ordering of forward rules for programs whose
2
+ // negations or collections lie on a dependency cycle (SPEC Section 6.4).
3
+ //
4
+ // Classic stratification (program.js) asks whether a rule's head can unify
5
+ // with a negated goal. A head written with variables in every position, as
6
+ // rdf(X, Q, Y), then reaches every negation, and so does any cycle through
7
+ // it. Following N. Küchenmeister, A. Ivliev, D. Arndt and M. Krötzsch,
8
+ // "Stratified Negation in RDF Rules: A Correct Approach" (arXiv:2607.28778),
9
+ // this asks instead which chains of rule applications starting at a rule
10
+ // with a negation can make some negated goal true, given the Datalog rules
11
+ // and the contradictions: a chain whose facts make a contradiction hold
12
+ // is no chain. The rules form layers when no chain leads from a rule back to
13
+ // itself. Each check errs on the side of more chains, so an accepted program
14
+ // is chain-stratified in the paper's sense.
15
+ import { PRIMITIVE_KEYS } from './builtins.js';
16
+ import { Env, Struct, Var, copyResolved, flattenConjunction, freshTerm, identity, isCallable, isTerm, key, unify, variables } from './terms.js';
17
+
18
+ // The analysis stops, rejecting the program, beyond these many chain states,
19
+ // or closure facts for one state.
20
+ export const CHAIN_LIMITS = { states: 4096, facts: 2048 };
21
+
22
+ // Ranks for the forward clauses of a program classic stratification
23
+ // rejects, or null when the program is not chain-stratified, as far as this
24
+ // analysis can tell. Rank 0 holds the Datalog rules; a rule with a negation,
25
+ // a collection or a restriction ranks above every rule a chain from it can
26
+ // disable.
27
+ export function chainStrata(clauses) {
28
+ const rules = [];
29
+ for (const clause of clauses) {
30
+ if (clause.parentId !== null || clause.templates.length || clause.captures !== null) return null;
31
+ if (!clause.forward && !clause.body.length) continue;
32
+ const rule = ruleOf(clause);
33
+ if (rule === null) return null;
34
+ rules.push(rule);
35
+ }
36
+ const datalog = rules.filter((rule) => rule.datalog && rule.pure);
37
+ const negating = rules.filter((rule) => rule.negated.length);
38
+ const edges = new Map();
39
+ let states = 0;
40
+ for (const start of rules.filter((rule) => rule.forward && !rule.datalog)) {
41
+ const seen = new Set();
42
+ const first = stateOf(start, renamed(start), datalog);
43
+ if (first === null) continue;
44
+ const pending = [first];
45
+ while (pending.length) {
46
+ const state = pending.pop();
47
+ if (seen.has(state.label)) continue;
48
+ seen.add(state.label);
49
+ if (++states > CHAIN_LIMITS.states) return null;
50
+ for (const target of negating) {
51
+ if (edges.get(start.id)?.has(target.id) || !disables(state, target, datalog)) continue;
52
+ if (!edges.has(start.id)) edges.set(start.id, new Set());
53
+ edges.get(start.id).add(target.id);
54
+ // An edge that closes a cycle settles the question.
55
+ if (reaches(edges, target.id, start.id)) return null;
56
+ }
57
+ for (const next of rules) {
58
+ if (!next.heads.length) continue;
59
+ for (const extended of extensions(state, next, datalog)) {
60
+ if (extended === undefined) return null;
61
+ if (!seen.has(extended.label)) pending.push(extended);
62
+ }
63
+ }
64
+ }
65
+ }
66
+ // Layers: the longest path of chain edges, above the Datalog rules.
67
+ const ranks = new Map();
68
+ const forward = rules.filter((rule) => rule.forward);
69
+ const visiting = new Set();
70
+ const rank = (rule) => {
71
+ if (ranks.has(rule.id)) return ranks.get(rule.id);
72
+ if (rule.datalog) return 0;
73
+ if (visiting.has(rule.id)) return null;
74
+ visiting.add(rule.id);
75
+ let value = 1;
76
+ for (const [from, targets] of edges) {
77
+ if (!targets.has(rule.id)) continue;
78
+ const before = rules.find((item) => item.id === from);
79
+ const below = rank(before);
80
+ if (below === null) return null;
81
+ value = Math.max(value, below + 1);
82
+ }
83
+ visiting.delete(rule.id);
84
+ ranks.set(rule.id, value);
85
+ return value;
86
+ };
87
+ for (const rule of forward) {
88
+ const value = rank(rule);
89
+ if (value === null) return null;
90
+ ranks.set(rule.id, value);
91
+ }
92
+ return ranks;
93
+ }
94
+
95
+ // Whether edges lead from one rule to another, or back to itself.
96
+ function reaches(edges, from, to) {
97
+ const pending = [from];
98
+ const seen = new Set();
99
+ while (pending.length) {
100
+ const id = pending.pop();
101
+ if (id === to) return true;
102
+ if (seen.has(id)) continue;
103
+ seen.add(id);
104
+ pending.push(...(edges.get(id) ?? []));
105
+ }
106
+ return false;
107
+ }
108
+
109
+ // A clause as the analysis reads it: positive goals, negated groups (a
110
+ // negation or a collection), heads, and whether it is Datalog (no negation,
111
+ // collection or restriction) and pure (no primitive, so its closure is
112
+ // exact). A control other than these, or a variable goal, gives null.
113
+ function ruleOf(clause) {
114
+ const positive = [];
115
+ const negated = [];
116
+ let pure = true;
117
+ for (const goal of clause.localBody) {
118
+ if (goal === clause.guard) continue;
119
+ if (goal === 'true') continue;
120
+ if (!isCallable(goal)) return null;
121
+ const goalKey = key(goal);
122
+ if (goalKey === 'not/1' || goalKey === 'findall/3') {
123
+ const group = [];
124
+ for (const inner of flattenConjunction(goalKey === 'not/1' ? goal.args[0] : goal.args[1])) {
125
+ if (inner instanceof Var || !isCallable(inner)) return null;
126
+ if (PRIMITIVE_KEYS.has(key(inner))) continue;
127
+ if (['not/1', 'findall/3', 'or/2', 'once/1', 'call/1'].includes(key(inner))) return null;
128
+ group.push(inner);
129
+ }
130
+ if (group.length) negated.push(group);
131
+ pure = false;
132
+ } else if (['or/2', 'once/1', 'call/1'].includes(goalKey)) {
133
+ return null;
134
+ } else if (PRIMITIVE_KEYS.has(goalKey)) {
135
+ pure = false;
136
+ } else {
137
+ positive.push(goal);
138
+ }
139
+ }
140
+ // A backward rule is answered by search, which a cycle through its
141
+ // negation or collection would never finish.
142
+ if (!clause.forward && negated.length) return null;
143
+ const heads = clause.forward ? clause.plainHeads.filter((head) => head !== 'true' && head !== 'false') : [clause.head];
144
+ const constraint = clause.forward && clause.plainHeads.includes('false');
145
+ return {
146
+ id: clause.id, forward: clause.forward, positive, negated, heads, constraint, pure,
147
+ datalog: !negated.length && !clause.restricted,
148
+ };
149
+ }
150
+
151
+ let serial = 0;
152
+ function renamed(rule) {
153
+ const names = new Map();
154
+ const suffix = `chain${++serial}`;
155
+ return {
156
+ positive: rule.positive.map((goal) => freshTerm(goal, suffix, names)),
157
+ negated: rule.negated.map((group) => group.map((goal) => freshTerm(goal, suffix, names))),
158
+ heads: rule.heads.map((goal) => freshTerm(goal, suffix, names)),
159
+ };
160
+ }
161
+
162
+ // Variables written as constants, so that facts can be matched by rules.
163
+ function freeze(term, names) {
164
+ if (term instanceof Var) {
165
+ if (!names.has(term.name)) names.set(term.name, new Struct('$chain_var', [term.name]));
166
+ return names.get(term.name);
167
+ }
168
+ if (term instanceof Struct) return new Struct(term.name, term.args.map((arg) => freeze(arg, names)));
169
+ return term;
170
+ }
171
+ function thaw(term, vars) {
172
+ if (isTerm(term, '$chain_var', 1)) {
173
+ if (!vars.has(term.args[0])) vars.set(term.args[0], new Var(term.args[0]));
174
+ return vars.get(term.args[0]);
175
+ }
176
+ if (term instanceof Struct) return new Struct(term.name, term.args.map((arg) => thaw(arg, vars)));
177
+ return term;
178
+ }
179
+ function frozenNames(term, out = new Set()) {
180
+ if (isTerm(term, '$chain_var', 1)) out.add(term.args[0]);
181
+ else if (term instanceof Struct) for (const arg of term.args) frozenNames(arg, out);
182
+ return out;
183
+ }
184
+
185
+ // The closure of frozen facts under the pure Datalog rules: a Map of facts by
186
+ // identity, null when a contradiction holds, undefined beyond the limit.
187
+ function closure(facts, datalog) {
188
+ const known = new Map(facts.map((fact) => [identity(fact), fact]));
189
+ for (let changed = true; changed;) {
190
+ changed = false;
191
+ for (const rule of datalog) {
192
+ const fresh = renamed(rule);
193
+ for (const env of matches(fresh.positive, 0, [...known.values()], new Env())) {
194
+ if (rule.constraint) return null;
195
+ for (const head of fresh.heads) {
196
+ const fact = copyResolved(head, env);
197
+ if (variables(fact).size) continue;
198
+ const id = identity(fact);
199
+ if (known.has(id)) continue;
200
+ known.set(id, fact);
201
+ changed = true;
202
+ if (known.size > CHAIN_LIMITS.facts) return undefined;
203
+ }
204
+ }
205
+ }
206
+ }
207
+ return known;
208
+ }
209
+
210
+ function* matches(goals, index, facts, env) {
211
+ if (index === goals.length) {
212
+ yield env;
213
+ return;
214
+ }
215
+ for (const fact of facts) {
216
+ const mark = env.mark();
217
+ if (unify(goals[index], fact, env)) yield* matches(goals, index + 1, facts, env);
218
+ env.undo(mark);
219
+ }
220
+ }
221
+
222
+ // Whether goals, their variables free, hold among frozen facts.
223
+ function holds(goals, facts) {
224
+ for (const _ of matches(goals, 0, facts, new Env())) return true; // eslint-disable-line no-unused-vars
225
+ return false;
226
+ }
227
+
228
+ // A chain state: the last rule's heads, the closure of the chain's facts
229
+ // that mention only their variables, and which of those the chain caused,
230
+ // with a label naming it up to renaming. The chain's conditions hold
231
+ // independently of it: the start's goals, and each later rule's goals but
232
+ // the one a caused fact matched. A fact is caused when the closure of
233
+ // everything holds it but the closure of the conditions does not. null when
234
+ // a contradiction holds, undefined beyond the limit.
235
+ function stateOf(rule, instance, datalog, conditions = instance.positive, caused = []) {
236
+ const names = new Map();
237
+ const independent = conditions.map((goal) => freeze(goal, names));
238
+ const base = closure(independent, datalog);
239
+ if (base === null) return null;
240
+ if (base === undefined) return undefined;
241
+ const heads = instance.heads.map((goal) => freeze(goal, names));
242
+ const facts = closure([...independent, ...caused.map((goal) => freeze(goal, names)), ...heads], datalog);
243
+ if (facts === null) return null;
244
+ if (facts === undefined) return undefined;
245
+ const keep = new Set();
246
+ for (const head of heads) frozenNames(head, keep);
247
+ const kept = [...facts.values()].filter((fact) => [...frozenNames(fact)].every((name) => keep.has(name)));
248
+ const added = kept.map((fact) => !base.has(identity(fact)));
249
+ // Rename the kept variables in order of their first occurrence in the heads.
250
+ const order = new Map();
251
+ for (const head of heads) for (const name of frozenNames(head)) if (!order.has(name)) order.set(name, `V${order.size}`);
252
+ const canonical = (term) => (isTerm(term, '$chain_var', 1) ? new Struct('$chain_var', [order.get(term.args[0])])
253
+ : term instanceof Struct ? new Struct(term.name, term.args.map(canonical)) : term);
254
+ const texts = kept.map((fact, i) => `${added[i] ? '+' : ''}${identity(canonical(fact))}`).sort();
255
+ const label = `${rule.id}\u0001${heads.map((head) => identity(canonical(head))).join('\u0002')}\u0001${texts.join('\u0002')}`;
256
+ return { rule, heads: heads.map(canonical), facts: kept.map(canonical), added, label };
257
+ }
258
+
259
+ // The chain states extending a state by one application of next: a goal of
260
+ // next matches a fact the state's heads add, a head or what the Datalog
261
+ // rules derive with it, the facts do not already satisfy next's heads or a
262
+ // negated group of next, and no contradiction holds.
263
+ function* extensions(state, next, datalog) {
264
+ const vars = new Map();
265
+ const facts = state.facts.map((fact) => thaw(fact, vars));
266
+ const added = facts.filter((_, i) => state.added[i]);
267
+ for (let position = 0; position < next.positive.length; position++) {
268
+ for (const head of added) {
269
+ const instance = renamed(next);
270
+ const env = new Env();
271
+ if (!unify(instance.positive[position], head, env)) continue;
272
+ const resolve = (goal) => copyResolved(goal, env);
273
+ const body = [...facts.map(resolve), ...instance.positive.map(resolve)];
274
+ const causedBefore = facts.filter((_, i) => state.added[i]).map(resolve);
275
+ const causedIds = new Set(causedBefore.map((goal) => identity(goal)));
276
+ const conditions = [...facts.filter((_, i) => !state.added[i]).map(resolve),
277
+ ...instance.positive.map(resolve).filter((goal) => !causedIds.has(identity(goal)))];
278
+ const applied = { positive: instance.positive.map(resolve), negated: instance.negated.map((group) => group.map(resolve)), heads: instance.heads.map(resolve) };
279
+ const names = new Map();
280
+ const known = closure(body.map((goal) => freeze(goal, names)), datalog);
281
+ if (known === null) continue;
282
+ if (known === undefined) {
283
+ yield undefined;
284
+ return;
285
+ }
286
+ // Whether next adds something, and whether its negations hold, is
287
+ // asked of the chain's closed facts and next's own goals, not of
288
+ // their closure: the closure would include next's own conclusion.
289
+ // Frozen, but with the variables only next's heads or negations
290
+ // mention left free, as existential patterns.
291
+ const pattern = (goal) => freezeBound(goal, names);
292
+ const before = body.map(pattern);
293
+ if (holds(applied.heads.map(pattern), before)) continue;
294
+ if (applied.negated.some((group) => holds(group.map(pattern), before))) continue;
295
+ const extended = stateOf(next, applied, datalog, conditions, causedBefore);
296
+ if (extended === undefined) {
297
+ yield undefined;
298
+ return;
299
+ }
300
+ if (extended !== null) yield extended;
301
+ }
302
+ }
303
+ }
304
+
305
+ // A goal with the variables the frozen facts name frozen and the others free.
306
+ function freezeBound(term, names) {
307
+ if (term instanceof Var) return names.has(term.name) ? names.get(term.name) : term;
308
+ if (term instanceof Struct) return new Struct(term.name, term.args.map((arg) => freezeBound(arg, names)));
309
+ return term;
310
+ }
311
+
312
+ // Whether a fact the state's heads add, a head or what the Datalog rules
313
+ // derive with it, can make a negated goal of target true without a
314
+ // contradiction holding.
315
+ function disables(state, target, datalog) {
316
+ const vars = new Map();
317
+ const facts = state.facts.map((fact) => thaw(fact, vars));
318
+ const added = facts.filter((_, i) => state.added[i]);
319
+ for (const group of target.negated) {
320
+ for (let position = 0; position < group.length; position++) {
321
+ for (const head of added) {
322
+ const instance = renamed(target);
323
+ const env = new Env();
324
+ const goal = instance.negated[target.negated.indexOf(group)][position];
325
+ if (!unify(goal, head, env)) continue;
326
+ const names = new Map();
327
+ const known = closure(facts.map((fact) => freeze(copyResolved(fact, env), names)), datalog);
328
+ if (known !== null) return true;
329
+ }
330
+ }
331
+ }
332
+ return false;
333
+ }