eyemind 0.2.10 → 0.3.0

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
@@ -16,7 +16,7 @@ library and develop eyemind; the playground runs programs in your browser;
16
16
  the specification defines the language, its canonical text, the proof format
17
17
  and the C1–C8 checks. The examples are 94 runnable programs, each with a card
18
18
  deck and saved conclusions, proofs and check reports. The conformance suite
19
- has 1270 cases that test any implementation of the specification through its
19
+ has 1283 cases that test any implementation of the specification through its
20
20
  command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
21
21
 
22
22
  ```js
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.2.10
5
+ Version: eyemind 0.3.0
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
@@ -63,6 +63,7 @@ proof.
63
63
  - [10.1 Structure](#101-structure)
64
64
  - [10.2 Clause displays](#102-clause-displays)
65
65
  - [10.3 Steps](#103-steps)
66
+ - [10.4 Search certificates](#104-search-certificates)
66
67
  - [11. Proof Checking](#11-proof-checking)
67
68
  - [11.1 Reading the document](#111-reading-the-document)
68
69
  - [11.2 C1 Resolution](#112-c1-resolution)
@@ -365,8 +366,9 @@ A clause MUST be rejected when:
365
366
  - a head is not an atom or compound, or is a list, the atom `'[]'` or a
366
367
  `'.'/2` compound, which as a goal would be a conjunction (Section 4.1) and
367
368
  could never call the clause;
368
- - a head uses `step/4` or `clause/2`, reserved for proof documents, or
369
- explicitly states the reserved predicate `activated/2`;
369
+ - a head uses `step/4`, `clause/2`, `searched/2` or `derived/2`, reserved
370
+ for proof documents, or explicitly states the reserved predicate
371
+ `activated/2`;
370
372
  - a head is a primitive or control, except the head `'true'` of a query or
371
373
  `'false'` of a contradiction; `implies` MUST NOT conclude either atom;
372
374
  - a body goal is neither a variable, atom nor compound, or is an empty or
@@ -709,7 +711,7 @@ be bound first. Section 11.9 rejects certificates that bypass this boundary.
709
711
 
710
712
  Inspection uses a fixed source catalogue, so its own results do not depend on
711
713
  forward rounds. Other goals using derived patterns still participate in
712
- stratification. Negation and collection retain their explicit obligations.
714
+ stratification. Negation and collection keep their own justifications (Section 10.3).
713
715
 
714
716
  ## 7. Semantics
715
717
 
@@ -807,7 +809,8 @@ infinite closure. A finite model does not ensure search termination:
807
809
  recurs indefinitely. Exceeding a resource bound raises an error (Section
808
810
  8.3). Contradictions halt without completing the closure (Section 8.5).
809
811
  A valid proof establishes only its claims subject to its trusted boundaries
810
- (Section 11.11), not completeness of the model or the answers.
812
+ (Section 11.11), not completeness of the model or the answers. Its search
813
+ certificate settles the negations and collections it can (Section 10.4).
811
814
 
812
815
  ## 8. Evaluation and Conclusions
813
816
 
@@ -949,11 +952,16 @@ differently; they are ignored when the output is read (Section 9.1).
949
952
  When a proof is requested, each solution records how each of its goals was
950
953
  justified: by a fact or rule of the program, by a derived fact (whose own
951
954
  record is kept), by a primitive, by a control, by an absence (a negation) or
952
- by a collection (`findall`). For each conclusion the first derivation found
953
- is recorded. A reasoner MUST check every proof it generates (Section 11)
954
- before returning it, and MUST fail with an error rather than return a proof
955
- that does not pass. A run without conclusions has a proof without claims,
956
- which is valid and certifies nothing.
955
+ by a collection (`findall`). For each conclusion the first derivation found is
956
+ recorded. Each negation and collection of a proof gets the search certificate
957
+ that settles it (Sections 10.4 and 11.7) whenever Section 11.7 allows one. A
958
+ table holds every answer of its call, so it can search beyond where the run
959
+ stopped, as under `once`; a boundary whose tables would meet an error, or
960
+ exceed `max_inferences` calls and answers (Section 8.3), stays trusted. A
961
+ reasoner MUST check every proof it generates (Section 11) before returning it,
962
+ and MUST fail with an error rather than return a proof that does not pass. A
963
+ run without conclusions has a proof without claims, which is valid and
964
+ certifies nothing.
957
965
 
958
966
  A goal such as `is_var(X)` followed by `unify(X, 'a')`
959
967
  cannot be recorded faithfully by its final substitution, so such a run
@@ -1096,13 +1104,16 @@ A proof document is a document (Section 9.1) holding, in this order:
1096
1104
  increasing `N`;
1097
1105
  4. an empty line;
1098
1106
  5. when there are steps, comment lines saying what a step records, then one
1099
- `step(Goal, By, Bindings, Uses)` per justified goal.
1107
+ `step(Goal, By, Bindings, Uses)` per justified goal;
1108
+ 6. when it has a search certificate (Section 10.4), an empty line, comment
1109
+ lines introducing it, then one `derived(Pattern, Facts)` per listed
1110
+ relation, then one `searched(Call, Answers)` per table.
1100
1111
 
1101
1112
  Comments are informative and MAY be worded differently; they are ignored when
1102
1113
  the document is read.
1103
1114
 
1104
- A checker MUST treat every statement that is neither `clause/2` nor `step/4`
1105
- as a claim, whatever its position.
1115
+ A checker MUST treat every statement that is neither `clause/2`, `step/4`,
1116
+ `searched/2` nor `derived/2` as a claim, whatever its position.
1106
1117
 
1107
1118
  ### 10.2 Clause displays
1108
1119
 
@@ -1146,8 +1157,8 @@ order. `By` is one of:
1146
1157
  | `source(N)` | `Goal` is an instance of the inspectable source rule `N` as `implies(Body, Head)` or `implied_by(Head, Body)`. | empty | empty |
1147
1158
  | `'builtin'` | `Goal` is a primitive that holds. | empty | empty |
1148
1159
  | `'control'` | `Goal` is `call`, `once` or a disjunction, solved by `Uses`. | empty | the solved goals; for a disjunction, the side that was solved, so `or(or(A, B), C)` solved by `A` uses `or(A, B)`, which has a step of its own |
1149
- | `'absent'` | `Goal` is a negation taken on trust. | empty | empty |
1150
- | `'collected'` | `Goal` is a `findall` taken on trust. | empty | empty |
1160
+ | `'absent'` | `Goal` is a negation, settled by the search certificate or taken on trust. | empty | empty |
1161
+ | `'collected'` | `Goal` is a `findall`, settled by the search certificate or taken on trust. | empty | empty |
1151
1162
 
1152
1163
  `Bindings` is an object from each variable name of the cited clause, as
1153
1164
  the program wrote it, to its value in this step: `{X: 'socrates'}`. A key
@@ -1163,11 +1174,43 @@ empty bindings. A derived clause's bindings also include variables of its
1163
1174
  enclosing generators' scope projections, so their witnesses can be checked.
1164
1175
  These variables are renamed together with the clause's head and full body.
1165
1176
 
1177
+ ### 10.4 Search certificates
1178
+
1179
+ No step can show that a goal has no solution, or that a list holds every
1180
+ solution. A search certificate shows it by recording the searches behind a
1181
+ proof's negations and collections:
1182
+
1183
+ - `searched(Call, Answers)` is a **table**: `Call` is a goal as one of those
1184
+ searches called it, and `Answers` the array of its answers, each the
1185
+ instance of `Call` that one solution gave, in the order of Section 8.1,
1186
+ repetitions included. Each answer's variables are its own: they are shared
1187
+ neither with `Call` nor with another answer.
1188
+ - `derived(Pattern, Facts)` is a **listing**: `Pattern` is the name of a
1189
+ relation that forward rules conclude, applied to distinct variables, or the
1190
+ name alone for arity 0, and `Facts` the array of every fact the run derived
1191
+ for that relation, in the order derived (Section 8.2). Each listed fact has
1192
+ steps of its own.
1193
+
1194
+ A table exists for each call to a relation that a backward rule defines or
1195
+ forward rules conclude, made by those searches or by the closure checks of
1196
+ Section 11.7; a call to a relation defined by facts alone needs none. A
1197
+ listing exists for each relation forward rules conclude that a table or a
1198
+ closure check consults. A reasoner writes only the tables and listings of
1199
+ the boundaries it settles: listings first, in the order first consulted,
1200
+ then tables, in the order their calls are first met. For example:
1201
+
1202
+ ```js
1203
+ derived(nonpacifist(A), [nonpacifist('nixon')])
1204
+ searched(nonpacifist('ada'), [])
1205
+ ```
1206
+
1166
1207
  ## 11. Proof Checking
1167
1208
 
1168
1209
  A checker is given a program, a proof document and, when the proof answers
1169
1210
  goals asked from outside the program, those goals. It MUST NOT call a
1170
- reasoner to supply a missing step; it MAY recompute primitives. It
1211
+ reasoner to supply a missing step; it MAY recompute primitives, and it MAY
1212
+ expand a call one level against the program with every inner call answered
1213
+ by the search certificate (Section 11.7). It
1171
1214
  establishes eight conditions and records each failure with its condition, a
1172
1215
  detail and, where there is one, the term concerned.
1173
1216
 
@@ -1179,8 +1222,12 @@ program whose display (Section 10.2) is identical to `Display`, variable
1179
1222
  names included, so a display that merely renames the clause's variables
1180
1223
  differs; otherwise C1 fails. Each `step` MUST have bindings that read as a list of `'='/2` pairs,
1181
1224
  as an object literal does, and a list of uses, and no two steps may have
1182
- identical goals; otherwise C3 fails and the step is set aside. Every other
1183
- statement is a claim (Section 10.1).
1225
+ identical goals; otherwise C3 fails and the step is set aside. A `searched`
1226
+ statement MUST have a callable `Call` and an array of answers, and a
1227
+ `derived` statement a callable `Pattern` and an array of facts; no two tables
1228
+ may have calls identical up to renaming of their variables, and no two
1229
+ listings may name the same relation; otherwise C3 fails and the statement is
1230
+ set aside. Every other statement is a claim (Section 10.1).
1184
1231
 
1185
1232
  ### 11.2 C1 Resolution
1186
1233
 
@@ -1253,14 +1300,69 @@ proof fail on an implementation other than the one that made it.
1253
1300
 
1254
1301
  ### 11.7 C6 Boundary consistency
1255
1302
 
1256
- A trusted boundary cannot be proved, but the evidence at hand can refute it.
1257
- The evidence for a goal is: when the goal is a ground primitive, the goal
1258
- itself if it holds, and otherwise the recomputed fact that it fails; when it
1259
- is a control, none, and the boundary is left undecided; otherwise the
1260
- program's facts and the goals of the document's steps with the same name and
1261
- arity. A goal of the last kind **has evidence** only when there is at least
1262
- one such fact or step goal; with none, nothing could refute the boundary, and
1263
- it is left undecided.
1303
+ A negation or collection is a **boundary**. A checker first tries to
1304
+ **settle** each well-formed boundary step (Section 11.4) with the search
1305
+ certificate, by searching its goal `G` as Section 8.1 does, except that:
1306
+
1307
+ - a call to a relation that a backward rule defines or forward rules
1308
+ conclude is answered by the table whose call is identical to it up to
1309
+ renaming, each answer renamed apart in turn, and a call to a relation
1310
+ defined by facts alone by those facts, in clause order;
1311
+ - a negation inside the search treats its unbound variables as anonymous.
1312
+
1313
+ The **expansion** of a call is the search of Section 8.1 taken one level:
1314
+ the facts in the listing of its relation, in order, then the program's facts
1315
+ and backward rules of that name and arity, in clause order, each rule's body
1316
+ searched in its place, inner calls answered as above. The boundary's search
1317
+ **rests on** each table and listing it consults, and on those its tables and
1318
+ the closure checks of its listings consult, transitively. The boundary is
1319
+ settled when:
1320
+
1321
+ 1. each table it rests on equals its expansion: the same number of answers,
1322
+ each identical up to renaming of variables to the answer in the same
1323
+ position;
1324
+ 2. each listing it rests on has a step for each fact, every fact of the
1325
+ listed name and arity and ground, and is **closed**: for each forward
1326
+ rule with a head of that relation, each solution of the rule's body under
1327
+ the certificate, with the rule's witnesses bound to their Skolem terms
1328
+ (Section 8.2), gives head instances of that relation that are listed or
1329
+ are ground facts of the program;
1330
+ 3. no table it rests on depends on itself through the tables its expansion
1331
+ consults;
1332
+ 4. its outcome agrees: for a negation, `G` has no solution; for a collection
1333
+ `findall(T, G, L)`, `L` is an instance of the list of the instances of
1334
+ `T`, one per solution of `G`, in order, each renamed apart;
1335
+ 5. no collection or `once` within its search, a table it rests on or a
1336
+ closure check uses a table whose answers rest on a listing, since the
1337
+ order of derived facts cannot be checked this way; and its search reaches
1338
+ no source inspection and no clause appended by a template, and it
1339
+ consults no listing whose relation a forward rule with a template head
1340
+ or captures concludes (Section 6.2).
1341
+
1342
+ For example, the absence `not(nonpacifist('ada'))` rests on the table
1343
+ `searched(nonpacifist('ada'), [])` and the listing `derived(nonpacifist(A),
1344
+ [nonpacifist('nixon')])`. The table equals its expansion: the listed fact
1345
+ does not match the call, and no backward rule defines `nonpacifist/1`. The
1346
+ listing is closed: the only rule concluding `nonpacifist/1` derives
1347
+ `nonpacifist('nixon')`, which is listed, and that fact has its own step.
1348
+
1349
+ A boundary fails C6 when its certificate is wrong: a table differs from its
1350
+ expansion, a listed fact has no step or another name or arity, a listing is
1351
+ not closed, tables depend on themselves, a search leads to an error, or a
1352
+ negation's goal has a solution. Each wrong table or listing is reported once,
1353
+ for the first boundary resting on it. A boundary whose certificate is
1354
+ missing, incomplete or not applicable under item 5, or a collection whose
1355
+ list does not agree, is not settled. A boundary that is not settled is
1356
+ trusted, including one that fails C6.
1357
+
1358
+ A trusted boundary that is not settled cannot be proved, but the evidence at
1359
+ hand can refute it. The evidence for a goal is: when the goal is a ground
1360
+ primitive, the goal itself if it holds, and otherwise the recomputed fact
1361
+ that it fails; when it is a control, none, and the boundary is left
1362
+ undecided; otherwise the program's facts and the goals of the document's
1363
+ steps with the same name and arity. A goal of the last kind **has evidence**
1364
+ only when there is at least one such fact or step goal; with none, nothing
1365
+ could refute the boundary, and it is left undecided.
1264
1366
 
1265
1367
  - An absence `not(G)` is decided when `G` is a single goal, or a ground
1266
1368
  conjunction, whose every goal has evidence. It fails C6 when every goal of
@@ -1270,7 +1372,7 @@ it is left undecided.
1270
1372
  decided when `G` is a single goal with evidence. It fails C6 when an
1271
1373
  instance of `T` for some evidence of `G` unifies with no element of `L`.
1272
1374
 
1273
- A boundary that is not refuted remains an obligation (Section 12).
1375
+ A trusted boundary that is not refuted remains an obligation (Section 12).
1274
1376
 
1275
1377
  ### 11.8 C7 Relevance
1276
1378
 
@@ -1279,7 +1381,9 @@ Otherwise the questions are, for each forward rule, each ordinary head other
1279
1381
  than `'true'`, and the rule's body as a conjunction when one of its heads is
1280
1382
  `'true'` and no claim is `'false'`. Each claim MUST be an instance of a
1281
1383
  question. Each step MUST be reachable from a conjunct of a claim through the
1282
- conjuncts of uses.
1384
+ conjuncts of uses and, from a settled boundary, through the facts of the
1385
+ listings it rests on. Each table and listing MUST be consulted by the search
1386
+ or closure check of some boundary.
1283
1387
 
1284
1388
  ### 11.9 C8 Witness integrity
1285
1389
 
@@ -1327,7 +1431,7 @@ not covered by C8.
1327
1431
  | C3 justification | steps |
1328
1432
  | C4 coverage | claims plus uses |
1329
1433
  | C5 re_decision | `'builtin'` and `'control'` steps that passed C5 |
1330
- | C6 boundary_consistency | boundaries decided |
1434
+ | C6 boundary_consistency | boundaries settled, failed or decided |
1331
1435
  | C7 relevance | claims plus steps |
1332
1436
  | C8 witness_integrity | `clause` steps with witnesses in their forward head or enclosing generators that passed C8 |
1333
1437
 
@@ -1335,7 +1439,7 @@ A check also counts the **steps** it read, the **claims**, the `clause` steps
1335
1439
  **verified** by C1, the `source` inspection steps also **verified** by C1,
1336
1440
  the `'builtin'` steps **recomputed** by C5, the
1337
1441
  `'control'` steps **composed** by C5, and the `'absent'` and `'collected'`
1338
- steps **trusted**.
1442
+ steps **trusted**, those C6 did not settle.
1339
1443
 
1340
1444
  A proof is **valid** when no condition failed. A valid proof with trusted
1341
1445
  boundaries is valid *conditional on* them.
@@ -1343,7 +1447,8 @@ boundaries is valid *conditional on* them.
1343
1447
  ### 11.11 Scope of a valid proof
1344
1448
 
1345
1449
  A valid proof establishes that each of its claims follows from the program
1346
- by the recorded steps, given its trusted boundaries. It does not establish
1450
+ by the recorded steps, given its trusted boundaries; a settled boundary is
1451
+ established by its search certificate. It does not establish
1347
1452
  that the claims are all the conclusions of the program, that the program
1348
1453
  derives no `'false'`, or that the program is the one intended: a proof MAY
1349
1454
  leave conclusions out, and a run's own proof holds exactly its conclusions.
@@ -1378,8 +1483,9 @@ and MAY be worded differently. They are ignored when the document is read.
1378
1483
  Failures are listed in the order they are found: those of reading the
1379
1484
  document (Section 11.1), in document order; C4 for each claim, in claim
1380
1485
  order; then for each step, in document order, C4 for its uses and the C1, C3,
1381
- C5 or C8 failure of its justification; C6 for each boundary, in step order;
1382
- C7 for each claim, then for each step; and C2.
1486
+ C5 or C8 failure of its justification; C6 for each boundary, in step order,
1487
+ those of its search certificate in the order found; C7 for each claim, then
1488
+ for each step, then for each table and listing, in document order; and C2.
1383
1489
 
1384
1490
  `Detail` is informative text identifying what failed; its wording is not
1385
1491
  specified. It MUST NOT affect validity, counts or the condition reported.
@@ -1622,8 +1728,8 @@ clause(1, fact(type('socrates', 'human')))
1622
1728
  clause(2, fact(subclass_of('human', 'mortal')))
1623
1729
  clause(3, implies([type(S, A), subclass_of(A, B)], type(S, B)))
1624
1730
 
1625
- // Steps: each goal, what justifies it (a clause, a builtin, a control, or an
1626
- // absence or collection taken on trust), the bindings and the goals it uses.
1731
+ // Steps: each goal, what justifies it (a clause, a builtin, a control, an
1732
+ // absence or a collection), the bindings and the goals it uses.
1627
1733
  step(type('socrates', 'mortal'), clause(3), {S: 'socrates', A: 'human', B: 'mortal'}, [type('socrates', 'human'), subclass_of('human', 'mortal')])
1628
1734
  step(type('socrates', 'human'), clause(1), {}, [])
1629
1735
  step(subclass_of('human', 'mortal'), clause(2), {}, [])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.2.10",
3
+ "version": "0.3.0",
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/closure.js ADDED
@@ -0,0 +1,409 @@
1
+ // Search certificates: what settles a negation or a collection.
2
+ //
3
+ // A negation holds when its goal has no solution, and a collection lists
4
+ // every solution; no step can show either. A search certificate can. For each
5
+ // call the search behind the boundary made, it lists every answer, in search
6
+ // order: searched(Call, Answers). For each predicate that forward rules derive
7
+ // and the search consulted, it lists every derived fact: derived(Pattern,
8
+ // Facts). A table is checked by expanding its call one level against the
9
+ // program, as a search would, with every inner call answered by the table of
10
+ // that call, so no table vouches for itself and a wrong one shows as a
11
+ // disagreement. A listing is checked by its facts' own steps, which show each
12
+ // was derived, and by closure: under the listed facts no forward rule derives
13
+ // a fact of that predicate the listing leaves out. Nothing is searched for.
14
+ //
15
+ // The order of derived facts cannot be checked this way, so a collection or
16
+ // a once/1 whose answers rest on a listing stays an obligation, and so does a
17
+ // boundary whose search reaches rule templates or inspection.
18
+ import { PRIMITIVE_KEYS, primitive } from './builtins.js';
19
+ import { freshClause, text, variant } from './common.js';
20
+ import { INSPECTION_KEYS } from './inspection.js';
21
+ import {
22
+ Env, EyemindError, Struct, Var, copyResolved, deref, flattenConjunction, freshTerm, identity, isCallable, isGround, isTerm, key,
23
+ listFromItems, unify, variables,
24
+ } from './terms.js';
25
+
26
+ // A search the certificate cannot vouch for: its boundary stays an obligation.
27
+ export class Unsettled extends Error {}
28
+
29
+ // What one expansion relied on: the tables it read, the listings it read and
30
+ // the tables whose answer order it needed.
31
+ export class Reliance {
32
+ constructor(ordered = false) {
33
+ this.tables = new Set();
34
+ this.listings = new Set();
35
+ this.ordered = new Set();
36
+ this.inner = ordered ? 1 : 0;
37
+ }
38
+ }
39
+
40
+ // Whether term is an instance of pattern, whose variables are its own.
41
+ function instanceOf(term, pattern) {
42
+ const env = new Env();
43
+ return unify(pattern, term, env) && variant(copyResolved(term, env)) === variant(term);
44
+ }
45
+
46
+ // The name and arity of every relation a forward rule concludes.
47
+ export function forwardKeys(program) {
48
+ const keys = new Set();
49
+ for (const clause of program.forward) {
50
+ for (const head of clause.plainHeads) {
51
+ if (isCallable(head) && head !== 'true' && head !== 'false') keys.add(key(head));
52
+ }
53
+ }
54
+ return keys;
55
+ }
56
+
57
+ // Settles boundaries against a source of certificate statements:
58
+ // answers(call) gives the answers listed for a call, or null; facts(goalKey)
59
+ // the facts listed for a predicate forward rules derive, or null; and
60
+ // supported(fact) whether the proof has a step for a listed fact. Tables and
61
+ // listings are checked once, however many boundaries rest on them.
62
+ export class Settler {
63
+ constructor(program, source) {
64
+ this.program = program;
65
+ this.source = source;
66
+ this.derivedKeys = forwardKeys(program);
67
+ this.tables = new Map();
68
+ this.listings = new Map();
69
+ this.serial = 0;
70
+ }
71
+
72
+ // The outcome for one negation or collection: status 'settled',
73
+ // 'unsettled' or 'failed', the failures as [detail, term] pairs, whether the
74
+ // only failure is the boundary's own result, and the tables and listings it
75
+ // rests on.
76
+ settle(boundary) {
77
+ const collecting = isTerm(boundary, 'findall', 3);
78
+ const goal = collecting ? boundary.args[1] : boundary.args[0];
79
+ const root = new Reliance(collecting);
80
+ const outcome = { status: 'settled', failures: [], boundaryOnly: false, tables: [], listings: [] };
81
+ let found = [];
82
+ try {
83
+ const env = new Env();
84
+ const copied = freshTerm(collecting ? new Struct('-', [boundary.args[0], goal]) : goal, `root${++this.serial}`);
85
+ const [template, searched] = collecting ? copied.args : [null, copied];
86
+ for (const _ of this.solve(searched, env, root)) { // eslint-disable-line no-unused-vars
87
+ found.push(collecting ? freshTerm(copyResolved(template, env), `item${++this.serial}`) : null);
88
+ if (!collecting) break;
89
+ }
90
+ } catch (error) {
91
+ if (error instanceof Unsettled) return { ...outcome, status: 'unsettled' };
92
+ if (!(error instanceof EyemindError)) throw error;
93
+ outcome.failures.push([`search certificate leads to an error: ${error.message}`, boundary]);
94
+ found = null;
95
+ }
96
+ let unsettled = false;
97
+ const tables = new Set();
98
+ const listings = new Set();
99
+ const ordered = new Set(root.ordered);
100
+ const pendingTables = [...root.tables];
101
+ const pendingListings = [];
102
+ while (pendingTables.length || pendingListings.length) {
103
+ const fromTable = pendingTables.length > 0;
104
+ const entryKey = fromTable ? pendingTables.pop() : pendingListings.pop();
105
+ const seen = fromTable ? tables : listings;
106
+ if (seen.has(entryKey)) continue;
107
+ seen.add(entryKey);
108
+ const entry = fromTable ? this.checkTable(entryKey) : this.checkListing(entryKey);
109
+ if (entry.unsettled) unsettled = true;
110
+ if (entry.failure !== null) {
111
+ // A table or listing that fails is reported for the first boundary
112
+ // resting on it; later ones fail with it, without repeating it.
113
+ if (!entry.reported) outcome.failures.push([entry.failure, entry.subject]);
114
+ entry.reported = true;
115
+ outcome.failed = true;
116
+ }
117
+ pendingTables.push(...entry.reliance.tables);
118
+ pendingListings.push(...entry.reliance.listings);
119
+ for (const item of entry.reliance.ordered) ordered.add(item);
120
+ }
121
+ outcome.tables = [...tables];
122
+ outcome.listings = [...listings];
123
+ const circular = this.circularity(tables);
124
+ if (circular !== null) {
125
+ outcome.failures.push([`search certificate is circular at ${text(circular.call)}`, circular.call]);
126
+ }
127
+ if (outcome.failures.length || outcome.failed) return { ...outcome, status: 'failed' };
128
+ if (unsettled || [...ordered].some((item) => !this.exact(item))) return { ...outcome, status: 'unsettled' };
129
+ if (!collecting && found.length) {
130
+ outcome.failures.push([`absence contradicted by its search: ${text(boundary)}`, boundary]);
131
+ return { ...outcome, status: 'failed', boundaryOnly: true };
132
+ }
133
+ // A collection's list is the search's, renamed apart, bound perhaps by
134
+ // later goals. A step shows its goal as the whole solution left it, so a
135
+ // goal a later goal instantiated may no longer be the goal searched: a
136
+ // list that disagrees is left to the evidence rather than refuted.
137
+ if (collecting && !instanceOf(boundary.args[2], listFromItems(found))) return { ...outcome, status: 'unsettled' };
138
+ return outcome;
139
+ }
140
+
141
+ // Each solution of a goal, its bindings made in env and undone before the
142
+ // next one, as a search finds them; inner calls are answered by tables.
143
+ * solve(goal, env, reliance) {
144
+ goal = deref(goal, env);
145
+ if (goal instanceof Var) throw new EyemindError('a called variable must be bound');
146
+ if (!isCallable(goal)) throw new EyemindError(`expected a callable goal, got ${text(goal)}`);
147
+ const goalKey = key(goal);
148
+ const mark = env.mark();
149
+ if (goalKey === 'and/2') {
150
+ for (const _ of this.solve(goal.args[0], env, reliance)) yield* this.solve(goal.args[1], env, reliance); // eslint-disable-line no-unused-vars
151
+ } else if (goalKey === 'or/2') {
152
+ yield* this.solve(goal.args[0], env, reliance);
153
+ yield* this.solve(goal.args[1], env, reliance);
154
+ } else if (goalKey === 'call/1') {
155
+ yield* this.solve(goal.args[0], env, reliance);
156
+ } else if (goalKey === 'once/1' || goalKey === 'not/1') {
157
+ // A negation's unbound variables stand for any value, as anonymous
158
+ // ones do; a reasoner would not have run one with a named variable.
159
+ const once = goalKey === 'once/1';
160
+ if (once) reliance.inner++;
161
+ const inner = this.solve(goal.args[0], env, reliance);
162
+ const first = inner.next();
163
+ if (once) reliance.inner--;
164
+ if (once && !first.done) yield;
165
+ inner.return();
166
+ env.undo(mark);
167
+ if (!once && first.done) yield;
168
+ } else if (goalKey === 'findall/3') {
169
+ const items = [];
170
+ reliance.inner++;
171
+ for (const _ of this.solve(goal.args[1], env, reliance)) { // eslint-disable-line no-unused-vars
172
+ items.push(freshTerm(copyResolved(goal.args[0], env), `collection${++this.serial}`));
173
+ }
174
+ reliance.inner--;
175
+ env.undo(mark);
176
+ if (unify(goal.args[2], listFromItems(items), env)) yield;
177
+ } else if (PRIMITIVE_KEYS.has(goalKey)) {
178
+ for (const _ of primitive(goal, env)) { // eslint-disable-line no-unused-vars
179
+ yield;
180
+ env.undo(mark);
181
+ }
182
+ } else if (INSPECTION_KEYS.has(goalKey)) {
183
+ throw new Unsettled();
184
+ } else if (!this.derivedKeys.has(goalKey) &&
185
+ (this.program.groups.get(goalKey) || []).every((clause) => !clause.body.length && clause.parentId === null)) {
186
+ // Facts alone are scanned where they stand, with no table needed.
187
+ yield* this.expand(goal, env, reliance);
188
+ } else {
189
+ const call = copyResolved(goal, env);
190
+ const callKey = variant(call);
191
+ let entry = this.tables.get(callKey);
192
+ if (entry === undefined) {
193
+ const answers = this.source.answers(call);
194
+ if (answers === null) throw new Unsettled();
195
+ entry = { call, answers, checked: false, failure: null, subject: call, unsettled: false, reported: false, reliance: null };
196
+ this.tables.set(callKey, entry);
197
+ }
198
+ reliance.tables.add(callKey);
199
+ if (reliance.inner) reliance.ordered.add(callKey);
200
+ for (const answer of entry.answers) {
201
+ if (unify(goal, freshTerm(answer, `answer${++this.serial}`), env)) yield;
202
+ env.undo(mark);
203
+ }
204
+ }
205
+ env.undo(mark);
206
+ }
207
+
208
+ // A call expanded one level, as a search would: the derived facts of its
209
+ // relation in the order derived, then the program's facts and backward
210
+ // rules in clause order, each rule's body solved in its place.
211
+ * expand(call, env, reliance) {
212
+ const goalKey = key(call);
213
+ const mark = env.mark();
214
+ if (this.derivedKeys.has(goalKey)) {
215
+ const facts = this.listing(goalKey);
216
+ reliance.listings.add(goalKey);
217
+ for (const fact of facts) {
218
+ if (unify(call, fact, env)) yield;
219
+ env.undo(mark);
220
+ }
221
+ }
222
+ for (const clause of this.program.groups.get(goalKey) || []) {
223
+ // A derived rule instance answers only through the run that made it.
224
+ if (clause.parentId !== null) throw new Unsettled();
225
+ const [head, body] = freshClause(clause, `clause${++this.serial}`);
226
+ if (unify(call, head, env)) yield* this.solveAll(body, 0, env, reliance);
227
+ env.undo(mark);
228
+ }
229
+ }
230
+
231
+ * solveAll(goals, index, env, reliance) {
232
+ if (index === goals.length) {
233
+ yield;
234
+ return;
235
+ }
236
+ for (const _ of this.solve(goals[index], env, reliance)) yield* this.solveAll(goals, index + 1, env, reliance); // eslint-disable-line no-unused-vars
237
+ }
238
+
239
+ listing(goalKey) {
240
+ let entry = this.listings.get(goalKey);
241
+ if (entry === undefined) {
242
+ const facts = this.source.facts(goalKey);
243
+ if (facts === null) throw new Unsettled();
244
+ entry = { facts, checked: false, failure: null, subject: null, unsettled: false, reported: false, reliance: null };
245
+ this.listings.set(goalKey, entry);
246
+ }
247
+ return entry.facts;
248
+ }
249
+
250
+ // A table holds when expanding its call gives exactly its answers, in order.
251
+ checkTable(callKey) {
252
+ const entry = this.tables.get(callKey);
253
+ if (entry.checked) return entry;
254
+ entry.checked = true;
255
+ entry.reliance = new Reliance();
256
+ try {
257
+ const call = freshTerm(entry.call, `table${++this.serial}`);
258
+ const env = new Env();
259
+ const found = [];
260
+ for (const _ of this.expand(call, env, entry.reliance)) found.push(copyResolved(call, env)); // eslint-disable-line no-unused-vars
261
+ const listed = entry.answers;
262
+ let i = 0;
263
+ while (i < found.length && i < listed.length && variant(found[i]) === variant(listed[i])) i++;
264
+ if (i < found.length && i < listed.length) {
265
+ entry.failure = `the search of ${text(entry.call)} answers ${text(found[i])} where its table lists ${text(listed[i])}`;
266
+ } else if (i < found.length) {
267
+ entry.failure = `the table of ${text(entry.call)} leaves out the answer ${text(found[i])}`;
268
+ } else if (i < listed.length) {
269
+ entry.failure = `the table of ${text(entry.call)} lists ${text(listed[i])}, which its search does not answer`;
270
+ }
271
+ } catch (error) {
272
+ if (error instanceof Unsettled) entry.unsettled = true;
273
+ else if (error instanceof EyemindError) entry.failure = `the search of ${text(entry.call)} leads to an error: ${error.message}`;
274
+ else {
275
+ // Checked again once whatever interrupted it is dealt with.
276
+ entry.checked = false;
277
+ throw error;
278
+ }
279
+ }
280
+ return entry;
281
+ }
282
+
283
+ // A listing holds when each fact has a step and no forward rule derives,
284
+ // under the listed facts, a fact of that relation it leaves out.
285
+ checkListing(goalKey) {
286
+ const entry = this.listings.get(goalKey);
287
+ if (entry.checked) return entry;
288
+ entry.checked = true;
289
+ entry.reliance = new Reliance();
290
+ const listed = new Set();
291
+ try {
292
+ for (const fact of entry.facts) {
293
+ if (!isCallable(fact) || key(fact) !== goalKey) {
294
+ entry.failure = `derived facts of ${goalKey} list ${text(fact)}`;
295
+ entry.subject = fact;
296
+ return entry;
297
+ }
298
+ // A pattern an inspection derived is not a fact closure can compare.
299
+ if (!isGround(fact)) throw new Unsettled();
300
+ if (!this.source.supported(fact)) {
301
+ entry.failure = `derived fact without a step: ${text(fact)}`;
302
+ entry.subject = fact;
303
+ return entry;
304
+ }
305
+ listed.add(identity(fact));
306
+ }
307
+ for (const rule of this.program.forward) {
308
+ if (!rule.plainHeads.some((head) => isCallable(head) && key(head) === goalKey)) continue;
309
+ if (rule.parentId !== null || rule.templates.length || rule.captures !== null) throw new Unsettled();
310
+ const missing = this.closes(rule, goalKey, listed, entry.reliance);
311
+ if (missing !== null) {
312
+ entry.failure = `derived facts of ${goalKey} leave out ${text(missing)}, which clause ${rule.id} derives`;
313
+ entry.subject = missing;
314
+ return entry;
315
+ }
316
+ }
317
+ } catch (error) {
318
+ if (error instanceof Unsettled) entry.unsettled = true;
319
+ else if (error instanceof EyemindError) entry.failure = `the closure of ${goalKey} leads to an error: ${error.message}`;
320
+ else {
321
+ entry.checked = false;
322
+ throw error;
323
+ }
324
+ }
325
+ return entry;
326
+ }
327
+
328
+ // The first conclusion of rule with key goalKey, its witnesses made as a
329
+ // forward round makes them, that is neither listed nor a ground fact of the
330
+ // program; null when there is none.
331
+ closes(rule, goalKey, listed, reliance) {
332
+ const [head, body, names] = freshClause(rule, `closure${++this.serial}`);
333
+ const witnesses = new Set(rule.witnessNames.map((name) => names.get(name).name));
334
+ const heads = flattenConjunction(head).filter((item) => isCallable(item) && key(item) === goalKey);
335
+ const env = new Env();
336
+ for (const _ of this.solveAll(body, 0, env, reliance)) { // eslint-disable-line no-unused-vars
337
+ const mark = env.mark();
338
+ if (witnesses.size) {
339
+ const values = [];
340
+ for (const variable of variables(head).values()) {
341
+ if (witnesses.has(variable.name)) continue;
342
+ const value = copyResolved(variable, env);
343
+ if (!isGround(value)) throw new Unsettled();
344
+ values.push(value);
345
+ }
346
+ const firing = listFromItems(values);
347
+ for (const name of rule.witnessNames) {
348
+ unify(names.get(name), new Struct('skolem', [BigInt(rule.id), name, firing]), env);
349
+ }
350
+ }
351
+ for (const item of heads) {
352
+ const conclusion = copyResolved(item, env);
353
+ if (!isGround(conclusion)) throw new Unsettled();
354
+ const conclusionId = identity(conclusion);
355
+ if (!listed.has(conclusionId) && !this.program.groundFactKeys.has(conclusionId)) return conclusion;
356
+ }
357
+ env.undo(mark);
358
+ }
359
+ return null;
360
+ }
361
+
362
+ // The first table found on a cycle of tables, or null: a search that met
363
+ // its own call again would never have finished.
364
+ circularity(tables) {
365
+ const state = new Map();
366
+ for (const start of tables) {
367
+ if (state.has(start)) continue;
368
+ const stack = [[start, [...this.tables.get(start).reliance.tables], 0]];
369
+ state.set(start, 'open');
370
+ while (stack.length) {
371
+ const top = stack[stack.length - 1];
372
+ if (top[2] >= top[1].length) {
373
+ state.set(top[0], 'done');
374
+ stack.pop();
375
+ continue;
376
+ }
377
+ const next = top[1][top[2]++];
378
+ if (state.get(next) === 'open') return this.tables.get(next);
379
+ if (state.has(next)) continue;
380
+ state.set(next, 'open');
381
+ const entry = this.tables.get(next);
382
+ stack.push([next, entry.reliance ? [...entry.reliance.tables] : [], 0]);
383
+ }
384
+ }
385
+ return null;
386
+ }
387
+
388
+ // Whether a table's answers keep the order a search finds them in: none of
389
+ // them, through any table it rests on, came from a listing.
390
+ exact(callKey) {
391
+ const memo = this.exactness ??= new Map();
392
+ if (memo.has(callKey)) return memo.get(callKey);
393
+ const order = [];
394
+ const pending = [callKey];
395
+ const seen = new Set();
396
+ while (pending.length) {
397
+ const item = pending.pop();
398
+ if (seen.has(item) || memo.has(item)) continue;
399
+ seen.add(item);
400
+ order.push(item);
401
+ pending.push(...this.tables.get(item).reliance.tables);
402
+ }
403
+ for (let i = order.length - 1; i >= 0; i--) {
404
+ const reliance = this.tables.get(order[i]).reliance;
405
+ memo.set(order[i], !reliance.listings.size && [...reliance.tables].every((item) => memo.get(item) !== false));
406
+ }
407
+ return memo.get(callKey);
408
+ }
409
+ }
package/src/engine.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Backward resolution, forward fixpoints and proof recording.
2
2
  import { PRIMITIVE_KEYS, primitive } from './builtins.js';
3
+ import { Reliance, Settler, Unsettled } from './closure.js';
3
4
  import { freshClause, matchHead, renaming, text, variant } from './common.js';
4
5
  import { goalTerm, subgoals } from './goals.js';
5
6
  import { INSPECTION_KEYS } from './inspection.js';
@@ -918,6 +919,123 @@ export function skolemTerms(clause, head, unresolved, env, context = null) {
918
919
  return [...unresolved.keys()].map((name) => new Struct('skolem', [BigInt(clause.id), named.get(name), argumentsList]));
919
920
  }
920
921
 
922
+ // The search certificate of a run's negations and collections. Each call
923
+ // their searches make is answered by expanding it one level, every inner call
924
+ // by its own table, so the tables cost what the searches did; the checker
925
+ // then checks each table again, and each boundary against what the run found.
926
+ // A boundary the certificate cannot settle stays an obligation; one the run
927
+ // and its certificate disagree on is an error, since a proof must not hide it.
928
+ function certify(solver, boundaries) {
929
+ const program = solver.program;
930
+ const computed = new Map();
931
+ const met = new Map();
932
+ const open = new Set();
933
+ const listed = new Map();
934
+ let budget = 0;
935
+ let depth = 0;
936
+ const settler = new Settler(program, {
937
+ answers(call) {
938
+ const callKey = variant(call);
939
+ if (computed.has(callKey)) return computed.get(callKey);
940
+ if (!met.has(callKey)) met.set(callKey, met.size);
941
+ // A search that met its own call again would not have finished, and
942
+ // one that keeps meeting new calls is cut off.
943
+ if (open.has(callKey) || ++budget > solver.maxInferences) throw new Unsettled();
944
+ // Deep searches are taken up again from an explicit stack.
945
+ if (depth >= CERTIFY_DEPTH) throw new Missing(call);
946
+ depth++;
947
+ open.add(callKey);
948
+ try {
949
+ const term = freshTerm(call, `certificate${++settler.serial}`);
950
+ const env = new Env();
951
+ const answers = [];
952
+ for (const _ of settler.expand(term, env, new Reliance())) { // eslint-disable-line no-unused-vars
953
+ if (++budget > solver.maxInferences) throw new Unsettled();
954
+ // Each answer is written with variables of its own.
955
+ answers.push(freshTerm(copyResolved(term, env), `answer${++settler.serial}`));
956
+ }
957
+ computed.set(callKey, answers);
958
+ return answers;
959
+ } catch (error) {
960
+ // A full table can search past where the run stopped, as under once/1,
961
+ // and meet an error the run never did: such a boundary stays trusted.
962
+ if (error instanceof EyemindError) throw new Unsettled();
963
+ throw error;
964
+ } finally {
965
+ depth--;
966
+ open.delete(callKey);
967
+ }
968
+ },
969
+ facts(goalKey) {
970
+ const nodes = solver.facts.get(goalKey) || NO_NODES;
971
+ if (nodes.some((node) => node.generic)) throw new Unsettled();
972
+ listed.set(goalKey, nodes);
973
+ return nodes.map((node) => node.goal);
974
+ },
975
+ supported: () => true,
976
+ });
977
+ // Answer a call too deep to reach directly, and the deeper calls it needs.
978
+ function ensure(start) {
979
+ const pending = [start];
980
+ const waiting = new Set([variant(start)]);
981
+ while (pending.length) {
982
+ const call = pending[pending.length - 1];
983
+ try {
984
+ settler.source.answers(call);
985
+ waiting.delete(variant(pending.pop()));
986
+ } catch (error) {
987
+ if (!(error instanceof Missing)) throw error;
988
+ const deeper = variant(error.call);
989
+ if (waiting.has(deeper)) throw new Unsettled();
990
+ waiting.add(deeper);
991
+ pending.push(error.call);
992
+ }
993
+ }
994
+ }
995
+ const tables = new Set();
996
+ const listings = new Set();
997
+ for (const boundary of boundaries) {
998
+ let outcome = null;
999
+ budget = 0;
1000
+ while (outcome === null) {
1001
+ try {
1002
+ outcome = settler.settle(boundary);
1003
+ } catch (error) {
1004
+ if (!(error instanceof Missing)) throw error;
1005
+ try {
1006
+ ensure(error.call);
1007
+ } catch (failure) {
1008
+ if (!(failure instanceof Unsettled)) throw failure;
1009
+ outcome = { status: 'unsettled' };
1010
+ }
1011
+ }
1012
+ }
1013
+ if (outcome.status === 'settled') {
1014
+ for (const item of outcome.tables) tables.add(item);
1015
+ for (const item of outcome.listings) listings.add(item);
1016
+ } else if (outcome.status === 'failed') {
1017
+ throw new EyemindError(`cannot certify this result: ${outcome.failures[0]?.[0] ?? 'its search certificate fails'}`);
1018
+ }
1019
+ }
1020
+ return {
1021
+ // Tables in the order their calls were first met.
1022
+ tables: [...settler.tables].filter(([callKey]) => tables.has(callKey))
1023
+ .sort(([a], [b]) => met.get(a) - met.get(b)).map(([, entry]) => [entry.call, entry.answers]),
1024
+ listings: [...settler.listings.keys()].filter((goalKey) => listings.has(goalKey)).map((goalKey) => [goalKey, listed.get(goalKey)]),
1025
+ };
1026
+ }
1027
+
1028
+ // How many calls deep a certificate's tables are made by direct recursion.
1029
+ const CERTIFY_DEPTH = 100;
1030
+
1031
+ // A call whose table is not made yet, too deep to make it directly.
1032
+ class Missing extends Error {
1033
+ constructor(call) {
1034
+ super('missing table');
1035
+ this.call = call;
1036
+ }
1037
+ }
1038
+
921
1039
  // What a run concluded. answers are the conclusions as printable text and
922
1040
  // bindings one object per answer of the goal's variables; with a proof, proof
923
1041
  // is the document and proofReport its check, clausesUsed the ids of the
@@ -1023,7 +1141,8 @@ function reason(program, goalInputs, options) {
1023
1141
  for (const [name, value] of answer) out[name] = write(value, null, lettering);
1024
1142
  return out;
1025
1143
  });
1026
- const rendered = options.proof ? renderProof(program, claims, roots, true, heading) : null;
1144
+ const rendered = options.proof
1145
+ ? renderProof(program, claims, roots, true, heading, (boundaries) => certify(solver, boundaries)) : null;
1027
1146
  const document = rendered !== null ? rendered[0] : null;
1028
1147
  // A rule that reports a claim is used by it, though a proof records only
1029
1148
  // the claim's support.
package/src/program.js CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  import { write } from './writer.js';
11
11
 
12
12
  export const CONTROL_KEYS = new Set(['and/2', 'or/2', 'not/1', 'call/1', 'once/1', 'findall/3']);
13
- export const RESERVED_KEYS = new Set(['step/4', 'clause/2', 'activated/2', 'implies/2', 'implied_by/2', 'forward/2', 'backward/2']);
13
+ export const RESERVED_KEYS = new Set(['step/4', 'clause/2', 'searched/2', 'derived/2', 'activated/2', 'implies/2', 'implied_by/2', 'forward/2', 'backward/2']);
14
14
 
15
15
  // The statements that state a forward rule, and how an error names them.
16
16
  const FORWARD_KINDS = { forward: 'a forward rule', query: 'query()', contradiction: 'contradiction()' };
package/src/proof.js CHANGED
@@ -3,20 +3,22 @@
3
3
  // A proof document is JavaScript source, one expression per line: first the
4
4
  // claims, then clause(N, Display) for every source clause the proof cites,
5
5
  // written as the program states it (fact(...), implies(...) or
6
- // implied_by(...)), then one step(Goal, By, Bindings, Uses) per inference. The
6
+ // implied_by(...)), then one step(Goal, By, Bindings, Uses) per inference,
7
+ // then the search certificate that settles its negations and collections. The
7
8
  // document reader parses it as data; it never executes it.
8
9
  //
9
10
  // Verification follows recorded uses; it never asks the solver to find a
10
11
  // missing derivation. Only pure primitives are independently recomputed.
11
12
  import { PRIMITIVE_KEYS, primitive } from './builtins.js';
12
- import { freshClause, text } from './common.js';
13
+ import { Settler } from './closure.js';
14
+ import { freshClause, text, variant } from './common.js';
13
15
  import { goalTerm } from './goals.js';
14
16
  import { INSPECTION_KEYS, isInspection } from './inspection.js';
15
17
  import { CONTROL_KEYS, Program } from './program.js';
16
18
  import { readTerms } from './reader.js';
17
19
  import {
18
20
  Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, flattenConjunction, freshTerm,
19
- isCallable, isFloat, isGround, isTerm, key, listFromItems, properListItems, unify, variables,
21
+ isCallable, isFloat, isGround, isTerm, key, keyArity, keyName, listFromItems, properListItems, unify, variables,
20
22
  } from './terms.js';
21
23
  import { Lettering, letterName, quote, write, writeNotingVariables } from './writer.js';
22
24
 
@@ -168,27 +170,46 @@ function bindingsText(bindings, lettering) {
168
170
  return `{${parts.join(', ')}}`;
169
171
  }
170
172
 
173
+ // The most general goal of a name and arity, as a listing of derived facts
174
+ // names its relation.
175
+ function relationPattern(goalKey) {
176
+ const arity = keyArity(goalKey);
177
+ if (!arity) return keyName(goalKey);
178
+ return new Struct(keyName(goalKey), Array.from({ length: arity }, (_, i) => new Var(`_relation${i}`)));
179
+ }
180
+
171
181
  // The proof document of a run's claims and their derivations, opened by
172
182
  // heading, the comment that says what the claims are. With checkable, also
173
183
  // what checkRendered() needs to check it without reading the document back:
174
184
  // the document and that, as a pair. Comments are ignored when it is read.
175
- export function renderProof(program, claims, roots, checkable = false, heading = null) {
185
+ // certify, given the goals of the negations and collections, gives their
186
+ // search certificate: [Call, Answers] tables and [Key, Nodes] listings, the
187
+ // nodes of each listed derived fact.
188
+ export function renderProof(program, claims, roots, checkable = false, heading = null, certify = null) {
176
189
  const spellings = new Spellings();
177
190
  const steps = new Map();
178
191
  const cited = new Set();
179
- const pending = [...roots].reverse();
180
- while (pending.length) {
181
- const node = pending.pop();
182
- const nodeId = spellings.spell(node.goal);
183
- if (steps.has(nodeId)) continue;
184
- steps.set(nodeId, node);
185
- if (node.by instanceof Struct) {
186
- const id = Number(node.by.args[0]);
187
- cited.add(id);
188
- for (const parent of program.byId.get(id)?.scopeIds || []) cited.add(parent);
192
+ const walk = (starts) => {
193
+ const pending = [...starts].reverse();
194
+ while (pending.length) {
195
+ const node = pending.pop();
196
+ const nodeId = spellings.spell(node.goal);
197
+ if (steps.has(nodeId)) continue;
198
+ steps.set(nodeId, node);
199
+ if (node.by instanceof Struct) {
200
+ const id = Number(node.by.args[0]);
201
+ cited.add(id);
202
+ for (const parent of program.byId.get(id)?.scopeIds || []) cited.add(parent);
203
+ }
204
+ for (let i = node.children.length - 1; i >= 0; i--) pending.push(node.children[i]);
189
205
  }
190
- for (let i = node.children.length - 1; i >= 0; i--) pending.push(node.children[i]);
191
- }
206
+ };
207
+ walk(roots);
208
+ const boundaries = [...steps.values()].filter((node) => node.by === 'absent' || node.by === 'collected')
209
+ .map((node) => node.goal);
210
+ const certificate = certify !== null && boundaries.length ? certify(boundaries) : { tables: [], listings: [] };
211
+ // A listed derived fact is shown by its own steps, after the claims' steps.
212
+ walk(certificate.listings.flatMap(([, nodes]) => nodes));
192
213
  // Variables are named A, B, ... in the order the document first shows
193
214
  // them, the claims written first, as in the run's conclusions.
194
215
  const lettering = new Lettering();
@@ -201,30 +222,47 @@ export function renderProof(program, claims, roots, checkable = false, heading =
201
222
  }
202
223
  lines.push('');
203
224
  if (steps.size) {
204
- lines.push('// Steps: each goal, what justifies it (a clause, a builtin, a control, or an',
205
- '// absence or collection taken on trust), the bindings and the goals it uses.');
225
+ lines.push('// Steps: each goal, what justifies it (a clause, a builtin, a control, an',
226
+ '// absence or a collection), the bindings and the goals it uses.');
206
227
  }
207
228
  for (const node of steps.values()) {
208
229
  const uses = `[${node.children.map((child) => spellings.lettered(child.goal, lettering)).join(', ')}]`;
209
230
  lines.push(`step(${spellings.lettered(node.goal, lettering)}, ${text(node.by)}, ` +
210
231
  `${bindingsText(node.bindings, lettering)}, ${uses})`);
211
232
  }
233
+ const read = { tables: new Map(), listings: new Map(), order: [] };
234
+ if (certificate.tables.length || certificate.listings.length) {
235
+ lines.push('', '// Search certificate: every fact derived for each relation the searches behind',
236
+ '// negations and collections consult, and every answer of each call they made, in order.');
237
+ }
238
+ for (const [goalKey, nodes] of certificate.listings) {
239
+ const facts = nodes.map((node) => node.goal);
240
+ const pattern = relationPattern(goalKey);
241
+ lines.push(spellings.lettered(new Struct('derived', [pattern, listFromItems(facts)]), lettering));
242
+ read.listings.set(goalKey, facts);
243
+ read.order.push(['listing', goalKey, pattern]);
244
+ }
245
+ for (const [call, answers] of certificate.tables) {
246
+ lines.push(spellings.lettered(new Struct('searched', [call, listFromItems(answers)]), lettering));
247
+ read.tables.set(variant(call), answers);
248
+ read.order.push(['table', variant(call), call]);
249
+ }
212
250
  const document = `${lines.join('\n')}\n`;
213
251
  if (!checkable) return document;
214
252
  // The steps as reading the document would give them: bindings as '='/2
215
253
  // pairs, uses as goals. Their variables keep the run's names, which the
216
254
  // document only spells differently, so the checks come out the same; what a
217
255
  // report shows of a term is spelled as the document spells it.
218
- const read = new Map();
256
+ const readSteps = new Map();
219
257
  for (const [nodeId, node] of steps) {
220
- read.set(nodeId, {
258
+ readSteps.set(nodeId, {
221
259
  goal: node.goal,
222
260
  by: node.by,
223
261
  bindings: node.bindings.map(([name, value]) => new Struct('=', [name, value])),
224
262
  uses: node.children.map((child) => child.goal),
225
263
  });
226
264
  }
227
- return [document, [[...claims], read, spellings, (term) => spellings.lettered(term, lettering)]];
265
+ return [document, [[...claims], readSteps, spellings, (term) => spellings.lettered(term, lettering), read]];
228
266
  }
229
267
 
230
268
  class Failures {
@@ -248,8 +286,8 @@ export function checkProof(program, document, { goals = null, allowTrusted = tru
248
286
  if (!(program instanceof Program)) throw new EyemindError('checkProof() needs a Program; load one first');
249
287
  const fail = new Failures();
250
288
  const spellings = new Spellings();
251
- const [claims, steps] = readDocument(program, document, fail, spellings);
252
- return check(program, claims, steps, goals, allowTrusted, fail, spellings, text);
289
+ const [claims, steps, certificate] = readDocument(program, document, fail, spellings);
290
+ return check(program, claims, steps, certificate, goals, allowTrusted, fail, spellings, text);
253
291
  }
254
292
 
255
293
  // Check a proof as renderProof(..., true) gave it: the report checkProof()
@@ -257,19 +295,41 @@ export function checkProof(program, document, { goals = null, allowTrusted = tru
257
295
  // checks its own proofs this way; their text is covered by the tests that
258
296
  // what is written reads back as the same terms.
259
297
  export function checkRendered(program, checkable, goals = null, allowTrusted = true) {
260
- const [claims, steps, spellings, name] = checkable;
261
- return check(program, claims, steps, goals, allowTrusted, new Failures(name), spellings, name);
298
+ const [claims, steps, spellings, name, certificate] = checkable;
299
+ return check(program, claims, steps, certificate, goals, allowTrusted, new Failures(name), spellings, name);
300
+ }
301
+
302
+ // Settle each negation and collection that is well formed by its search
303
+ // certificate (C6), before the steps are checked: a settled one is no
304
+ // obligation.
305
+ function settleBoundaries(program, steps, certificate, spellings) {
306
+ const settler = new Settler(program, {
307
+ answers: (call) => certificate.tables.get(variant(call)) ?? null,
308
+ facts: (goalKey) => certificate.listings.get(goalKey) ?? null,
309
+ supported: (fact) => steps.has(spellings.spell(fact)),
310
+ });
311
+ const outcomes = new Map();
312
+ for (const [stepId, step] of steps) {
313
+ if (isBoundary(step)) outcomes.set(stepId, settler.settle(step.goal));
314
+ }
315
+ return { settler, outcomes };
316
+ }
317
+
318
+ function isBoundary({ goal, by, bindings, uses }) {
319
+ return ((by === 'absent' && isTerm(goal, 'not', 1)) || (by === 'collected' && isTerm(goal, 'findall', 3))) &&
320
+ !bindings.length && !uses.length;
262
321
  }
263
322
 
264
- function check(program, claims, steps, goals, allowTrusted, fail, spellings, name) {
323
+ function check(program, claims, steps, certificate, goals, allowTrusted, fail, spellings, name) {
324
+ const settlement = settleBoundaries(program, steps, certificate, spellings);
265
325
  for (const claim of claims) {
266
326
  if (!flattenConjunction(claim).every((part) => steps.has(spellings.spell(part)))) {
267
327
  fail.add('C4', `unjustified claim ${text(claim)}`, claim);
268
328
  }
269
329
  }
270
- const tally = checkSteps(program, steps, allowTrusted, fail, spellings, name);
271
- const confronted = checkBoundaries(program, steps, tally.boundaries, fail);
272
- checkRelevance(program, claims, steps, goals || [], fail, spellings);
330
+ const tally = checkSteps(program, steps, allowTrusted, fail, spellings, name, settlement.outcomes);
331
+ const confronted = checkBoundaries(program, steps, tally.boundaries, fail, settlement.outcomes, spellings);
332
+ checkRelevance(program, claims, steps, goals || [], fail, spellings, settlement, certificate);
273
333
  checkWellFounded(steps, fail, spellings);
274
334
  let uses = 0;
275
335
  for (const step of steps.values()) uses += step.uses.length;
@@ -316,14 +376,20 @@ export function strict(report) {
316
376
  return { ...report, valid: !failures.length, failures, conditions, failureTerms: [...report.trustedTerms] };
317
377
  }
318
378
 
319
- // C3: split a document into claims and steps keyed by the goal's text.
379
+ // C3: split a document into claims, steps keyed by the goal's text, and the
380
+ // statements of its search certificate.
320
381
  // clause/2 records are compared with the source.
321
382
  function readDocument(program, document, fail, spellings) {
322
383
  const claims = [];
323
384
  const steps = new Map();
385
+ const certificate = { tables: new Map(), listings: new Map(), order: [] };
324
386
  const empty = new Env();
325
387
  try {
326
388
  for (const [term] of readTerms(document)) {
389
+ if (isTerm(term, 'searched', 2) || isTerm(term, 'derived', 2)) {
390
+ readCertificate(term, certificate, fail, empty);
391
+ continue;
392
+ }
327
393
  if (isTerm(term, 'clause', 2)) {
328
394
  // These display records are not authority: the source program is.
329
395
  const clause = clauseNamed(program, term.args[0]);
@@ -354,7 +420,32 @@ function readDocument(program, document, fail, spellings) {
354
420
  if (!(error instanceof EyemindError)) throw error;
355
421
  fail.add('C3', error.message);
356
422
  }
357
- return [claims, steps];
423
+ return [claims, steps, certificate];
424
+ }
425
+
426
+ // A search certificate statement: searched(Call, Answers), a table of every
427
+ // answer of a call, or derived(Pattern, Facts), every fact forward rules
428
+ // derived for the relation of Pattern.
429
+ function readCertificate(term, certificate, fail, empty) {
430
+ const [subject, list] = term.args;
431
+ const items = properListItems(list, empty);
432
+ const table = term.name === 'searched';
433
+ // A listing names its relation by the name applied to distinct variables.
434
+ const pattern = table || typeof subject === 'string' || (subject instanceof Struct &&
435
+ subject.args.every((arg, i) => arg instanceof Var && subject.args.findIndex((other) => other instanceof Var && other.name === arg.name) === i));
436
+ if (!isCallable(subject) || items === null || !pattern) {
437
+ fail.add('C3', table ? 'a search table must be searched(Goal, Answers) with an array of answers'
438
+ : 'a listing must be derived(Pattern, Facts) with an array of facts', subject);
439
+ return;
440
+ }
441
+ const entryKey = table ? variant(subject) : key(subject);
442
+ const entries = table ? certificate.tables : certificate.listings;
443
+ if (entries.has(entryKey)) {
444
+ fail.add('C3', `duplicate ${table ? 'search table' : 'listing'} for ${table ? text(subject) : entryKey}`, subject);
445
+ return;
446
+ }
447
+ entries.set(entryKey, items);
448
+ certificate.order.push([table ? 'table' : 'listing', entryKey, subject]);
358
449
  }
359
450
 
360
451
  function clauseNamed(program, id) {
@@ -368,7 +459,7 @@ const CONTROL_BY = 'control';
368
459
  // C4, C1, C3 and C5 for each step: every use is justified, and the step is an
369
460
  // instance of the clause it cites, a recomputed primitive, a control composed
370
461
  // of its uses, or a trusted boundary the later checks confront.
371
- function checkSteps(program, steps, allowTrusted, fail, spellings, name) {
462
+ function checkSteps(program, steps, allowTrusted, fail, spellings, name, outcomes) {
372
463
  const tally = { verified: 0, redecided: 0, composed: 0, witnessed: 0, boundaries: [], trusted: [] };
373
464
 
374
465
  function covered(goal) {
@@ -430,6 +521,8 @@ function checkSteps(program, steps, allowTrusted, fail, spellings, name) {
430
521
  } else if ((by === 'absent' && isTerm(goal, 'not', 1)) || (by === 'collected' && isTerm(goal, 'findall', 3))) {
431
522
  if (bindings.length || uses.length) fail.add('C3', 'trusted boundaries cannot have bindings or uses', goal);
432
523
  tally.boundaries.push(goal);
524
+ // A boundary its search certificate settles is checked, not trusted.
525
+ if (outcomes.get(spellings.spell(goal))?.status === 'settled') continue;
433
526
  tally.trusted.push([{ kind: by, conclusion: name(goal) }, goal]);
434
527
  if (!allowTrusted) fail.add('C5', `trusted boundary forbidden: ${by}`, goal);
435
528
  } else {
@@ -601,12 +694,13 @@ function checkWitnesses(clause, head, names, env) {
601
694
  return text(listFromItems(expected)) === text(firing);
602
695
  }
603
696
 
604
- // C6: a trusted boundary cannot be proved, but evidence at hand can refute
605
- // it. An absence fails when a source fact, a step of this certificate or a
606
- // recomputed primitive is a solution; a collection fails when such a solution
607
- // is missing from its list. Returns how many boundaries the evidence could
608
- // speak for.
609
- function checkBoundaries(program, steps, boundaries, fail) {
697
+ // C6: a boundary its search certificate settles holds; one whose certificate
698
+ // fails does not. Without a certificate a boundary cannot be proved, but
699
+ // evidence at hand can refute it. An absence fails when a source fact, a step
700
+ // of this certificate or a recomputed primitive is a solution; a collection
701
+ // fails when such a solution is missing from its list. Returns how many
702
+ // boundaries a certificate or the evidence could speak for.
703
+ function checkBoundaries(program, steps, boundaries, fail, outcomes, spellings) {
610
704
  const stepGoals = new Map();
611
705
  for (const step of steps.values()) {
612
706
  if (isCallable(step.goal)) {
@@ -650,6 +744,12 @@ function checkBoundaries(program, steps, boundaries, fail) {
650
744
  }
651
745
 
652
746
  for (const boundary of boundaries) {
747
+ const outcome = outcomes.get(spellings.spell(boundary));
748
+ if (outcome !== undefined && outcome.status !== 'unsettled') {
749
+ confronted++;
750
+ for (const [detail, term] of outcome.failures) fail.add('C6', detail, term);
751
+ continue;
752
+ }
653
753
  if (isTerm(boundary, 'not', 1)) {
654
754
  const parts = flattenConjunction(boundary.args[0]);
655
755
  // Without a join, only a single goal or a ground conjunction is decided.
@@ -692,7 +792,7 @@ function checkBoundaries(program, steps, boundaries, fail) {
692
792
  // C7: the certificate answers the question that was asked and carries nothing
693
793
  // beside it. A claim is an instance of a goal asked from outside, of a
694
794
  // query() goal or, for printed conclusions, of a forward head.
695
- function checkRelevance(program, claims, steps, goals, fail, spellings) {
795
+ function checkRelevance(program, claims, steps, goals, fail, spellings, settlement, certificate) {
696
796
  let serial = 0;
697
797
  const instanceOf = (claim, question) => isInstance(claim, question, `asked${++serial}`);
698
798
  const asked = goals.map(goalTerm);
@@ -721,10 +821,21 @@ function checkRelevance(program, claims, steps, goals, fail, spellings) {
721
821
  for (const use of steps.get(stepId).uses) {
722
822
  for (const part of flattenConjunction(use)) reach.push(spellings.spell(part));
723
823
  }
824
+ // A settled boundary rests on the derived facts its certificate lists.
825
+ const outcome = settlement.outcomes.get(stepId);
826
+ if (outcome?.status === 'settled') {
827
+ for (const goalKey of outcome.listings) {
828
+ for (const fact of settlement.settler.listings.get(goalKey).facts) reach.push(spellings.spell(fact));
829
+ }
830
+ }
724
831
  }
725
832
  for (const [stepId, step] of steps) {
726
833
  if (!reached.has(stepId)) fail.add('C7', `step serves no claim: ${stepId}`, step.goal);
727
834
  }
835
+ for (const [kind, entryKey, subject] of certificate.order) {
836
+ const used = kind === 'table' ? settlement.settler.tables : settlement.settler.listings;
837
+ if (!used.has(entryKey)) fail.add('C7', `search certificate serves no boundary: ${text(subject)}`, subject);
838
+ }
728
839
  }
729
840
 
730
841
  // C2: no step depends on itself, walked iteratively.
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.2.10';
2
+ export const VERSION = '0.3.0';