eyemind 0.5.32 → 0.6.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/src/proof.js CHANGED
@@ -1,29 +1,25 @@
1
- // Proof documents: rendering and checking C1-C10 against the source program.
1
+ // Proof documents: rendering, and checking them against the source program.
2
2
  //
3
3
  // A proof document is JavaScript source, one expression per line: first the
4
- // claims, then clause(N, Display) for every source clause the proof cites,
5
- // written as the program states it (fact(...), implies(...) or
6
- // implied_by(...)), then one step(Goal, By, Bindings, Uses) per inference,
7
- // then the search certificate that settles its negations and collections. The
8
- // document reader parses it as data; it never executes it.
9
- // Native N3 and SRL documents decode to these same records and validate their
10
- // displayed evidence before the unchanged C1–C10 checks consume it.
4
+ // claims, then one step(Goal, By, Bindings, Uses) per recorded inference a
5
+ // derived fact rests on, then the certificate: derived(Pattern, Facts)
6
+ // listings of derived facts and called(Call, Answers) tables of every answer
7
+ // of a call. The document reader parses it as data; it never executes it.
11
8
  //
12
- // Verification follows recorded uses; it never asks the solver to find a
13
- // missing derivation. Only pure primitives are independently recomputed.
14
- import { PRIMITIVE_KEYS, STATE_TESTS, primitive } from './builtins.js';
15
- import { Settler } from './closure.js';
16
- import { freshClause, text, variant } from './common.js';
17
- import { goalTerm } from './goals.js';
18
- import { checkCalls } from './fidelity.js';
19
- import { INSPECTION_KEYS, isInspection } from './inspection.js';
20
- import { CONTROL_KEYS, Program } from './program.js';
9
+ // Checking answers the original questions from the certificate, each table
10
+ // checked against the source program, and replays every derived fact the
11
+ // answers rest on from its recorded firing (fidelity.js). It never asks the
12
+ // solver to find a missing derivation, and every step, table and listing must
13
+ // be used by the check.
14
+ import { text, variant } from './common.js';
15
+ import { checkAnswers } from './fidelity.js';
16
+ import { Program } from './program.js';
21
17
  import {
22
- Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, flattenConjunction, freshTerm,
23
- isCallable, isCollection, isFloat, isGround, isTerm, key, keyArity, keyName, listFromItems, properListItems, unify, variables,
18
+ Env, EyemindError, Struct, Var, flattenConjunction, isCallable, isGround, isTerm, key, keyArity, keyName, listFromItems,
19
+ properListItems, variables,
24
20
  } from './terms.js';
25
21
  import { readTerms } from './reader.js';
26
- import { Lettering, letterName, quote, write, writeNotingVariables } from './writer.js';
22
+ import { Lettering, quote, write, writeNotingVariables } from './writer.js';
27
23
 
28
24
  // Several goals or conclusions are displayed as an array, as a program
29
25
  // states them; a single one as itself.
@@ -51,86 +47,6 @@ export function clauseDisplay(clause) {
51
47
  return new Struct('fact', [clause.head]);
52
48
  }
53
49
 
54
- function sameValue(a, b) {
55
- // Identical means the same canonical text: 0.0 and -0.0 differ.
56
- return typeof a === 'number' ? Object.is(a, b) : a === b;
57
- }
58
-
59
- // Whether term, read through env, is exactly target, variables included.
60
- // The functions whose float results may differ between hosts' math libraries
61
- // (SPEC Section 13), and how far apart, in units in the last place, a claimed
62
- // result of one of them may be from the recomputed one (Section 11.8).
63
- const HOST_MATH = new Set(['exp', 'log', 'log2', 'log10', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2',
64
- 'sinh', 'cosh', 'tanh', 'pow']);
65
- const HOST_MATH_ULPS = 4n;
66
-
67
- function usesHostMath(expression) {
68
- const pending = [expression];
69
- while (pending.length) {
70
- const term = pending.pop();
71
- if (!(term instanceof Struct)) continue;
72
- if (HOST_MATH.has(term.name)) return true;
73
- pending.push(...term.args);
74
- }
75
- return false;
76
- }
77
-
78
- // A float's position among all floats, so that adjacent floats differ by one.
79
- const BITS = new DataView(new ArrayBuffer(8));
80
- function floatPosition(value) {
81
- BITS.setFloat64(0, value);
82
- const bits = BITS.getBigInt64(0);
83
- return bits < 0n ? -(bits & 0x7fffffffffffffffn) : bits;
84
- }
85
-
86
- // is(Claimed, Expression) with a float claimed for an expression that uses
87
- // host math agrees when the recomputed float lies within HOST_MATH_ULPS of it.
88
- function nearHostMath(goal) {
89
- if (!isTerm(goal, 'is', 2) || !isFloat(goal.args[0]) || !usesHostMath(goal.args[1])) return false;
90
- const result = new Var('Result');
91
- const env = new Env();
92
- try {
93
- for (const solution of primitive(new Struct('is', [result, goal.args[1]]), env)) {
94
- const value = deref(result, solution);
95
- if (!isFloat(value)) return false;
96
- const distance = floatPosition(value) - floatPosition(goal.args[0]);
97
- return (distance < 0n ? -distance : distance) <= HOST_MATH_ULPS;
98
- }
99
- } catch (error) {
100
- if (!(error instanceof EyemindError)) throw error;
101
- }
102
- return false;
103
- }
104
-
105
- function resolvesTo(term, env, target) {
106
- const pending = [term, target];
107
- while (pending.length) {
108
- const expected = pending.pop();
109
- let actual = pending.pop();
110
- if (actual instanceof Var) actual = deref(actual, env);
111
- if (actual instanceof Struct) {
112
- if (!(expected instanceof Struct) || actual.name !== expected.name || actual.args.length !== expected.args.length) {
113
- return false;
114
- }
115
- for (let i = actual.args.length - 1; i >= 0; i--) pending.push(actual.args[i], expected.args[i]);
116
- } else if (actual instanceof Var) {
117
- if (!(expected instanceof Var) || actual.name !== expected.name) return false;
118
- } else if (expected instanceof Struct || expected instanceof Var || typeof actual !== typeof expected ||
119
- !sameValue(actual, expected)) {
120
- return false;
121
- }
122
- }
123
- return true;
124
- }
125
-
126
- // Whether goal is an instance of pattern: a copy of pattern renamed with
127
- // suffix matches goal without binding any variable of goal.
128
- function isInstance(goal, pattern, suffix) {
129
- const renamed = freshTerm(pattern, suffix);
130
- const env = new Env();
131
- return unify(renamed, goal, env) && resolvesTo(renamed, env, goal);
132
- }
133
-
134
50
  // The canonical text of terms, written once per term object. A proof names
135
51
  // most goals several times, as a step and as a use, and the checks look each
136
52
  // up more than once; the text is the same every time.
@@ -181,101 +97,68 @@ function relationPattern(goalKey) {
181
97
  return new Struct(keyName(goalKey), Array.from({ length: arity }, (_, i) => new Var(`_relation${i}`)));
182
98
  }
183
99
 
