eyemind 0.8.15 → 0.8.17

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/LS-SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The Logic Script (LS) Language and Proof Format
5
- Version: eyemind 0.8.15
5
+ Version: eyemind 0.8.17
6
6
  ```
7
7
 
8
8
  This document specifies Logic Script (LS): the syntax and meaning of its
package/README.md CHANGED
@@ -13,7 +13,7 @@ program, a JavaScript library and a browser application.
13
13
  [Playground](https://eyereasoner.github.io/eyemind/playground/) · [Examples](https://eyereasoner.github.io/eyemind/examples/) · [Specification](https://eyereasoner.github.io/eyemind/LS-SPEC) · [Conformance](https://eyereasoner.github.io/eyemind/conformance/)
14
14
 
15
15
  The examples are 158 runnable programs, each with a card deck and saved
16
- conclusions; all but one streamed example also save proofs and check reports. The specification defines the language,
16
+ conclusions; all but the two streamed examples also save proofs and check reports. The specification defines the language,
17
17
  the proof format and how a proof is checked; its conformance suite has
18
18
  1247 cases that test language and proof behavior, and runs
19
19
  [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
@@ -52,32 +52,42 @@ the proof format and how a proof is checked; its conformance suite has
52
52
 
53
53
  ## Why eyemind?
54
54
 
55
- Prolog, Datalog, N3 and SRL already exist, and eyemind adds no new logic: rules run to a least fixpoint, with stratified negation and collection. What it adds is that it does not stop at the answer. Every conclusion can come with a proof that a separate checker verifies against your program, without calling the reasoner.
56
-
57
- 1. **The proof covers everything that went into the answer.**
58
- - Most engines show an answer, or at best a trace you have to trust.
59
- - eyemind proofs include the hard parts:
60
- - "nothing matched" (negation and collections), decided from complete answer tables whose listings of derived facts must be closed;
61
- - what a rule says exists, as the Skolem term of that rule firing;
62
- - whether each answer really answers the question asked, and whether every answer of the question is there.
63
- - A forged proof must never pass the check, so a result is something you can hand to someone who does not trust your engine.
64
- 2. **Logic Script programs are JavaScript scripts.**
65
- - There is no syntax to learn, no parser to install and no dependency.
66
- - The same program runs on the command line, as a library and in a browser tab.
67
- - Conclusions and proofs are data that is read back into terms without being run.
68
- 3. **Forward and backward reasoning in one program.**
69
- - Classic Datalog is forward-only and has no function terms; Prolog is backward-only.
70
- - eyemind does both: forward rounds compute what follows, backward search answers questions, the two call each other, and what a rule says exists becomes a Skolem term.
71
- 4. **A specification written for other implementers.**
72
- - The specification and its black-box [conformance suite](https://eyereasoner.github.io/eyemind/conformance/) let someone else build an independent LS implementation and test it.
73
- - Agreement between independent implementations is what makes a proof worth more than "trust our code".
74
- 5. **Exact numbers.** Integers are BigInts and are never silently turned into floats.
75
-
76
- When eyemind is not the right tool:
77
-
78
- - If you do not need proofs, use the mature tools: SWI-Prolog and XSB have tabling, and Soufflé is fast at scale.
79
- - N3 and SRL are designed around RDF and Web data. eyemind does not compete there: it reads them, and compiles them to LS (see [Other formats](#other-formats)).
80
- - eyemind is for cases where someone else has to be able to check why a conclusion holds: audits, compliance, and decisions between parties that do not trust each other.
55
+ eyemind adds no new logic: as in Datalog, Prolog, N3 and SRL, rules run to a
56
+ least fixpoint, with stratified negation and collection. What it adds is
57
+ evidence. Every conclusion can come with a proof that a separate checker
58
+ verifies against your program, without running the reasoner.
59
+
60
+ 1. **Proofs that cover the whole answer.** Most engines give an answer, or a
61
+ trace you have to trust. An eyemind proof also justifies the hard parts:
62
+ - that nothing matched, for negation and collections, from complete answer
63
+ tables whose listings of derived facts must be closed;
64
+ - what a rule says exists, as the Skolem term of its firing;
65
+ - that each answer answers the question asked, and that none is missing.
66
+
67
+ A forged proof must never pass the check, so you can hand a result to
68
+ someone who does not trust your engine.
69
+ 2. **Programs are JavaScript.** No syntax to learn, no parser to install, no
70
+ dependencies. One program runs on the command line, as a library and in a
71
+ browser tab; conclusions and proofs are data, read back without being run.
72
+ 3. **Forward and backward reasoning together.** Datalog is forward-only and
73
+ has no function terms; Prolog is backward-only. In eyemind, forward rounds
74
+ derive what follows, backward search answers questions, and each calls the
75
+ other.
76
+ 4. **Your formats, the same proofs.** RDF 1.2, N3, SRL, Logical English and
77
+ the OWL 2 RL, SKOS, QUDT and SHACL profiles compile to LS, so their
78
+ conclusions get the same checkable proofs.
79
+ 5. **Written for other implementers.** The specification and its black-box
80
+ [conformance suite](https://eyereasoner.github.io/eyemind/conformance/) let
81
+ others build an independent LS implementation. Agreement between
82
+ implementations is what makes a proof worth more than "trust our code".
83
+ 6. **Exact numbers.** Integers are BigInts and never silently become floats.
84
+
85
+ **When to use something else.** If you do not need proofs, mature tools are
86
+ faster: SWI-Prolog and XSB have tabling, and Soufflé scales. N3 and SRL are
87
+ built for Web data; eyemind reads and compiles them rather than competing
88
+ (see [Other formats](#other-formats)). eyemind is for conclusions someone else
89
+ must be able to check: audits, compliance, and decisions between parties that
90
+ do not trust each other.
81
91
 
82
92
  ## Install and run
83
93
 
@@ -323,18 +333,27 @@ a triple that `owl:sameAs` copies to an equal object serves no rule that
323
333
  reads only its subject. See the
324
334
  [observations](https://eyereasoner.github.io/eyemind/examples/deck/observations-owl2rl) deck.
325
335
 
326
- SHACL shapes can state both contracts, which are trusted and not validated.
336
+ SHACL shapes state both contracts, which are trusted and not validated, and
337
+ plan the rules as [rdfjs-inference-engine](https://github.com/pietercolpaert/rdfjs-inference-engine/blob/main/SHACL-OPTIMIZATION.md)
338
+ does, by property and class. A rule whose schema premise, such as
339
+ `rdfs:domain` or `owl:FunctionalProperty`, the background lacks is left out.
327
340
  `--shacl-in FILE` reads the input shapes: each property shape is a pattern of
328
341
  message triples, its path the property and its value what `sh:datatype`,
329
342
  `sh:nodeKind`, `sh:class`, `sh:hasValue` or `sh:in` allows, in the default
330
- graph; other paths allow triples of each of their predicates. The rules are
331
- specialized to these patterns when the background loads, and a message whose
332
- triples are all instances of them uses that program, whatever fields it
333
- leaves out. When every input shape is closed, a message triple whose property
334
- no shape names or ignores is dropped first. A message with other triples gets
335
- rules of its own shape, and `--stats` reports `conforms` and `dropped` per
336
- message. `--shacl-out FILE` reads output shapes as an output contract: each
337
- property shape asks for triples of its path, of the values it allows. See the
343
+ graph; other paths allow triples of each of their predicates. Only rules that
344
+ can read a property or class of the background, the messages or a kept rule
345
+ stay, and they are specialized to these patterns when the background loads;
346
+ a message whose triples are all instances of them uses that program, and one
347
+ with other triples gets rules of its own shape. When every input shape is
348
+ closed, a message triple whose property no shape names or ignores is dropped
349
+ first; `--stats` reports `conforms` and `dropped` per message.
350
+ `--shacl-out FILE` reads output shapes as an output contract: each property
351
+ shape asks for triples of its path, of the values it allows, and only rules
352
+ concluding those, or what such a rule reads, stay. A variable property or
353
+ class in a rule takes the values its schema premise has in the background, as
354
+ partial evaluation gives them. Planned rules derive what the shapes lead to,
355
+ not every OWL 2 RL consequence: equality that the output does not ask for is
356
+ not derived. See the
338
357
  [shape-planning](https://eyereasoner.github.io/eyemind/examples/deck/shape-planning-owl2rl) deck.
339
358
 
340
359
  ```sh
