eyemind 0.2.10 → 0.3.1

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/src/proof.js CHANGED
@@ -1,22 +1,24 @@
1
- // Proof documents: rendering, and checking C1-C8 against the source program.
1
+ // Proof documents: rendering, and checking C1-C9 against the source program.
2
2
  //
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);
262
300
  }
263
301
 
264
- function check(program, claims, steps, goals, allowTrusted, fail, spellings, name) {
302
+ // Settle each negation and collection that is well formed by its search
303
+ // certificate (C9), 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;
321
+ }
322
+
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, closed] = 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;
@@ -283,6 +343,7 @@ function check(program, claims, steps, goals, allowTrusted, fail, spellings, nam
283
343
  { id: 'C6', name: 'boundary_consistency', covered: confronted, failed: failed('C6') },
284
344
  { id: 'C7', name: 'relevance', covered: claims.length + steps.size, failed: failed('C7') },
285
345
  { id: 'C8', name: 'witness_integrity', covered: tally.witnessed, failed: failed('C8') },
346
+ { id: 'C9', name: 'search_closure', covered: closed, failed: failed('C9') },
286
347
  ];
287
348
  return {
288
349
  valid: !fail.items.length,
@@ -316,14 +377,20 @@ export function strict(report) {
316
377
  return { ...report, valid: !failures.length, failures, conditions, failureTerms: [...report.trustedTerms] };
317
378
  }
318
379
 
319
- // C3: split a document into claims and steps keyed by the goal's text.
380
+ // C3: split a document into claims, steps keyed by the goal's text, and the
381
+ // statements of its search certificate.
320
382
  // clause/2 records are compared with the source.
321
383
  function readDocument(program, document, fail, spellings) {
322
384
  const claims = [];
323
385
  const steps = new Map();
386
+ const certificate = { tables: new Map(), listings: new Map(), order: [] };
324
387
  const empty = new Env();
325
388
  try {
326
389
  for (const [term] of readTerms(document)) {
390
+ if (isTerm(term, 'searched', 2) || isTerm(term, 'derived', 2)) {
391
+ readCertificate(term, certificate, fail, empty);
392
+ continue;
393
+ }
327
394
  if (isTerm(term, 'clause', 2)) {
328
395
  // These display records are not authority: the source program is.
329
396
  const clause = clauseNamed(program, term.args[0]);
@@ -354,7 +421,32 @@ function readDocument(program, document, fail, spellings) {
354
421
  if (!(error instanceof EyemindError)) throw error;
355
422
  fail.add('C3', error.message);
356
423
  }
357
- return [claims, steps];
424
+ return [claims, steps, certificate];
425
+ }
426
+
427
+ // A search certificate statement: searched(Call, Answers), a table of every
428
+ // answer of a call, or derived(Pattern, Facts), every fact forward rules
429
+ // derived for the relation of Pattern.
430
+ function readCertificate(term, certificate, fail, empty) {
431
+ const [subject, list] = term.args;
432
+ const items = properListItems(list, empty);
433
+ const table = term.name === 'searched';
434
+ // A listing names its relation by the name applied to distinct variables.
435
+ const pattern = table || typeof subject === 'string' || (subject instanceof Struct &&
436
+ subject.args.every((arg, i) => arg instanceof Var && subject.args.findIndex((other) => other instanceof Var && other.name === arg.name) === i));
437
+ if (!isCallable(subject) || items === null || !pattern) {
438
+ fail.add('C3', table ? 'a search table must be searched(Goal, Answers) with an array of answers'
439
+ : 'a listing must be derived(Pattern, Facts) with an array of facts', subject);
440
+ return;
441
+ }
442
+ const entryKey = table ? variant(subject) : key(subject);
443
+ const entries = table ? certificate.tables : certificate.listings;
444
+ if (entries.has(entryKey)) {
445
+ fail.add('C3', `duplicate ${table ? 'search table' : 'listing'} for ${table ? text(subject) : entryKey}`, subject);
446
+ return;
447
+ }
448
+ entries.set(entryKey, items);
449
+ certificate.order.push([table ? 'table' : 'listing', entryKey, subject]);
358
450
  }
359
451
 
360
452
  function clauseNamed(program, id) {
@@ -368,7 +460,7 @@ const CONTROL_BY = 'control';
368
460
  // C4, C1, C3 and C5 for each step: every use is justified, and the step is an
369
461
  // instance of the clause it cites, a recomputed primitive, a control composed
370
462
  // of its uses, or a trusted boundary the later checks confront.
371
- function checkSteps(program, steps, allowTrusted, fail, spellings, name) {
463
+ function checkSteps(program, steps, allowTrusted, fail, spellings, name, outcomes) {
372
464
  const tally = { verified: 0, redecided: 0, composed: 0, witnessed: 0, boundaries: [], trusted: [] };
373
465
 
374
466
  function covered(goal) {
@@ -430,6 +522,8 @@ function checkSteps(program, steps, allowTrusted, fail, spellings, name) {
430
522
  } else if ((by === 'absent' && isTerm(goal, 'not', 1)) || (by === 'collected' && isTerm(goal, 'findall', 3))) {
431
523
  if (bindings.length || uses.length) fail.add('C3', 'trusted boundaries cannot have bindings or uses', goal);
432
524
  tally.boundaries.push(goal);
525
+ // A boundary its search certificate settles is checked, not trusted.
526
+ if (outcomes.get(spellings.spell(goal))?.status === 'settled') continue;
433
527
  tally.trusted.push([{ kind: by, conclusion: name(goal) }, goal]);
434
528
  if (!allowTrusted) fail.add('C5', `trusted boundary forbidden: ${by}`, goal);
435
529
  } else {
@@ -601,12 +695,14 @@ function checkWitnesses(clause, head, names, env) {
601
695
  return text(listFromItems(expected)) === text(firing);
602
696
  }
603
697
 
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) {
698
+ // C9 and C6. A boundary its search certificate settles holds, and one whose
699
+ // certificate is wrong fails C9. Without a settling certificate a boundary
700
+ // cannot be proved, but evidence at hand can refute it (C6). An absence fails
701
+ // when a source fact, a step of this certificate or a recomputed primitive is
702
+ // a solution; a collection fails when such a solution is missing from its
703
+ // list. Returns how many boundaries the evidence could speak for, and how
704
+ // many their certificates settled or refuted.
705
+ function checkBoundaries(program, steps, boundaries, fail, outcomes, spellings) {
610
706
  const stepGoals = new Map();
611
707
  for (const step of steps.values()) {
612
708
  if (isCallable(step.goal)) {
@@ -617,6 +713,7 @@ function checkBoundaries(program, steps, boundaries, fail) {
617
713
  }
618
714
  let serial = 0;
619
715
  let confronted = 0;
716
+ let closed = 0;
620
717
  const nextSerial = () => ++serial;
621
718
 
622
719
  // Each solution of a simple goal that the evidence shows, or null when the
@@ -650,6 +747,12 @@ function checkBoundaries(program, steps, boundaries, fail) {
650
747
  }
651
748
 
652
749
  for (const boundary of boundaries) {
750
+ const outcome = outcomes.get(spellings.spell(boundary));
751
+ if (outcome !== undefined && outcome.status !== 'unsettled') {
752
+ closed++;
753
+ for (const [detail, term] of outcome.failures) fail.add('C9', detail, term);
754
+ continue;
755
+ }
653
756
  if (isTerm(boundary, 'not', 1)) {
654
757
  const parts = flattenConjunction(boundary.args[0]);
655
758
  // Without a join, only a single goal or a ground conjunction is decided.
@@ -686,13 +789,13 @@ function checkBoundaries(program, steps, boundaries, fail) {
686
789
  }
687
790
  }
688
791
  }
689
- return confronted;
792
+ return [confronted, closed];
690
793
  }
691
794
 
692
795
  // C7: the certificate answers the question that was asked and carries nothing
693
796
  // beside it. A claim is an instance of a goal asked from outside, of a
694
797
  // query() goal or, for printed conclusions, of a forward head.
695
- function checkRelevance(program, claims, steps, goals, fail, spellings) {
798
+ function checkRelevance(program, claims, steps, goals, fail, spellings, settlement, certificate) {
696
799
  let serial = 0;
697
800
  const instanceOf = (claim, question) => isInstance(claim, question, `asked${++serial}`);
698
801
  const asked = goals.map(goalTerm);
@@ -721,10 +824,21 @@ function checkRelevance(program, claims, steps, goals, fail, spellings) {
721
824
  for (const use of steps.get(stepId).uses) {
722
825
  for (const part of flattenConjunction(use)) reach.push(spellings.spell(part));
723
826
  }
827
+ // A settled boundary rests on the derived facts its certificate lists.
828
+ const outcome = settlement.outcomes.get(stepId);
829
+ if (outcome?.status === 'settled') {
830
+ for (const goalKey of outcome.listings) {
831
+ for (const fact of settlement.settler.listings.get(goalKey).facts) reach.push(spellings.spell(fact));
832
+ }
833
+ }
724
834
  }
725
835
  for (const [stepId, step] of steps) {
726
836
  if (!reached.has(stepId)) fail.add('C7', `step serves no claim: ${stepId}`, step.goal);
727
837
  }
838
+ for (const [kind, entryKey, subject] of certificate.order) {
839
+ const used = kind === 'table' ? settlement.settler.tables : settlement.settler.listings;
840
+ if (!used.has(entryKey)) fail.add('C7', `search certificate serves no boundary: ${text(subject)}`, subject);
841
+ }
728
842
  }
729
843
 
730
844
  // C2: no step depends on itself, walked iteratively.
@@ -812,8 +926,8 @@ export function checkReport(report) {
812
926
  : report.trusted.length ? '// Answers checked subject to the obligations below.'
813
927
  : '// Checked answers: these follow from the input program.';
814
928
  const lines = [heading, ...report.answers, '',
815
- '// C1-C8: resolution, acyclicity, justification, coverage,',
816
- '// re-decision, boundary consistency, relevance and witness integrity.'];
929
+ '// C1-C9: resolution, acyclicity, justification, coverage, re-decision,',
930
+ '// boundary consistency, relevance, witness integrity and search closure.'];
817
931
  let previous = null;
818
932
  for (const fact of facts) {
819
933
  if (fact.name === 'failure' && previous !== 'failure') {
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.1';