184
- // The proof document of a run's claims and their derivations, opened by
185
- // heading, the comment that says what the claims are. With checkable, also
186
- // what checkRendered() needs to check it without reading the document back:
187
- // the document and that, as a pair. Comments are ignored when it is read.
188
- // certify, given the goals of the negations and collections, gives their
189
- // search certificate: [Call, Answers] tables and [Key, Nodes] listings, the
190
- // nodes of each listed derived fact.
191
- export function renderProof(program, claims, roots, checkable = false, heading = null, certify = null) {
100
+ // The proof document of a run's claims, opened by heading, the comment that
101
+ // says what the claims are. certificate holds the listings, as [Key, Nodes]
102
+ // with the nodes of each listed derived fact, the call tables, as
103
+ // [Call, Answers], and followed, the goals whose steps its replays follow:
104
+ // the steps the proof holds. firings holds the nodes of further claims to
105
+ // replay, those of a halted run. With checkable, also what checkRendered() needs to check it
106
+ // without reading the document back: the document and that, as a pair.
107
+ // Comments are ignored when it is read.
108
+ export function renderProof(program, claims, certificate, firings = [], checkable = false, heading = null) {
192
109
  const spellings = new Spellings();
193
110
  const steps = new Map();
194
- const cited = new Set();
195
- const walk = (starts, listed = false) => {
196
- const pending = [...starts].reverse();
197
- while (pending.length) {
198
- const node = pending.pop();
199
- const nodeId = spellings.spell(node.goal);
200
- if (steps.has(nodeId)) continue;
201
- // A listed derived pattern a claim's step already shows, up to the
202
- // renaming of its variables, needs no second step.
203
- if (listed && !isGround(node.goal) &&
204
- [...steps.values()].some((step) => !isGround(step.goal) && variant(step.goal) === variant(node.goal))) continue;
205
- steps.set(nodeId, node);
206
- if (isTerm(node.by, 'clause', 1) || isTerm(node.by, 'source', 1)) {
207
- const id = Number(node.by.args[0]);
208
- cited.add(id);
209
- for (const parent of program.byId.get(id)?.scopeIds || []) cited.add(parent);
210
- }
211
- for (let i = node.children.length - 1; i >= 0; i--) pending.push(node.children[i]);
212
- }
213
- };
214
- walk(roots);
215
- const boundariesOf = () => [...steps.values()].filter((node) => node.by === 'absent' || node.by === 'collected')
216
- .map((node) => node.goal);
217
- let boundaries = boundariesOf();
218
- let certificate = certify !== null ? certify(boundaries) : { tables: [], listings: [] };
219
- // A listed derived fact is shown by its own steps, after the claims' steps.
220
- // Their negations and collections need certificates too, which can list
221
- // further facts: certify again until no new boundary appears.
222
- for (;;) {
223
- walk(certificate.listings.flatMap(([, nodes]) => nodes), true);
224
- if (certify === null || boundariesOf().length === boundaries.length) break;
225
- boundaries = boundariesOf();
226
- certificate = certify(boundaries);
111
+ const seen = new Set();
112
+ const pending = [...certificate.listings.flatMap(([, nodes]) => nodes), ...firings].reverse();
113
+ while (pending.length) {
114
+ const node = pending.pop();
115
+ const nodeId = spellings.spell(node.goal);
116
+ if (steps.has(nodeId) || seen.has(node)) continue;
117
+ seen.add(node);
118
+ for (let i = node.children.length - 1; i >= 0; i--) pending.push(node.children[i]);
119
+ if (!certificate.followed.has(text(node.goal))) continue;
120
+ // A derived pattern another step already shows, up to the renaming of its
121
+ // variables, needs no second step.
122
+ if (!isGround(node.goal) &&
123
+ [...steps.values()].some((step) => !isGround(step.goal) && variant(step.goal) === variant(node.goal))) continue;
124
+ steps.set(nodeId, node);
227
125
  }
228
126
  // Variables are named A, B, ... in the order the document first shows
229
127
  // them, the claims written first, as in the run's conclusions.
230
128
  const lettering = new Lettering();
231
129
  const lines = heading === null ? [] : [heading];
232
130
  for (const claim of claims) lines.push(spellings.lettered(claim, lettering));
233
- lines.push('');
234
- if (cited.size) lines.push('// Clauses: the program clauses the steps cite, by clause number.');
235
- for (const clauseId of [...cited].sort((a, b) => a - b)) {
236
- lines.push(text(new Struct('clause', [BigInt(clauseId), clauseDisplay(program.byId.get(clauseId))])));
237
- }
238
- lines.push('');
239
131
  if (steps.size) {
240
- lines.push('// Steps: each goal, what justifies it (a clause, a builtin, a control, an',
241
- '// absence or a collection), the bindings and the goals it uses.');
132
+ lines.push('', '// Steps: each derived fact and what it rests on: the clause or control that',
133
+ '// justifies it, the bindings and the goals it uses.');
242
134
  }
243
135
  for (const node of steps.values()) {
244
136
  const uses = `[${node.children.map((child) => spellings.lettered(child.goal, lettering)).join(', ')}]`;
245
- const by = isTerm(node.by, 'called', 1) ? spellings.lettered(node.by, lettering) : text(node.by);
246
- lines.push(`step(${spellings.lettered(node.goal, lettering)}, ${by}, ` +
137
+ lines.push(`step(${spellings.lettered(node.goal, lettering)}, ${text(node.by)}, ` +
247
138
  `${bindingsText(node.bindings, lettering)}, ${uses})`);
248
139
  }
249
- const read = { tables: new Map(), calls: new Map(), listings: new Map(), order: [] };
250
- if (certificate.tables.length || certificate.listings.length || certificate.calls?.length) {
251
- lines.push('', '// Search certificate: derived facts and complete answers used to check',
252
- '// negations, collections and the original questions.');
140
+ const read = { calls: new Map(), callTerms: new Map(), listings: new Map() };
141
+ if (certificate.tables.length || certificate.listings.length) {
142
+ lines.push('', '// Certificate: the derived facts and every answer of each call the questions make.');
253
143
  }
254
144
  for (const [goalKey, nodes] of certificate.listings) {
255
145
  const facts = nodes.map((node) => node.goal);
256
- const pattern = relationPattern(goalKey);
257
- lines.push(spellings.lettered(new Struct('derived', [pattern, listFromItems(facts)]), lettering));
146
+ lines.push(spellings.lettered(new Struct('derived', [relationPattern(goalKey), listFromItems(facts)]), lettering));
258
147
  read.listings.set(goalKey, facts);
259
- read.order.push(['listing', goalKey, pattern]);
260
- }
261
- for (const [call, answers] of certificate.tables) {
262
- lines.push(spellings.lettered(new Struct('searched', [call, listFromItems(answers)]), lettering));
263
- read.tables.set(variant(call), answers);
264
- read.order.push(['table', variant(call), call]);
265
148
  }
266
- // C10 must retain the distinction between named and anonymous variables
149
+ // Call tables keep the distinction between named and anonymous variables,
267
150
  // because a named unbound variable makes a negation an error.
268
151
  const callNames = new Lettering(true);
269
- for (const [call, answers] of certificate.calls || []) {
152
+ for (const [call, answers] of certificate.tables) {
270
153
  lines.push(spellings.lettered(new Struct('called', [call, listFromItems(answers)]), callNames));
271
154
  read.calls.set(variant(call, true), answers);
272
- read.order.push(['call', variant(call, true), call]);
155
+ read.callTerms.set(variant(call, true), call);
273
156
  }
274
157
  const document = `${lines.join('\n')}\n`;
275
158
  if (!checkable) return document;
276
159
  // The steps as reading the document would give them: bindings as '='/2
277
160
  // pairs, uses as goals. Their variables keep the run's names, which the
278
- // document only spells differently, so the checks come out the same; what a
161
+ // document only spells differently, so the check comes out the same; what a
279
162
  // report shows of a term is spelled as the document spells it.
280
163
  const readSteps = new Map();
281
164
  for (const [nodeId, node] of steps) {
@@ -295,32 +178,29 @@ class Failures {
295
178
  this.name = name;
296
179
  }
297
180
 
298
- add(condition, detail, term = null) {
299
- const record = { condition, detail };
300
- if (term !== null) record.conclusion = this.name(term);
181
+ add(detail, term = null) {
301
182
  // The term itself stays out of JSON but is kept for the term report.
302
- this.items.push([record, term]);
183
+ this.items.push([detail, term]);
303
184
  }
304
185
  }
305
186
 
306
187
  // Check a proof document against the program that produced it. goals names
307
188
  // the goals the proof answers when they were asked from outside the program.
308
- // allowTrusted false rejects every unresolved obligation.
309
- export function checkProof(program, document, { goals = null, allowTrusted = true } = {}) {
189
+ export function checkProof(program, document, { goals = null } = {}) {
310
190
  if (!(program instanceof Program)) throw new EyemindError('checkProof() needs a Program; load one first');
311
191
  const fail = new Failures();
312
192
  const spellings = new Spellings();
313
- const [claims, steps, certificate] = readDocument(program, document, fail, spellings);
314
- return check(program, claims, steps, certificate, goals, allowTrusted, fail, spellings, text);
193
+ const [claims, steps, certificate] = readDocument(document, fail, spellings);
194
+ return check(program, claims, steps, certificate, goals, fail, spellings, text);
315
195
  }
316
196
 
317
197
  // Check a proof as renderProof(..., true) gave it: the report checkProof()
318
198
  // gives for its document, without reading the document back. A reasoner
319
199
  // checks its own proofs this way; their text is covered by the tests that
320
200
  // what is written reads back as the same terms.
321
- export function checkRendered(program, checkable, goals = null, allowTrusted = true) {
201
+ export function checkRendered(program, checkable, goals = null) {
322
202
  const [claims, steps, spellings, name, certificate] = checkable;
323
- return check(program, claims, steps, certificate, goals, allowTrusted, new Failures(name), spellings, name);
203
+ return check(program, claims, steps, certificate, goals, new Failures(name), spellings, name);
324
204
  }
325
205
 
326
206
  // The step of a goal: by its spelling, or for a derived pattern up to the
@@ -339,112 +219,55 @@ export function stepIdOf(steps, spellings, goal) {
339
219
  return index.get(variant(goal)) ?? stepId;
340
220
  }
341
221
 
342
- // Settle each negation and collection that is well formed by its search
343
- // certificate (C9), before the steps are checked: a settled one is no
344
- // obligation.
345
- function settleBoundaries(program, steps, certificate, spellings) {
346
- const settler = new Settler(program, {
347
- answers: (call) => certificate.tables.get(variant(call)) ?? null,
348
- facts: (goalKey) => certificate.listings.get(goalKey) ?? null,
349
- supported: (fact) => steps.has(stepIdOf(steps, spellings, fact)),
350
- });
351
- const outcomes = new Map();
222
+ function check(program, claims, steps, certificate, goals, fail, spellings, name) {
223
+ const usedSteps = new Set();
224
+ const stepOf = (goal) => {
225
+ const stepId = stepIdOf(steps, spellings, goal);
226
+ const step = steps.get(stepId);
227
+ if (step) usedSteps.add(stepId);
228
+ return step;
229
+ };
230
+ const used = checkAnswers(program, claims, goals, certificate, stepOf, fail);
231
+ // Nothing in a proof goes unchecked.
352
232
  for (const [stepId, step] of steps) {
353
- if (isBoundary(step)) outcomes.set(stepId, settler.settle(step.goal));
233
+ if (!usedSteps.has(stepId)) fail.add(`the check does not use the step of ${stepId}`, step.goal);
354
234
  }
355
- return { settler, outcomes };
356
- }
357
-
358
- function isBoundary({ goal, by, bindings, uses }) {
359
- return ((by === 'absent' && isTerm(goal, 'not', 1)) || (by === 'collected' && isCollection(goal))) &&
360
- !bindings.length && !uses.length;
361
- }
362
-
363
- function check(program, claims, steps, certificate, goals, allowTrusted, fail, spellings, name) {
364
- const settlement = settleBoundaries(program, steps, certificate, spellings);
365
- for (const claim of claims) {
366
- if (!flattenConjunction(claim).every((part) => steps.has(spellings.spell(part)))) {
367
- fail.add('C4', `unjustified claim ${text(claim)}`, claim);
368
- }
235
+ for (const [goalKey] of certificate.listings) {
236
+ if (!used.listings.has(goalKey)) fail.add(`the check does not use the derived facts of ${goalKey}`);
237
+ }
238
+ for (const [callKey, call] of certificate.callTerms) {
239
+ if (!used.tables.has(callKey)) fail.add(`the check does not use the call table of ${text(call)}`, call);
369
240
  }
370
- const provenance = new WitnessProvenance(program, steps, certificate, settlement.outcomes, spellings);
371
- const tally = checkSteps(program, steps, allowTrusted, fail, spellings, name, settlement.outcomes, provenance);
372
- const [confronted, closed] = checkBoundaries(program, steps, tally.boundaries, fail, settlement.outcomes, spellings);
373
- settlement.calls = checkCalls(program, claims, goals, certificate, steps, spellings, fail, allowTrusted, name);
374
- tally.trusted.push(...settlement.calls.unresolved);
375
- checkRelevance(program, claims, steps, goals || [], fail, spellings, settlement, certificate);
376
- checkWellFounded(steps, fail, spellings);
377
- let uses = 0;
378
- for (const step of steps.values()) uses += step.uses.length;
379
- const failed = (condition) => fail.items.filter(([record]) => record.condition === condition).length;
380
- const conditions = [
381
- { id: 'C1', name: 'resolution', covered: tally.verified, failed: failed('C1') },
382
- { id: 'C2', name: 'well_founded', covered: steps.size, failed: failed('C2') },
383
- { id: 'C3', name: 'justification', covered: steps.size, failed: failed('C3') },
384
- { id: 'C4', name: 'coverage', covered: claims.length + uses, failed: failed('C4') },
385
- { id: 'C5', name: 're_decision', covered: tally.redecided + tally.composed, failed: failed('C5') },
386
- { id: 'C6', name: 'boundary_consistency', covered: confronted, failed: failed('C6') },
387
- { id: 'C7', name: 'relevance', covered: claims.length + steps.size, failed: failed('C7') },
388
- { id: 'C8', name: 'witness_integrity', covered: tally.witnessed, failed: failed('C8') },
389
- { id: 'C9', name: 'search_closure', covered: closed, failed: failed('C9') },
390
- { id: 'C10', name: 'call_fidelity', covered: settlement.calls.covered, failed: failed('C10') },
391
- ];
392
241
  return {
393
242
  valid: !fail.items.length,
394
- steps: steps.size,
395
243
  claims: claims.length,
244
+ steps: steps.size,
396
245
  answers: claims.map((claim) => name(claim)),
397
- verified: tally.verified,
398
- redecided: tally.redecided,
399
- composed: tally.composed,
400
- uses,
401
- trusted: tally.trusted.map(([record]) => record),
402
- failures: fail.items.map(([record]) => record),
403
- conditions,
246
+ halted: claims.includes('false'),
247
+ failures: fail.items.map(([detail, term]) => (term === null ? { detail } : { detail, subject: fail.name(term) })),
404
248
  // Terms behind the records, for the term report.
405
249
  failureTerms: fail.items.map(([, term]) => term),
406
- trustedTerms: tally.trusted.map(([, term]) => term),
407
250
  };
408
251
  }
409
252
 
410
- // The verdict allowTrusted false would give, from a report without it.
411
- // Without failures, strict checking adds C5 failures for trusted boundaries
412
- // and C10 failures for unresolved original calls and questions whose
413
- // answers are not shown complete, in obligation order. It
414
- // needs no second reading. A report with failures returns null: check again.
415
- export function strict(report) {
416
- if (report.failures.length) return null;
417
- const failures = report.trusted.map((record) => ({
418
- condition: record.kind === 'call_fidelity' ? 'C10' : 'C5',
419
- detail: record.reason === 'all_answers' ? `answer completeness remains unproved: ${record.conclusion}`
420
- : record.kind === 'call_fidelity' ? `call fidelity remains unproved: ${record.conclusion}` : `trusted boundary forbidden: ${record.kind}`,
421
- conclusion: record.conclusion,
422
- }));
423
- const conditions = report.conditions.map((condition) => (
424
- ['C5', 'C10'].includes(condition.id) ? { ...condition, failed: failures.filter((failure) => failure.condition === condition.id).length } : { ...condition }));
425
- return { ...report, valid: !failures.length, failures, conditions, failureTerms: [...report.trustedTerms] };
426
- }
427
-
428
- // C3: split a document into claims, steps keyed by the goal's text, and the
429
- // statements of its search certificate.
430
- // clause/2 records are compared with the source.
431
- function readDocument(program, document, fail, spellings) {
253
+ // Split a document into claims, steps keyed by the goal's text, and the
254
+ // statements of its certificate. Every statement that is no step, listing or
255
+ // call table is a claim.
256
+ function readDocument(document, fail, spellings) {
432
257
  const claims = [];
433
258
  const steps = new Map();
434
- const certificate = { tables: new Map(), calls: new Map(), listings: new Map(), order: [] };
259
+ const certificate = { calls: new Map(), callTerms: new Map(), listings: new Map() };
435
260
  const empty = new Env();
436
261
  try {
437
262
  for (const [term] of readTerms(document)) {
438
- if (isTerm(term, 'searched', 2) || isTerm(term, 'derived', 2) || isTerm(term, 'called', 2)) {
439
- readCertificate(term, certificate, fail, empty);
263
+ // A writer names a proof's variables itself; the checker's own names,
264
+ // which mark where a variable came from, are not for a document to use.
265
+ if ([...variables(term).keys()].some((name) => name.includes('#'))) {
266
+ fail.add('a proof names its variables A, B, ... or _0, _1, ..., never with #', term);
440
267
  continue;
441
268
  }
442
- if (isTerm(term, 'clause', 2)) {
443
- // These display records are not authority: the source program is.
444
- const clause = clauseNamed(program, term.args[0]);
445
- if (clause === null || !resolvesTo(term.args[1], empty, clauseDisplay(clause))) {
446
- fail.add('C1', 'clause display differs from source', term);
447
- }
269
+ if (isTerm(term, 'derived', 2) || isTerm(term, 'called', 2)) {
270
+ readCertificate(term, certificate, fail, empty);
448
271
  continue;
449
272
  }
450
273
  if (!isTerm(term, 'step', 4)) {
@@ -455,735 +278,66 @@ function readDocument(program, document, fail, spellings) {
455
278
  const bindings = properListItems(bindingList, empty);
456
279
  const uses = properListItems(useList, empty);
457
280
  if (bindings === null || uses === null || !bindings.every((pair) => isTerm(pair, '=', 2))) {
458
- fail.add('C3', 'step bindings must be an object and uses an array', goal);
281
+ fail.add('step bindings must be an object and uses an array', goal);
459
282
  continue;
460
283
  }
461
284
  const goalId = spellings.spell(goal);
462
285
  if (steps.has(goalId)) {
463
- fail.add('C3', `duplicate justification for ${goalId}`, goal);
286
+ fail.add(`duplicate step for ${goalId}`, goal);
464
287
  continue;
465
288
  }
466
289
  steps.set(goalId, { goal, by, bindings, uses });
467
290
  }
468
291
  } catch (error) {
469
292
  if (!(error instanceof EyemindError)) throw error;
470
- fail.add('C3', error.message);
293
+ fail.add(error.message);
471
294
  }
472
295
  return [claims, steps, certificate];
473
296
  }
474
297
 
475
- // A search certificate statement: searched/2 for C9 or called/2 for C10,
476
- // each listing every answer of its call; or derived/2, listing every fact
477
- // forward rules derived for the relation of its pattern.
298
+ // A certificate statement: called/2, listing every answer of its call, or
299
+ // derived/2, listing every fact forward rules derived for the relation of
300
+ // its pattern.
478
301
  function readCertificate(term, certificate, fail, empty) {
479
302
  const [subject, list] = term.args;
480
303
  const items = properListItems(list, empty);
481
- const calling = term.name === 'called';
482
- const table = term.name === 'searched' || calling;
304
+ const table = term.name === 'called';
483
305
  // A listing names its relation by the name applied to distinct variables.
484
306
  const pattern = table || typeof subject === 'string' || (subject instanceof Struct &&
485
307
  subject.args.every((arg, i) => arg instanceof Var && subject.args.findIndex((other) => other instanceof Var && other.name === arg.name) === i));
486
308
  if (!isCallable(subject) || items === null || !pattern) {
487
- fail.add('C3', table ? `a ${calling ? 'call' : 'search'} table must be ${calling ? 'called' : 'searched'}(Goal, Answers) with an array of answers`
309
+ fail.add(table ? 'a call table must be called(Goal, Answers) with an array of answers'
488
310
  : 'a listing must be derived(Pattern, Facts) with an array of facts', subject);
489
311
  return;
490
312
  }
491
- const entryKey = table ? variant(subject, calling) : key(subject);
492
- const entries = calling ? certificate.calls : table ? certificate.tables : certificate.listings;
313
+ const entryKey = table ? variant(subject, true) : key(subject);
314
+ const entries = table ? certificate.calls : certificate.listings;
493
315
  if (entries.has(entryKey)) {
494
- fail.add('C3', `duplicate ${calling ? 'call table' : table ? 'search table' : 'listing'} for ${table ? text(subject) : entryKey}`, subject);
316
+ fail.add(`duplicate ${table ? 'call table' : 'listing'} for ${table ? text(subject) : entryKey}`, subject);
495
317
  return;
496
318
  }
497
319
  entries.set(entryKey, items);
498
- certificate.order.push([calling ? 'call' : table ? 'table' : 'listing', entryKey, subject]);
499
- }
500
-
501
- function clauseNamed(program, id) {
502
- if (typeof id !== 'bigint' || id < 1n || id > BigInt(program.maxClauseId)) return null;
503
- return program.byId.get(Number(id)) ?? null;
504
- }
505
-
506
- const BUILTIN_BY = 'builtin';
507
- const CONTROL_BY = 'control';
508
-
509
- // C4, C1, C3 and C5 for each step: every use is justified, and the step is an
510
- // instance of the clause it cites, a recomputed primitive, a control composed
511
- // of its uses, or a trusted boundary the later checks confront.
512
- function checkSteps(program, steps, allowTrusted, fail, spellings, name, outcomes, provenance) {
513
- const tally = { verified: 0, redecided: 0, composed: 0, witnessed: 0, boundaries: [], trusted: [] };
514
-
515
- function covered(goal) {
516
- if (isTerm(goal, 'and', 2)) return flattenConjunction(goal).every(covered);
517
- if (steps.has(spellings.spell(goal))) return true;
518
- // Source facts are available as leaves, including universal facts.
519
- if (!isCallable(goal)) return false;
520
- return (program.groups.get(key(goal)) || [])
521
- .some((clause) => !clause.body.length && isInstance(goal, clause.head, 'given'));
522
- }
523
-
524
- for (const step of steps.values()) {
525
- const { goal, by, bindings, uses } = step;
526
- for (const use of uses) {
527
- if (!covered(use)) fail.add('C4', `unjustified use ${text(use)}`, goal);
528
- }
529
- if (isTerm(by, 'clause', 1)) {
530
- if (checkResolution(program, step, fail, tally, provenance)) tally.verified++;
531
- } else if (isTerm(by, 'source', 1)) {
532
- const clause = clauseNamed(program, by.args[0]);
533
- const inspected = clause === null ? null : program.inspectedById.get(clause.id);
534
- if (!inspected || bindings.length || uses.length || !isInspection(goal) ||
535
- !isInstance(goal, inspected.term, 'inspection')) {
536
- fail.add('C1', `not an instance of inspectable source rule ${text(by.args[0])}: ${text(goal)}`, goal);
537
- } else tally.verified++;
538
- } else if (by === BUILTIN_BY) {
539
- if (bindings.length || uses.length || !isCallable(goal) || !PRIMITIVE_KEYS.has(key(goal))) {
540
- fail.add('C3', 'invalid builtin justification', goal);
541
- continue;
542
- }
543
- if (!redecides(goal)) fail.add('C5', `primitive disagrees: ${text(goal)}`, goal);
544
- else tally.redecided++;
545
- } else if (isTerm(by, 'called', 1)) {
546
- if (bindings.length || uses.length || !isCallable(goal) || !STATE_TESTS.has(key(goal))) {
547
- fail.add('C3', 'invalid called justification', goal);
548
- continue;
549
- }
550
- if (!redecidesCalled(goal, by.args[0])) fail.add('C5', `primitive disagrees as called: ${text(by.args[0])}`, goal);
551
- else tally.redecided++;
552
- } else if (by === CONTROL_BY) {
553
- let candidates = [];
554
- if (isTerm(goal, 'call', 1) || isTerm(goal, 'once', 1)) candidates = [goal.args[0]];
555
- else if (isTerm(goal, 'or', 2)) candidates = [...goal.args];
556
- const composes = (candidate) => {
557
- const parts = flattenConjunction(candidate);
558
- return parts.length === uses.length && parts.every((part, i) => spellings.spell(part) === spellings.spell(uses[i]));
559
- };
560
- if (bindings.length || !candidates.some(composes)) {
561
- fail.add('C5', `control step does not follow from its uses: ${text(goal)}`, goal);
562
- } else {
563
- tally.composed++;
564
- }
565
- } else if ((by === 'absent' && isTerm(goal, 'not', 1)) || (by === 'collected' && isCollection(goal))) {
566
- if (bindings.length || uses.length) {
567
- fail.add('C3', 'trusted boundaries cannot have bindings or uses', goal);
568
- continue;
569
- }
570
- tally.boundaries.push(goal);
571
- // A boundary its search certificate settles is checked, not trusted.
572
- if (outcomes.get(spellings.spell(goal))?.status === 'settled') continue;
573
- tally.trusted.push([{ kind: by, conclusion: name(goal) }, goal]);
574
- if (!allowTrusted) fail.add('C5', `trusted boundary forbidden: ${by}`, goal);
575
- } else {
576
- fail.add('C3', `unknown justification ${text(by)}`, goal);
577
- }
578
- }
579
- return tally;
580
- }
581
-
582
- function redecides(goal) {
583
- return redecidesExactly(goal) || nearHostMath(goal);
584
- }
585
-
586
- function redecidesExactly(goal) {
587
- try {
588
- for (const env of primitive(goal, new Env())) {
589
- if (resolvesTo(goal, env, goal)) return true;
590
- }
591
- } catch (error) {
592
- if (!(error instanceof EyemindError)) throw error;
593
- }
594
- return false;
595
- }
596
-
597
- // A state test recorded as called: the called goal, renamed apart, holds as
598
- // a primitive without binding anything, and the step's goal is an instance
599
- // of it, the same primitive with only its variables since bound.
600
- function redecidesCalled(goal, called) {
601
- if (!isCallable(called) || key(called) !== key(goal)) return false;
602
- const renamed = freshTerm(called, 'calledCheck');
603
- try {
604
- let holds = false;
605
- for (const env of primitive(renamed, new Env())) {
606
- holds = resolvesTo(renamed, env, renamed);
607
- break;
608
- }
609
- return holds && isInstance(goal, called, 'calledInstance');
610
- } catch (error) {
611
- if (!(error instanceof EyemindError)) throw error;
612
- return false;
613
- }
614
- }
615
-
616
- const isConstant = (term) => typeof term === 'string' || typeof term === 'bigint' || typeof term === 'number';
617
-
618
- // Shortcuts the checker may take; tests turn them off to compare with the
619
- // general path.
620
- export const shortcuts = { flatResolution: true };
621
-
622
- // Check a ground instance of a flat backward clause by substitution. null
623
- // delegates structured arguments, proof variables and forward heads to the
624
- // general unifier. Flat ground steps need neither renamed terms nor a
625
- // substitution trail: source variables can be matched directly.
626
- function flatResolution(clause, goal, bindings, uses) {
627
- if (clause.forward || clause.scopeIds.length) return null;
628
- const values = new Map();
629
- for (const binding of bindings) {
630
- if (!isTerm(binding, '=', 2) || typeof binding.args[0] !== 'string' || values.has(binding.args[0])) return false;
631
- if (!isConstant(binding.args[1])) return null;
632
- values.set(binding.args[0], binding.args[1]);
633
- }
634
- const declared = new Set(values.keys());
635
- const names = new Set();
636
- if (clause.body.length !== uses.length) return false;
637
- const patterns = [clause.head, ...clause.body];
638
- const targets = [goal, ...uses];
639
- for (let i = 0; i < patterns.length; i++) {
640
- const pattern = patterns[i];
641
- const target = targets[i];
642
- if (pattern instanceof Var || target instanceof Var) return null;
643
- if (pattern instanceof Struct && target instanceof Struct) {
644
- if (pattern.name !== target.name || pattern.args.length !== target.args.length) return false;
645
- for (let j = 0; j < pattern.args.length; j++) {
646
- let expected = pattern.args[j];
647
- const actual = target.args[j];
648
- if (expected instanceof Struct || actual instanceof Struct || actual instanceof Var) return null;
649
- if (expected instanceof Var) {
650
- names.add(expected.name);
651
- if (!values.has(expected.name)) {
652
- values.set(expected.name, actual);
653
- continue;
654
- }
655
- expected = values.get(expected.name);
656
- }
657
- if (typeof expected !== typeof actual || !sameValue(expected, actual)) return false;
658
- }
659
- } else if (pattern instanceof Struct || target instanceof Struct || typeof pattern !== typeof target ||
660
- !sameValue(pattern, target)) {
661
- return false;
662
- }
663
- }
664
- for (const name of declared) if (!names.has(name)) return false;
665
- return true;
666
- }
667
-
668
- // C1: a clause step names a source clause, its bindings name distinct
669
- // variables of that clause, and under them one of the clause's heads is the
670
- // step's goal and its body is exactly the step's uses. C8 is checked under
671
- // the same substitution.
672
- function checkResolution(program, step, fail, tally, provenance = null) {
673
- const { goal, by, bindings, uses } = step;
674
- const clauseId = by.args[0];
675
- const clause = clauseNamed(program, clauseId);
676
- if (clause === null) {
677
- fail.add('C1', `unknown clause ${text(by)}`, goal);
678
- return false;
679
- }
680
- if (clause.scopeIds.some((id) => !program.byId.has(id))) {
681
- fail.add('C1', `missing generator of clause ${clauseId}`, goal);
682
- return false;
683
- }
684
- const flat = shortcuts.flatResolution ? flatResolution(clause, goal, bindings, uses) : null;
685
- if (flat !== null) {
686
- if (!flat) fail.add('C1', `not an instance of source clause ${clauseId}: ${text(goal)}`, goal);
687
- return flat;
688
- }
689
- const [head, body, names] = freshClause(clause, `check${clauseId}`);
690
- const env = new Env();
691
- const seen = new Set();
692
- let valid = true;
693
- for (const binding of bindings) {
694
- if (!isTerm(binding, '=', 2) || typeof binding.args[0] !== 'string' || !names.has(binding.args[0]) ||
695
- seen.has(binding.args[0])) {
696
- valid = false;
697
- break;
698
- }
699
- seen.add(binding.args[0]);
700
- if (!unify(names.get(binding.args[0]), binding.args[1], env)) valid = false;
701
- }
702
- const heads = clause.forward ? flattenConjunction(head) : [head];
703
- let resolution = false;
704
- let witnesses = null;
705
- for (const candidate of heads) {
706
- const mark = env.mark();
707
- let matches = unify(candidate, goal, env) && body.length === uses.length;
708
- for (let i = 0; matches && i < body.length; i++) {
709
- if (!unify(body[i], uses[i], env)) matches = false;
710
- }
711
- if (matches && resolvesTo(candidate, env, goal) && body.every((item, i) => resolvesTo(item, env, uses[i]))) {
712
- resolution = true;
713
- // Any head the step can be an instance of decides; a verified witness wins.
714
- let found = clause.forward && provenance !== null ? checkWitnesses(clause, head, body, names, env, provenance) : null;
715
- for (const parentId of provenance === null ? [] : clause.scopeIds) {
716
- const parent = program.byId.get(parentId);
717
- const scopeHead = freshTerm(parent.head, `check${clauseId}`, names);
718
- const checked = checkWitnesses(parent, scopeHead, body.slice(0, parent.body.length), names, env, provenance);
719
- if (checked === false) found = false;
720
- else if (checked === true && found === null) found = true;
721
- }
722
- if (found !== null && witnesses !== true) witnesses = found;
723
- }
724
- env.undo(mark);
725
- }
726
- if (!valid || !resolution) {
727
- fail.add('C1', `not an instance of source clause ${clauseId}: ${text(goal)}`, goal);
728
- return false;
729
- }
730
- if (witnesses === false) fail.add('C8', `witnesses or their premise provenance do not match the source scopes of clause ${clauseId}: ${text(goal)}`, goal);
731
- else if (witnesses === true) tally.witnessed++;
732
- return true;
733
- }
734
-
735
- // C8: under a step's substitution, each witness of a forward rule is the
736
- // Skolem term of this firing, skolem(Rule, Variable, Arguments), where
737
- // Arguments are the ground values of the conclusions' other variables, in
738
- // order of first occurrence, leaving out fresh parameters only when their
739
- // premise evidence establishes that provenance. Returns null when the
740
- // rule has no witnesses, else whether they all hold; head is the rule's
741
- // renamed conclusions and names maps its variables to their renamed ones.
742
- function checkWitnesses(clause, head, body, names, env, provenance) {
743
- const witnessed = clause.witnessNames;
744
- if (!witnessed.length) return null;
745
- // An existential firing needs bound inspection values. A generic rule
746
- // pattern cannot silently share one witness across all its instances.
747
- if (!isGround(copyResolved(head, env))) return false;
748
- let firing = null;
749
- for (const name of witnessed) {
750
- const value = copyResolved(names.get(name), env);
751
- if (!isTerm(value, 'skolem', 3) || value.args[0] !== BigInt(clause.id) || value.args[1] !== name) return false;
752
- if (firing === null) firing = value.args[2];
753
- else if (text(value.args[2]) !== text(firing)) return false;
754
- }
755
- const ofThisFiring = (term) => {
756
- const pending = [term];
757
- while (pending.length) {
758
- const item = pending.pop();
759
- if (!(item instanceof Struct)) continue;
760
- if (item.name === 'skolem' && item.args.length === 3 && item.args[0] === BigInt(clause.id) &&
761
- text(item.args[2]) === text(firing)) return true;
762
- pending.push(...item.args);
763
- }
764
- return false;
765
- };
766
- // Recover captures from the source clause and substitution, independently
767
- // of the proposed witness, including captures the head does not mention.
768
- const expected = clause.captures === null ? [] : [listFromItems(
769
- clause.captures.map((name) => copyResolved(names.get(name), env)),
770
- )];
771
- const introduced = new Set(witnessed.map((name) => names.get(name).name));
772
- let contextual = false;
773
- for (const variable of variables(head).values()) {
774
- const value = copyResolved(variable, env);
775
- if (isGround(value) && !ofThisFiring(value)) expected.push(value);
776
- else if (!introduced.has(variable.name)) contextual = true;
777
- }
778
- return text(listFromItems(expected)) === text(firing) &&
779
- (!contextual || provenance.check(clause, head, body, names, env, firing));
780
- }
781
-
782
- // A value may be omitted from a firing's context only when its apparent
783
- // fresh symbols really are parameters of the premise derivation. Abstract
784
- // those symbols together, then check the recorded evidence against the
785
- // source again. In particular, abstracting a literal input Skolem constant
786
- // must fail; its spelling does not make it a fresh value of this firing.
787
- class WitnessProvenance {
788
- constructor(program, steps, certificate, outcomes, spellings) {
789
- this.program = program;
790
- this.steps = steps;
791
- this.certificate = certificate;
792
- this.outcomes = outcomes;
793
- this.spellings = spellings;
794
- this.serial = 0;
795
- this.usedNames = null;
796
- }
797
-
798
- fresh() {
799
- if (this.usedNames === null) {
800
- this.usedNames = new Map();
801
- for (const step of this.steps.values()) {
802
- for (const term of [step.goal, ...step.bindings, ...step.uses]) variables(term, this.usedNames);
803
- }
804
- for (const clause of this.program.clauses) {
805
- for (const term of [clause.head, ...clause.body, ...clause.extraTerms]) variables(term, this.usedNames);
806
- }
807
- }
808
- let name;
809
- do { name = `\0witness${++this.serial}`; } while (this.usedNames.has(name));
810
- return new Var(name);
811
- }
812
-
813
- check(clause, head, body, names, env, firing) {
814
- const argumentsId = text(firing);
815
- const symbols = new Map();
816
- const copied = new Map();
817
- const abstract = (term) => {
818
- if (!(term instanceof Struct)) return term;
819
- if (copied.has(term)) return copied.get(term);
820
- let result;
821
- if (isTerm(term, 'skolem', 3) && term.args[0] === BigInt(clause.id) && text(term.args[2]) === argumentsId) {
822
- const id = text(term);
823
- if (!symbols.has(id)) symbols.set(id, this.fresh());
824
- result = symbols.get(id);
825
- } else {
826
- const args = term.args.map(abstract);
827
- result = args.every((arg, i) => arg === term.args[i]) ? term : new Struct(term.name, args);
828
- }
829
- copied.set(term, result);
830
- return result;
831
- };
832
- // Captures belong to an already-created instance, before this firing.
833
- for (const name of clause.captures || []) {
834
- const value = copyResolved(names.get(name), env);
835
- if (abstract(value) !== value) return false;
836
- }
837
- const projected = abstract(copyResolved(new Struct('scope', [head, ...body]), env));
838
- const source = new Struct('scope', [clause.head, ...clause.body]);
839
- if (!isInstance(projected, source, 'provenance')) return false;
840
- const pending = body.map((goal) => copyResolved(goal, env));
841
- const seen = new Set();
842
- const fail = new Failures();
843
- while (pending.length) {
844
- const original = pending.pop();
845
- if (isTerm(original, 'and', 2)) {
846
- pending.push(...flattenConjunction(original));
847
- continue;
848
- }
849
- const goal = abstract(original);
850
- if (goal === original) continue;
851
- const id = this.spellings.spell(original);
852
- if (seen.has(id)) continue;
853
- seen.add(id);
854
- const step = this.steps.get(id);
855
- if (step === undefined) {
856
- if (!isCallable(goal) || !(this.program.groups.get(key(goal)) || []).some((given) =>
857
- !given.body.length && isInstance(goal, given.head, 'provenanceFact'))) return false;
858
- continue;
859
- }
860
- if (isTerm(step.by, 'clause', 1)) {
861
- const cited = clauseNamed(this.program, step.by.args[0]);
862
- if (cited === null) return false;
863
- if (cited.forward) {
864
- // A premise's derived fact already exists. Its ground values are
865
- // data, and only its universal variables may be instantiated.
866
- if (!isInstance(goal, step.goal, 'provenanceDerived')) return false;
867
- continue;
868
- }
869
- if (!this.fixedScopes(cited, step, abstract)) return false;
870
- const generalized = { ...step, goal, bindings: step.bindings.map(abstract), uses: step.uses.map(abstract) };
871
- // Original steps receive their own C8 checks. Here only source
872
- // resolution is repeated, under the one shared abstraction.
873
- if (!checkResolution(this.program, generalized, fail, { witnessed: 0 })) return false;
874
- pending.push(...step.uses);
875
- } else if (isTerm(step.by, 'source', 1)) {
876
- const cited = clauseNamed(this.program, step.by.args[0]);
877
- const inspected = cited === null ? null : this.program.inspectedById.get(cited.id);
878
- if (!inspected || step.bindings.length || step.uses.length || !isInspection(goal) ||
879
- !isInstance(goal, inspected.term, 'provenanceInspection')) return false;
880
- } else if (step.by === BUILTIN_BY) {
881
- if (step.bindings.length || step.uses.length || !isCallable(goal) ||
882
- !PRIMITIVE_KEYS.has(key(goal)) || !redecides(goal)) return false;
883
- } else if (isTerm(step.by, 'called', 1)) {
884
- if (step.bindings.length || step.uses.length || !isCallable(goal) ||
885
- !STATE_TESTS.has(key(goal)) || !redecidesCalled(goal, step.by.args[0])) return false;
886
- } else if (step.by === CONTROL_BY) {
887
- const candidates = isTerm(goal, 'call', 1) || isTerm(goal, 'once', 1) ? [goal.args[0]]
888
- : isTerm(goal, 'or', 2) ? goal.args : [];
889
- const uses = step.uses.map(abstract);
890
- if (step.bindings.length || !candidates.some((candidate) => {
891
- const parts = flattenConjunction(candidate);
892
- return parts.length === uses.length && parts.every((part, i) => text(part) === text(uses[i]));
893
- })) return false;
894
- pending.push(...step.uses);
895
- } else if (isBoundary(step)) {
896
- // Generalizing a trusted assumption would silently strengthen it.
897
- // Only the already-consulted certificate may discharge a stronger
898
- // boundary; missing evidence fails provenance instead.
899
- const outcome = this.outcomes.get(id);
900
- if (outcome?.status !== 'settled') return false;
901
- const tables = new Set(outcome.tables);
902
- const listings = new Set(outcome.listings);
903
- const settler = new Settler(this.program, {
904
- answers: (call) => tables.has(variant(call)) ? this.certificate.tables.get(variant(call)) : null,
905
- facts: (goalKey) => listings.has(goalKey) ? this.certificate.listings.get(goalKey) : null,
906
- supported: (fact) => this.steps.has(this.spellings.spell(fact)),
907
- });
908
- if (settler.settle(goal).status !== 'settled') return false;
909
- } else return false;
910
- }
911
- return true;
912
- }
913
-
914
- fixedScopes(clause, step, abstract) {
915
- if (!clause.scopeIds.length) return true;
916
- const [head, body, names] = freshClause(clause, 'provenanceScope');
917
- const env = new Env();
918
- for (const pair of step.bindings) {
919
- if (!names.has(pair.args[0]) || !unify(names.get(pair.args[0]), pair.args[1], env)) return false;
920
- }
921
- if (!unify(head, step.goal, env) || body.length !== step.uses.length ||
922
- !body.every((goal, i) => unify(goal, step.uses[i], env))) return false;
923
- for (const term of clause.extraTerms) {
924
- const value = copyResolved(freshTerm(term, 'provenanceScope', names), env);
925
- if (abstract(value) !== value) return false;
926
- }
927
- return true;
928
- }
929
- }
930
-
931
- // C9 and C6. A boundary its search certificate settles holds, and one whose
932
- // certificate is wrong fails C9. Without a settling certificate a boundary
933
- // cannot be proved, but evidence at hand can refute it (C6). An absence fails
934
- // when a source fact, a step of this certificate or a recomputed primitive is
935
- // a solution; a collection fails when such a solution is missing from its
936
- // list. Returns how many boundaries the evidence could speak for, and how
937
- // many their certificates settled or refuted.
938
- function checkBoundaries(program, steps, boundaries, fail, outcomes, spellings) {
939
- const stepGoals = new Map();
940
- for (const step of steps.values()) {
941
- if (isCallable(step.goal)) {
942
- const goalKey = key(step.goal);
943
- if (!stepGoals.has(goalKey)) stepGoals.set(goalKey, []);
944
- stepGoals.get(goalKey).push(step.goal);
945
- }
946
- }
947
- let serial = 0;
948
- let confronted = 0;
949
- let closed = 0;
950
- const nextSerial = () => ++serial;
951
-
952
- // Each solution of a simple goal that the evidence shows, or null when the
953
- // evidence cannot speak for the goal. A recomputed primitive always speaks,
954
- // even when it fails; a predicate with no fact or step at all does not, so
955
- // a boundary over it is left undecided rather than counted as confronted.
956
- function evidence(goal) {
957
- if (!isCallable(goal)) return null;
958
- const goalKey = key(goal);
959
- if (PRIMITIVE_KEYS.has(goalKey)) {
960
- if (!isGround(goal)) return null;
961
- try {
962
- for (const _ of primitive(goal, new Env())) return [goal]; // eslint-disable-line no-unused-vars
963
- } catch (error) {
964
- if (!(error instanceof EyemindError)) throw error;
965
- return null;
966
- }
967
- return [];
968
- }
969
- if (CONTROL_KEYS.has(goalKey)) return null;
970
- let shown;
971
- if (INSPECTION_KEYS.has(goalKey)) {
972
- shown = program.inspections.get(goalKey).map((entry) => freshTerm(entry.term, `evidence${nextSerial()}`));
973
- } else {
974
- const facts = (program.groups.get(goalKey) || [])
975
- .filter((clause) => !clause.body.length && !clause.forward)
976
- .map((clause) => freshTerm(clause.head, `evidence${nextSerial()}`));
977
- shown = [...facts, ...(stepGoals.get(goalKey) || []).map((item) => freshTerm(item, `evidence${nextSerial()}`))];
978
- }
979
- return shown.length ? shown : null;
980
- }
981
-
982
- for (const boundary of boundaries) {
983
- const outcome = outcomes.get(spellings.spell(boundary));
984
- if (outcome !== undefined && outcome.status !== 'unsettled') {
985
- closed++;
986
- for (const [detail, term] of outcome.failures) fail.add('C9', detail, term);
987
- continue;
988
- }
989
- if (isTerm(boundary, 'not', 1)) {
990
- const parts = flattenConjunction(boundary.args[0]);
991
- // Without a join, only a single goal or a ground conjunction is decided.
992
- if (parts.length > 1 && !isGround(boundary.args[0])) continue;
993
- const shown = parts.map(evidence);
994
- if (shown.some((items) => items === null)) continue;
995
- confronted++;
996
- const solved = parts.every((part, i) => shown[i].some((item) => unify(freshTerm(part, `absent${nextSerial()}`), item, new Env())));
997
- if (solved) fail.add('C6', `absence contradicted by evidence: ${text(boundary)}`, boundary);
998
- } else {
999
- const parts = flattenConjunction(boundary.args[1]);
1000
- const shown = parts.length === 1 ? evidence(parts[0]) : null;
1001
- // Whether the collection is decided does not depend on its result.
1002
- if (shown !== null) confronted++;
1003
- const items = properListItems(boundary.args[2], new Env());
1004
- if (items === null) {
1005
- fail.add('C6', `collected result is not a proper list: ${text(boundary)}`, boundary);
1006
- continue;
1007
- }
1008
- if (shown === null) continue;
1009
- for (const item of shown) {
1010
- const names = new Map();
1011
- const number = nextSerial();
1012
- const pattern = freshTerm(boundary.args[0], `collect${number}`, names);
1013
- const goal = freshTerm(parts[0], `collect${number}`, names);
1014
- const env = new Env();
1015
- if (!unify(goal, item, env)) continue;
1016
- const answer = copyResolved(pattern, env);
1017
- const listed = items.some((element) => unify(answer, freshTerm(element, `listed${nextSerial()}`), new Env()));
1018
- if (!listed) {
1019
- fail.add('C6', `collection misses ${text(answer)}: ${text(boundary)}`, boundary);
1020
- break;
1021
- }
1022
- }
1023
- }
1024
- }
1025
- return [confronted, closed];
1026
- }
1027
-
1028
- // C7: the certificate answers the question that was asked and carries nothing
1029
- // beside it. A claim is an instance of a goal asked from outside, of a
1030
- // query() goal or, for printed conclusions, of a forward head.
1031
- function checkRelevance(program, claims, steps, goals, fail, spellings, settlement, certificate) {
1032
- let serial = 0;
1033
- const instanceOf = (claim, question) => isInstance(claim, question, `asked${++serial}`);
1034
- const asked = goals.map(goalTerm);
1035
- const halted = claims.some((claim) => claim === 'false');
1036
- const questions = [];
1037
- if (asked.length && !halted) {
1038
- questions.push(...asked);
1039
- } else {
1040
- for (const clause of program.forward) {
1041
- if (clause.heads.some((head) => head === 'true')) {
1042
- if (!halted && clause.body.length) questions.push(conjunction(clause.body));
1043
- }
1044
- for (const head of clause.plainHeads) if (head !== 'true') questions.push(head);
1045
- }
1046
- }
1047
- for (const claim of claims) {
1048
- if (!questions.some((question) => instanceOf(claim, question))) fail.add('C7', `claim answers no goal: ${text(claim)}`, claim);
1049
- }
1050
- const reached = new Set();
1051
- const reach = [];
1052
- for (const claim of claims) for (const part of flattenConjunction(claim)) reach.push(spellings.spell(part));
1053
- for (const entry of settlement.calls.settler.listings.values()) {
1054
- for (const fact of entry.facts) reach.push(stepIdOf(steps, spellings, fact));
1055
- }
1056
- while (reach.length) {
1057
- const stepId = reach.pop();
1058
- if (reached.has(stepId) || !steps.has(stepId)) continue;
1059
- reached.add(stepId);
1060
- for (const use of steps.get(stepId).uses) {
1061
- for (const part of flattenConjunction(use)) reach.push(spellings.spell(part));
1062
- }
1063
- // A settled boundary rests on the derived facts its certificate lists.
1064
- const outcome = settlement.outcomes.get(stepId);
1065
- if (outcome?.status === 'settled') {
1066
- for (const goalKey of outcome.listings) {
1067
- for (const fact of settlement.settler.listings.get(goalKey).facts) reach.push(stepIdOf(steps, spellings, fact));
1068
- }
1069
- }
1070
- }
1071
- for (const [stepId, step] of steps) {
1072
- if (!reached.has(stepId)) fail.add('C7', `step serves no claim: ${stepId}`, step.goal);
1073
- }
1074
- for (const [kind, entryKey, subject] of certificate.order) {
1075
- const used = kind === 'call' ? settlement.calls?.settler.tables
1076
- : kind === 'table' ? settlement.settler.tables : settlement.settler.listings;
1077
- const callListing = kind === 'listing' && settlement.calls?.settler.listings.has(entryKey);
1078
- if (!used?.has(entryKey) && !callListing) fail.add('C7', `search certificate serves no boundary or original call: ${text(subject)}`, subject);
1079
- }
1080
- }
1081
-
1082
- // C2: no step depends on itself, walked iteratively.
1083
- function checkWellFounded(steps, fail, spellings) {
1084
- const visiting = new Set();
1085
- const visited = new Set();
1086
- function supports(stepId) {
1087
- const used = [];
1088
- const step = steps.get(stepId);
1089
- for (const use of step ? step.uses : []) {
1090
- for (const part of flattenConjunction(use)) {
1091
- const partId = spellings.spell(part);
1092
- if (steps.has(partId)) used.push(partId);
1093
- }
1094
- }
1095
- return used;
1096
- }
1097
- for (const start of steps.keys()) {
1098
- if (visited.has(start)) continue;
1099
- visiting.add(start);
1100
- const stack = [[start, supports(start), 0]];
1101
- while (stack.length) {
1102
- const top = stack[stack.length - 1];
1103
- if (top[2] >= top[1].length) {
1104
- visiting.delete(top[0]);
1105
- visited.add(top[0]);
1106
- stack.pop();
1107
- continue;
1108
- }
1109
- const following = top[1][top[2]];
1110
- top[2]++;
1111
- if (visiting.has(following)) {
1112
- fail.add('C2', `cyclic derivation at ${following}`, steps.get(following).goal);
1113
- continue;
1114
- }
1115
- if (visited.has(following)) continue;
1116
- visiting.add(following);
1117
- stack.push([following, supports(following), 0]);
1118
- }
1119
- }
320
+ if (table) certificate.callTerms.set(entryKey, subject);
1120
321
  }
1121
322
 
1122
323
  function verdict(report) {
1123
- if (!report.valid) return new Struct('failed', [BigInt(report.failures.length)]);
1124
- return report.trusted.length ? 'checked_with_obligations' : 'checked';
324
+ return report.valid ? 'checked' : new Struct('failed', [BigInt(report.failures.length)]);
1125
325
  }
1126
326
 
1127
- // Rename a report fact's variables A, B, C, ... in order of appearance.
1128
- function lettered(term) {
1129
- const names = new Map();
1130
- function visit(t) {
1131
- if (t instanceof Var) {
1132
- if (!names.has(t.name)) names.set(t.name, new Var(letterName(names.size)));
1133
- return names.get(t.name);
1134
- }
1135
- if (t instanceof Struct) return new Struct(t.name, t.args.map(visit));
1136
- return t;
1137
- }
1138
- return visit(term);
1139
- }
1140
-
1141
- // The report as JavaScript source, one fact per line, every condition included.
327
+ // The report as JavaScript source: the claims, then a failure(Detail) per
328
+ // failure, then the verdict.
1142
329
  export function checkReport(report) {
1143
- const facts = [];
1144
- for (const condition of report.conditions) {
1145
- const outcome = condition.failed ? new Struct('failed', [BigInt(condition.failed)]) : 'ok';
1146
- facts.push(new Struct('condition', [condition.id, condition.name, outcome, BigInt(condition.covered)]));
1147
- }
1148
- report.failures.forEach((record, i) => {
1149
- const term = report.failureTerms[i];
1150
- const subject = term !== null ? term : (record.conclusion ?? 'proof_document');
1151
- facts.push(new Struct('failure', [record.condition, subject, record.detail]));
1152
- });
1153
- report.trusted.forEach((record, i) => {
1154
- const term = report.trustedTerms[i];
1155
- facts.push(new Struct('obligation', [record.kind, record.reason ?? 'theory_scoped', term !== null ? term : record.conclusion]));
1156
- });
1157
- for (const [name, count] of [['steps', report.steps], ['verified', report.verified], ['recomputed', report.redecided],
1158
- ['composed', report.composed], ['trusted', report.trusted.length], ['claims', report.claims]]) {
1159
- facts.push(new Struct(name, [BigInt(count)]));
1160
- }
1161
- facts.push(new Struct('verdict', [verdict(report)]));
1162
330
  const heading = !report.valid ? '// Unverified claims: proof checking failed.'
1163
- : !report.answers.length && report.trusted.length ? '// No answers claimed; this check establishes no conclusions.'
331
+ : report.halted ? '// Checked claims: these follow from the input program, which halted.'
1164
332
  : !report.answers.length ? '// No answers: the original questions have none.'
1165
- : report.trusted.length ? '// Answers checked subject to the obligations below.'
1166
- : '// Checked answers: these follow from the input program.';
1167
- const lines = [heading, ...report.answers, '',
1168
- '// C1-C10: resolution, acyclicity, justification, coverage, re-decision,',
1169
- '// boundary consistency, relevance, witness integrity, search closure and call fidelity.'];
1170
- let previous = null;
1171
- for (const fact of facts) {
1172
- if (fact.name === 'failure' && previous !== 'failure') {
1173
- lines.push('', '// Failures: the claims above have not passed every check.');
1174
- }
1175
- if (fact.name === 'obligation' && previous !== 'obligation') {
1176
- lines.push('', '// Obligations: absence, collection, original-call or all-answers evidence remains unproved.');
1177
- }
1178
- if (fact.name === 'steps') lines.push('', '// Proof statistics: recorded steps and how they were checked.');
1179
- if (fact.name === 'verdict') {
1180
- lines.push('', report.valid && !report.trusted.length && !report.answers.includes("'false'")
1181
- ? '// This verdict also establishes that the claims above are every answer of the original questions.'
1182
- : '// This verdict applies to the claims above; it does not establish that they are every answer.');
1183
- }
1184
- lines.push(text(lettered(fact)));
1185
- previous = fact.name;
1186
- }
333
+ : '// Checked answers: these follow from the input program and are every answer of its questions.';
334
+ const lines = [heading, ...report.answers, ''];
335
+ if (report.failures.length) {
336
+ lines.push('// Failures: what the check could not establish.');
337
+ for (const { detail } of report.failures) lines.push(text(new Struct('failure', [detail])));
338
+ lines.push('');
339
+ }
340
+ lines.push(text(new Struct('verdict', [verdict(report)])));
1187
341
  return `${lines.join('\n')}\n`;
1188
342
  }
1189
343
 
@@ -1193,6 +347,6 @@ export function verdictText(report) {
1193
347
 
1194
348
  // The report without its term-valued internals, ready for JSON.
1195
349
  export function publicReport(report) {
1196
- const { failureTerms, trustedTerms, ...rest } = report; // eslint-disable-line no-unused-vars
350
+ const { failureTerms, ...rest } = report; // eslint-disable-line no-unused-vars
1197
351
  return rest;
1198
352
  }