@@ -584,8 +603,8 @@ eyemind [OPTION ...] [FILE ...]
584
603
  | `--goal GOAL` | Ask `GOAL` after forward reasoning; may be repeated. |
585
604
  | `--unused` | List the clauses that make no difference to the conclusions. |
586
605
  | `--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. |
587
- | `--shacl-in FILE` | With `--stream-messages` and an RDF logic profile, trust the SHACL shapes in `FILE` to describe the messages: the rules are specialized to them before the first message, and a closed shape drops triples of other properties. |
588
- | `--shacl-out FILE` | With an RDF logic profile, keep only the rules that can contribute to triples the SHACL shapes in `FILE` describe, and write only those triples. |
606
+ | `--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. |
607
+ | `--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. |
589
608
  | `--stats` | Print reasoning statistics as JSON to standard error. |
590
609
  | `--max-depth N`, `--max-iterations N`, `--max-inferences N` | Bound backward depth (1000000), forward rounds per stratum (1000) and goals started (1000000); a compiled N3, SRL, ODRL or RDF profile program has 1000000, 100000 and 1000000000. |
591
610
  | `--to FORMAT` | Write the conclusions as `turtle`, `trig`, `n-triples`, `n-quads`, `n3`, `le` or `eyemind`; by default LE for LE, N3 for N3, Turtle for SRL, ODRL and RDF profiles, eyemind otherwise. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.8.15",
3
+ "version": "0.8.17",
4
4
  "description": "A dependency-free Logic Script (LS) reasoner with forward and backward reasoning, checkable proofs, and RDF 1.2, Notation3 (N3), SPARQL 1.2 RL (SRL) and Logical English (LE) interoperability.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/cli.js CHANGED
@@ -181,7 +181,7 @@ export function main(argv, io) {
181
181
  // message with rules specialized to its shape (rdf-logic.js).
182
182
  let reasoner = null;
183
183
  const infer = (inputs, message) => {
184
- reasoner ??= loadMessageReasoner(inputs.map(([path, text]) => [text, path === '-' ? '<stdin>' : path]), io, { base, ...rdfLogic, ...shapes });
184
+ reasoner ??= loadMessageReasoner(inputs.map(([path, text]) => [text, path === '-' ? '<stdin>' : path]), io, { base, ...rdfLogic, ...shapes, limits: { ...COMPILED_LIMITS, ...options } });
185
185
  const result = reasoner.infer(message.quads, { ...COMPILED_LIMITS, ...options });
186
186
  messageNumber++;
187
187
  if (printProgram) {
package/src/formats.js CHANGED
@@ -108,7 +108,7 @@ export function loadMessageReasoner(inputs, io = null, options = {}) {
108
108
  }
109
109
  }
110
110
 
111
- function load(inputs, io, { base = null, messageInputs = null, srlContext = null, odrl = false, owl2rl = false, qudt = false, skos = false, shacl = false, messages = false, shaclIn = null, shaclOut = null }) {
111
+ function load(inputs, io, { base = null, messageInputs = null, srlContext = null, odrl = false, owl2rl = false, qudt = false, skos = false, shacl = false, messages = false, shaclIn = null, shaclOut = null, limits = {} }) {
112
112
  const options = { owl2rl, qudt, skos, shacl }, profiles = RDF_PROFILES.filter((p) => options[p]);
113
113
  const switches = profiles.map((p) => '--' + p).join(' ');
114
114
  const kinds = inputs.map(([text, name]) => messageInputs?.has(name) ||
@@ -132,12 +132,13 @@ function load(inputs, io, { base = null, messageInputs = null, srlContext = null
132
132
  // SHACL shapes as contracts: what messages hold, and what is wanted.
133
133
  const shapes = ([text, name]) => parseRdf(text, { format: rdfFormat(name) ?? 'turtle', base: baseOf(name) }).quads;
134
134
  if (shaclOut) graph.wanted = [...graph.wanted ?? [], ...shaclOut.flatMap((input) => shaclOutPatterns(shapes(input), input[1]))];
135
+ graph.planned = Boolean(shaclIn || shaclOut);
135
136
  if (shaclIn) {
136
137
  const read = shaclIn.map((input) => shaclInPatterns(shapes(input), input[1]));
137
138
  const closed = read.every((r) => r.allowed);
138
139
  graph.expected = { patterns: read.flatMap((r) => r.patterns), allowed: closed ? new Set(read.flatMap((r) => [...r.allowed])) : null };
139
140
  }
140
- if (messages) return messageReasoner(graph, { profiles, source });
141
+ if (messages) return messageReasoner(graph, { profiles, source, limits });
141
142
  return compileRdfLogic(graph, { profiles, source, context: srlContext });
142
143
  }
143
144
  if (odrl) {
package/src/rdf-logic.js CHANGED
@@ -12,7 +12,8 @@ import { executionContext } from './srl.js';
12
12
  import { rdfValueRules } from './rdf-values.js';
13
13
  import { run } from './engine.js';
14
14
  import { Specializer, shape } from './specialize.js';
15
- import { Env, EyemindError, Struct, Var, freshTerm, identity, unify } from './terms.js';
15
+ import { Env, EyemindError, Struct, Var, freshTerm, identity, key, unify } from './terms.js';
16
+ import { CONTROL_KEYS, Program } from './program.js';
16
17
 
17
18
  export const ENTAILMENT = 'https://eyereasoner.github.io/eyemind/entailment#';
18
19
  export const RDF_PROFILES = ['owl2rl', 'qudt', 'skos', 'shacl'];
@@ -86,6 +87,12 @@ function shapePatterns(quads, name, input) {
86
87
  if (kind === 'IRI') return [iri()];
87
88
  if (kind === 'BlankNode') return [bnode()];
88
89
  if (kind === 'BlankNodeOrIRI' || (!kind && values(node, SH + 'class').length)) return [iri(), bnode()];
90
+ // A message literal is a literal term; an integer, which is a number
91
+ // term, then does not conform. An output contract asks for any literal.
92
+ const literal = () => input ? new Struct('literal', [any(), any()]) : any();
93
+ if (kind === 'Literal') return [literal()];
94
+ if (kind === 'IRIOrLiteral') return [iri(), literal()];
95
+ if (kind === 'BlankNodeOrLiteral') return [bnode(), literal()];
89
96
  return [any()];
90
97
  };
91
98
  // The predicates of a path, and whether it is a predicate or its inverse.
@@ -146,6 +153,147 @@ export const shaclIn = (quads, name) => shapePatterns(quads, name, true);
146
153
  // triples, of the values they allow.
147
154
  export const shaclOut = (quads, name) => shapePatterns(quads, name, false).patterns;
148
155
 
156
+ const RDF_TYPE = RDF + 'type';
157
+ const RDFS = 'http://www.w3.org/2000/01/rdf-schema#', OWL = 'http://www.w3.org/2002/07/owl#';
158
+ // Schema properties and property types whose rules can only fire when the
159
+ // background has them.
160
+ const SCHEMA = new Set([...['domain', 'range', 'subClassOf', 'subPropertyOf'].map((n) => RDFS + n),
161
+ ...['equivalentClass', 'equivalentProperty', 'inverseOf', 'propertyChainAxiom', 'intersectionOf', 'unionOf', 'oneOf',
162
+ 'members', 'distinctMembers', 'hasKey', 'onProperty', 'onClass', 'onDataRange', 'someValuesFrom', 'allValuesFrom',
163
+ 'hasValue', 'maxCardinality', 'maxQualifiedCardinality', 'complementOf', 'disjointWith', 'disjointUnionOf',
164
+ 'datatypeComplementOf'].map((n) => OWL + n)]);
165
+ const TYPE_GUARDS = new Set(['FunctionalProperty', 'InverseFunctionalProperty', 'TransitiveProperty', 'SymmetricProperty',
166
+ 'AsymmetricProperty', 'IrreflexiveProperty', 'ReflexiveProperty', 'AllDifferent', 'AllDisjointClasses',
167
+ 'AllDisjointProperties'].map((n) => OWL + n));
168
+ const QUADS = new Set(['rdf/4', 'ent_base/4']);
169
+
170
+ // The rules for messages that trusted SHACL shapes plan, at the level of
171
+ // properties and classes: a rule whose schema premise the background lacks
172
+ // is left out; with input shapes, only rules whose premises can match a
173
+ // property or class of the background, the messages or a kept rule's
174
+ // conclusion are kept; with output shapes, only rules concluding a property
175
+ // or class asked for, or one a kept rule reads. A relation other than a
176
+ // triple counts as a property of its own. Facts and backward rules stay.
177
+ export function planRules(program, quads, { input = null, output = null }) {
178
+ const named = (t) => t instanceof Struct && t.name === 'iri' && typeof t.args[0] === 'string' ? t.args[0] : null;
179
+ const describe = (goals, into) => {
180
+ for (const goal of goals) {
181
+ if (!(goal instanceof Struct)) continue;
182
+ const k = key(goal);
183
+ if (CONTROL_KEYS.has(k)) { describe(goal.args, into); continue; }
184
+ if (!QUADS.has(k)) { into.predicates.add('#' + k); continue; }
185
+ const p = named(goal.args[1]);
186
+ if (p === null) { into.variable = true; continue; }
187
+ if (p === RDF_TYPE && named(goal.args[2])) into.classes.add(named(goal.args[2]));
188
+ else into.predicates.add(p);
189
+ }
190
+ return into;
191
+ };
192
+ const entry = () => ({ predicates: new Set(), classes: new Set(), variable: false });
193
+ // The values a variable takes in a schema premise, such as P2 in
194
+ // rdf(P1, rdfs:subPropertyOf, P2), from the background's triples of that
195
+ // property, as partial evaluation makes them; null for no such premise.
196
+ const values = (variable, body) => {
197
+ for (const goal of body) {
198
+ if (!(goal instanceof Struct) || !QUADS.has(key(goal))) continue;
199
+ const p = named(goal.args[1]);
200
+ const at = [0, 2].find((i) => goal.args[i] instanceof Var && goal.args[i].name === variable.name);
201
+ if (p === null || p === RDF_TYPE || at === undefined) continue;
202
+ return [...new Set(quads.filter((quad) => named(quad[1]) === p).map((quad) => named(quad[at])).filter(Boolean))];
203
+ }
204
+ return null;
205
+ };
206
+ // The properties and classes of goals, a variable one taking its values.
207
+ const partial = (goals, body) => {
208
+ const into = entry();
209
+ for (const goal of goals) {
210
+ if (!(goal instanceof Struct) || !QUADS.has(key(goal))) { describe([goal], into); continue; }
211
+ const [, p, o] = goal.args;
212
+ if (p instanceof Var) {
213
+ const found = values(p, body);
214
+ if (found === null) into.variable = true;
215
+ else for (const value of found) into.predicates.add(value);
216
+ } else if (named(p) === RDF_TYPE && o instanceof Var) {
217
+ const found = values(o, body);
218
+ if (found === null) into.predicates.add(RDF_TYPE);
219
+ else for (const value of found) into.classes.add(value);
220
+ } else describe([goal], into);
221
+ }
222
+ return into;
223
+ };
224
+ const rules = program.clauses.filter((c) => c.forward).map((clause) => ({ clause,
225
+ body: partial(clause.body, clause.body), head: partial(clause.heads, clause.body) }));
226
+ // What the background has, and what statically relevant rules conclude
227
+ // from it.
228
+ const known = entry();
229
+ for (const quad of quads) {
230
+ const p = named(quad[1]);
231
+ if (p === RDF_TYPE && named(quad[2])) known.classes.add(named(quad[2]));
232
+ else if (p) known.predicates.add(p);
233
+ }
234
+ for (const clause of program.clauses) if (!clause.forward && !clause.body.length) known.predicates.add('#' + key(clause.head));
235
+ const matches = (body, have) => (!body.predicates.size && !body.classes.size) ||
236
+ [...body.predicates].some((p) => have.predicates.has(p)) || [...body.classes].some((c) => have.classes.has(c));
237
+ const close = (selected, have) => {
238
+ const kept = new Set();
239
+ for (let changed = true; changed;) {
240
+ changed = false;
241
+ for (const rule of selected) {
242
+ if (kept.has(rule) || !matches(rule.body, have)) continue;
243
+ kept.add(rule);
244
+ for (const p of rule.head.predicates) have.predicates.add(p);
245
+ for (const c of rule.head.classes) have.classes.add(c);
246
+ changed = true;
247
+ }
248
+ }
249
+ return kept;
250
+ };
251
+ const staticReach = close(rules, { predicates: new Set(known.predicates), classes: new Set(known.classes) });
252
+ const background = { predicates: new Set(known.predicates), classes: new Set(known.classes) };
253
+ for (const rule of staticReach) {
254
+ for (const p of rule.head.predicates) background.predicates.add(p);
255
+ for (const c of rule.head.classes) background.classes.add(c);
256
+ }
257
+ let selected = rules.filter((rule) => [...rule.body.predicates].every((p) => !SCHEMA.has(p) || background.predicates.has(p)) &&
258
+ [...rule.body.classes].every((c) => !TYPE_GUARDS.has(c) || background.classes.has(c)));
259
+ if (input) {
260
+ const reached = close(selected, { predicates: new Set([...background.predicates, ...input.predicates]),
261
+ classes: new Set([...background.classes, ...input.classes]) });
262
+ selected = selected.filter((rule) => reached.has(rule));
263
+ }
264
+ if (output) {
265
+ const desired = { predicates: new Set(output.predicates), classes: new Set(output.classes) };
266
+ const needed = new Set();
267
+ const wanted = (head) => (head.variable && desired.predicates.size && !desired.classes.size) ||
268
+ [...head.predicates].some((p) => desired.predicates.has(p) && !(p === RDF_TYPE && desired.classes.size)) ||
269
+ [...head.classes].some((c) => desired.classes.has(c));
270
+ for (let changed = true; changed;) {
271
+ changed = false;
272
+ for (const rule of selected) {
273
+ if (needed.has(rule) || !wanted(rule.head)) continue;
274
+ needed.add(rule);
275
+ for (const p of rule.body.predicates) desired.predicates.add(p);
276
+ for (const c of rule.body.classes) desired.classes.add(c);
277
+ changed = true;
278
+ }
279
+ }
280
+ selected = selected.filter((rule) => needed.has(rule));
281
+ }
282
+ const keep = new Set(selected.map((rule) => rule.clause.id));
283
+ return new Program(program.sources.filter((_, i) => !program.byId.get(i + 1)?.forward || keep.has(i + 1)));
284
+ }
285
+
286
+ // The properties and classes of triple patterns.
287
+ const vocabularyOf = (patterns) => {
288
+ const into = { predicates: new Set(), classes: new Set() };
289
+ for (const pattern of patterns) {
290
+ const p = pattern.args[1]?.name === 'iri' ? pattern.args[1].args[0] : null;
291
+ if (p === RDF_TYPE && pattern.args[2]?.name === 'iri' && typeof pattern.args[2].args[0] === 'string') into.classes.add(pattern.args[2].args[0]);
292
+ else if (p !== null) into.predicates.add(p);
293
+ }
294
+ return into;
295
+ };
296
+
149
297
  // Reasoning over messages one at a time, each with the same background
150
298
  // graph: infer(quads) gives the triples a message adds to what the background
151
299
  // alone concludes. The background is closed once and the rules are
@@ -157,10 +305,13 @@ export const shaclOut = (quads, name) => shapePatterns(quads, name, false).patte
157
305
  // and, for closed shapes, the properties a kept triple has: the program for
158
306
  // conforming messages is made before the first one arrives, and a message
159
307
  // that does not conform gets one of its own shape.
160
- export function messageReasoner({ quads, prefixes, wanted = null, expected = null }, { profiles, source = '<input>' }) {
308
+ export function messageReasoner({ quads, prefixes, wanted = null, expected = null, planned = false }, { profiles, source = '<input>', limits = {} }) {
161
309
  const options = { profiles, source };
162
310
  const background = compileRdfLogic({ quads, prefixes }, { ...options, stream: true });
163
- const specializer = new Specializer(background.program, { quads: ['rdf/4', 'ent_base/4'],
311
+ // Trusted SHACL shapes plan the rules first, as rdfjs-inference-engine does.
312
+ const program = planned ? planRules(background.program, quads, { input: expected && vocabularyOf(expected.patterns),
313
+ output: wanted && vocabularyOf(wanted) }) : background.program;
314
+ const specializer = new Specializer(program, { quads: ['rdf/4', 'ent_base/4'], limits,
164
315
  wanted: wanted && wanted.flatMap((pattern) => [pattern, new Struct('ent_report', pattern.args)]) });
165
316
  // The program for the messages an input shape describes is made at once.
166
317
  if (expected) specializer.expect(expected.patterns.flatMap((pattern) => [pattern, new Struct('ent_base', pattern.args)]));
@@ -190,6 +341,14 @@ export function messageReasoner({ quads, prefixes, wanted = null, expected = nul
190
341
  return { quads: added.map((t) => t.args).filter(kept), specialized: true, stats: result.stats, haltCode: result.haltCode,
191
342
  sources: special.fresh ? special.sources : null, ...(expected ? { ...shaped, conforms: special.conforms } : {}) };
192
343
  }
344
+ if (planned) {
345
+ // The planned rules run whole over the background and the message.
346
+ alone ??= new Set(run(program, limits).derived.map((node) => identity(node.goal)));
347
+ const result = run(program.withFacts(facts), limits);
348
+ const added = result.derived.map((node) => node.goal).filter((t) => !alone.has(identity(t)) &&
349
+ (t.name === 'ent_report' || (t.name === 'rdf' && RESOURCES.has(t.args[0].name) && t.args[1].name === 'iri')));
350
+ return { quads: added.map((t) => t.args).filter(kept), specialized: false, stats: result.stats, haltCode: result.haltCode, sources: null, ...shaped };
351
+ }
193
352
  alone ??= new Set(answers(compileRdfLogic({ quads, prefixes }, options).program, limits).map(identity));
194
353
  const result = run(compileRdfLogic({ quads: [...quads, ...message], prefixes, shapes: quads }, options).program, limits);
195
354
  const added = result.conclusions.filter((t) => t instanceof Struct && t.name === 'result_rdf' && !alone.has(identity(t)));
package/src/specialize.js CHANGED
@@ -23,7 +23,7 @@
23
23
  // has restricted rules, rule templates or inspection, is not specialized.
24
24
  import { CONTROL_KEYS, Program, Source } from './program.js';
25
25
  import { run } from './engine.js';
26
- import { Env, Struct, Var, conjunction, copyResolved, deref, freshTerm, flattenConjunction, identical, identity, isGround, isTerm, key, listFromItems, unify, variables } from './terms.js';
26
+ import { Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, freshTerm, flattenConjunction, identical, identity, isGround, isTerm, key, listFromItems, unify, variables } from './terms.js';
27
27
  import { Lettering, write } from './writer.js';
28
28
 
29
29
  const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
@@ -130,10 +130,12 @@ export function programText(sources) {
130
130
  export class Specializer {
131
131
  // quads: the keys whose arguments are subject, property, object and graph.
132
132
  // wanted: patterns of the new facts asked for, or null for all; rules that
133
- // cannot contribute to one are left out.
134
- constructor(program, { quads = [], wanted = null } = {}) {
133
+ // cannot contribute to one are left out. limits bound closing the
134
+ // program's own facts, as run() takes them.
135
+ constructor(program, { quads = [], wanted = null, limits = {} } = {}) {
135
136
  this.quads = new Set(quads);
136
137
  this.wanted = wanted;
138
+ this.limits = limits;
137
139
  this.cache = new Map();
138
140
  this.reason = null;
139
141
  try {
@@ -174,7 +176,13 @@ export class Specializer {
174
176
  this.clausesOf.get(k).push(clause);
175
177
  }
176
178
  this.rules = program.clauses.filter((c) => c.forward && !c.heads.every((head) => head === 'true'));
177
- const result = run(program);
179
+ let result;
180
+ try {
181
+ result = run(program, this.limits);
182
+ } catch (error) {
183
+ if (error instanceof EyemindError) error.message = `closing the background: ${error.message}`;
184
+ throw error;
185
+ }
178
186
  if (result.haltCode !== null) throw new Unsupported('its own facts are contradictory');
179
187
  const facts = program.clauses.filter((c) => !c.forward && !c.body.length && this.data.has(key(c.head))).map((c) => c.head);
180
188
  for (const node of result.derived) if (this.data.has(key(node.goal))) facts.push(node.goal);
@@ -246,7 +254,9 @@ export class Specializer {
246
254
  }
247
255
  const conforms = this.expected === undefined ? null
248
256
  : patterns.every((pattern) => this.expected.some((expected) => key(expected) === key(pattern) && instance(expected, pattern)));
249
- const compiled = conforms ? this.declared : this.compiled(patterns);
257
+ // Without a program for the expected patterns, a conforming message gets
258
+ // one of its own shape too.
259
+ const compiled = conforms && !this.declared.reason ? this.declared : this.compiled(patterns);
250
260
  if (compiled.reason) return null;
251
261
  const fresh = !compiled.used;
252
262
  compiled.program ??= new Program(compiled.sources);
@@ -490,6 +500,14 @@ export class Specializer {
490
500
  if (TYPE_TESTS.has(goalKey)) return resolved.args[0] instanceof Var || TYPE_TESTS.get(goalKey)(resolved.args[0]);
491
501
  if (goalKey === 'and/2') return resolved.args.every((arg) => this.holds(arg, depth, env));
492
502
  if (goalKey === 'or/2') return resolved.args.some((arg) => this.holds(arg, depth, new Env()));
503
+ // Facts that cannot be new are the old ones: one of them must match, and
504
+ // when only one does, the goal is that fact.
505
+ if (this.data.has(goalKey) && !this.mayBeNew(resolved)) {
506
+ const facts = this.matches(resolved, new Env(), MANY);
507
+ if (facts === null) return true;
508
+ if (facts.length === 1) unify(resolved, facts[0], env);
509
+ return facts.length > 0;
510
+ }
493
511
  if (!this.backwardKeys.has(goalKey)) return true;
494
512
  let only = null;
495
513
  let count = 0;
@@ -501,7 +519,8 @@ export class Specializer {
501
519
  if (!unify(resolved, head, local)) continue;
502
520
  if (depth && !clause.body.every((item) => this.holds(freshTerm(item, suffix, names), depth - 1, local))) continue;
503
521
  if (++count > 1) return true;
504
- only = clause.body.length ? null : copyResolved(head, local);
522
+ // Every answer is an instance of the one clause head that applies.
523
+ only = copyResolved(head, local);
505
524
  }
506
525
  if (only !== null) unify(resolved, only, env);
507
526
  return count > 0;
@@ -578,6 +597,13 @@ export class Specializer {
578
597
  const mark = env.mark();
579
598
  try {
580
599
  for (const [i, goal] of body.entries()) if (modes[i] === null && !this.holds(goal, DEPTH, env)) return;
600
+ // An old premise kept before later premises bound it reads only the
601
+ // old facts it still matches, and none ends the variant.
602
+ for (const [i, goal] of body.entries()) {
603
+ if (modes[i] !== 'old') continue;
604
+ const facts = this.matches(goal, env, MANY);
605
+ if (facts !== null && (!facts.length || !unify(goal, generalize(facts), env))) return;
606
+ }
581
607
  settled(count);
582
608
  } finally {
583
609
  env.undo(mark);
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The release this checkout is; ./release keeps it in step with package.json.
2
- export const VERSION = '0.8.15';
2
+ export const VERSION = '0.8.17';