eyemind 0.5.31 → 0.5.32

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
@@ -24,7 +24,6 @@ The playground runs programs in your browser; the specification defines the lang
24
24
  - [SPARQL 1.2 RL](#sparql-12-rl)
25
25
  - [How eyemind reasons](#how-eyemind-reasons)
26
26
  - [Proofs, and what checking one means](#proofs-and-what-checking-one-means)
27
- - [Native proof data](#native-proof-data)
28
27
  - [JSON check reports](#json-check-reports)
29
28
  - [Why negation and collection are safe](#why-negation-and-collection-are-safe)
30
29
  - [Checking the translation](#checking-the-translation)
@@ -148,7 +147,7 @@ for (let level = 1; level <= 10; level++) {
148
147
  - **Arithmetic is a term, not an operator.** `is(Y, add(X, 1))` computes and `gt(X, 1)` compares. `X + 1` or `X > 1` stops the program with a message saying what to write instead, and operators on plain numbers are JavaScript's own (`2 ** 60 + 1` arrives already rounded). The primitives are listed in [SPEC §4](https://eyereasoner.github.io/eyemind/SPEC#4-goals-and-primitives) and the arithmetic functions in [SPEC §5](https://eyereasoner.github.io/eyemind/SPEC#5-arithmetic).
149
148
  - **Numbers are exact.** An integral number is an integer, `2` and `2.0` alike, and `float(2)` is a float; write integers beyond 2^53 as a `BigInt`, `9007199254740993n`. `1` and `float(1)` do not unify, yet compare equal.
150
149
  - **Something exists.** A variable only a forward rule's conclusion mentions becomes a Skolem term of that firing: `implies(person(X), has_parent(X, P))` concludes `has_parent('ann', skolem(2, 'P', ['ann']))`.
151
- - **Data is not a program.** eyemind's term documents are plain expressions. `facts_from` reads one as facts and never executes it, so it is the safe way to take in data you do not trust, and lets one run reason over another's proof, as [audited-grants](https://github.com/eyereasoner/eyemind/blob/main/examples/audited-grants.js) does. Native N3 and SRL proofs are RDF data too.
150
+ - **Data is not a program.** eyemind's term documents are plain expressions. `facts_from` reads one as facts and never executes it, so it is the safe way to take in data you do not trust, and lets one run reason over another's proof, as [audited-grants](https://github.com/eyereasoner/eyemind/blob/main/examples/audited-grants.js) does.
152
151
 
153
152
  ### Deriving rules
154
153
 
@@ -293,7 +292,7 @@ Whole-log replay gives N3 or JavaScript rules an ordered view of the messages:
293
292
  ```sh
294
293
  eyemind examples/message-boundaries-n3.n3 examples/data/message-boundaries-n3.trig
295
294
  eyemind --proof examples/message-boundaries-n3.n3 examples/data/message-boundaries-n3.trig
296
- eyemind --check-proof examples/proof/message-boundaries-n3.n3 examples/message-boundaries-n3.n3 examples/data/message-boundaries-n3.trig
295
+ eyemind --check-proof examples/proof/message-boundaries-n3.js examples/message-boundaries-n3.n3 examples/data/message-boundaries-n3.trig
297
296
  ```
298
297
 
299
298
  The replay vocabulary is `eymsg:`, with namespace
@@ -403,29 +402,19 @@ The two work together: a forward rule's premise can call a backward definition,
403
402
  ## Proofs, and what checking one means
404
403
 
405
404
  A proof holds the claims, the source clauses it cites, and each recorded
406
- inference. JavaScript programs write `step(...)` records. N3 inputs write
407
- N3 proofs, and SRL inputs write SRL `DATA` proofs:
405
+ inference as `step(...)` records. Every input writes the same JavaScript
406
+ proof: an N3 document or SRL rule set is compiled to an eyemind program, and
407
+ its proof cites that program's clauses, with triples as `rdf(S, P, O)` (an
408
+ SRL inference as `inf(S, P, O)`) over `iri(...)` and `literal(...)` terms:
408
409
 
409
410
  ```sh
410
- eyemind --proof examples/socrates-n3.n3 > /tmp/socrates-proof.n3
411
- eyemind --check-proof /tmp/socrates-proof.n3 examples/socrates-n3.n3
412
- eyemind --proof examples/socrates-srl.srl > /tmp/socrates-proof.srl
413
- eyemind --check-proof /tmp/socrates-proof.srl examples/socrates-srl.srl
411
+ eyemind --proof examples/socrates-n3.n3 > /tmp/socrates-proof.js
412
+ eyemind --check-proof /tmp/socrates-proof.js examples/socrates-n3.n3
413
+ eyemind --proof examples/socrates-srl.srl > /tmp/socrates-proof.js
414
+ eyemind --check-proof /tmp/socrates-proof.js examples/socrates-srl.srl
414
415
  ```
415
416
 
416
- Native proofs use `pe:`, `https://eyereasoner.github.io/pe#`, for the claims,
417
- conclusions, rule numbers, bindings and ordered uses. N3 displays statements
418
- as quoted formulas; SRL displays them as RDF triple terms. Rule numbers name
419
- clauses of the compiled eyemind program. The `em:` vocabulary,
420
- `https://eyereasoner.github.io/eyemind/proof#`, keeps the exact terms and
421
- ordered records, including all C9 search and C10 call tables. The checker
422
- validates the displays against those records, then checks the certificate
423
- against the source program. Altered displays, duplicate properties and extra
424
- assertions fail checking. Proofs can be read as data by other N3 or SRL rules.
425
-
426
- `--check-proof` recognizes the content, independently of the filename, and
427
- continues to accept JavaScript certificates for native inputs. Check reports
428
- remain JavaScript term documents, or JSON with `--json`.
417
+ Check reports are JavaScript term documents too, or JSON with `--json`.
429
418
 
430
419
  Checking applies ten conditions:
431
420
 
@@ -476,69 +465,6 @@ verdict('checked')
476
465
 
477
466
  A `checked` verdict thus establishes two things: every claim follows from the program, and the claims are every answer of the original questions. The `called/2` table of each question lists all its answers and is checked against the program, so a proof that omits one fails C10, and a question with no claims is shown to have no answers. A failed check gives `failure(Condition, Conclusion, Detail)` facts, `verdict(failed(N))` and exit code 2. What a certificate cannot settle stays an `obligation(...)` with the verdict `checked_with_obligations`, among them `obligation('call_fidelity', 'all_answers', Question)` for a question whose answers it cannot show complete; `--strict-proof` rejects those. To check answers to `--goal` questions, pass the same goals when checking. [SPEC §11](https://eyereasoner.github.io/eyemind/SPEC#11-proof-checking) defines every condition.
478
467
 
479
- ### Native proof data
480
-
481
- These N3 and SRL encodings are implementation extensions to the canonical
482
- proof documents. Language and proof conformance does not require them.
483
-
484
- The native proof resource is `<urn:eyemind:proof>`, of type `pe:Proof`, where
485
- `pe:` is `https://eyereasoner.github.io/pe#` and `em:` is
486
- `https://eyereasoner.github.io/eyemind/proof#`. It has `em:format` equal to
487
- `"n3"` or `"srl"`, `pe:claims` as an ordered collection of claim displays,
488
- and `em:records` as an ordered collection of record IRIs. Record `N`, counted
489
- from 1, is `<urn:eyemind:proof#recordN>` and has one `em:term` containing its
490
- [Section 10](https://eyereasoner.github.io/eyemind/SPEC#10-proof-documents) statement, encoded as a tagged collection:
491
-
492
- | Term | Collection |
493
- | --- | --- |
494
- | Atom | `(em:atom "text")` |
495
- | Integer | `(em:integer "digits")`, with a minus for a negative integer |
496
- | Float | `(em:float "number")`, preserving signed zero as `"-0"` |
497
- | Variable | `(em:variable "name")`, including anonymous-variable status |
498
- | `iri(I)` with an RDF-compatible IRI | `(em:iri <I>)` |
499
- | Nonempty proper list | `(em:list (EncodedItem ...))` |
500
- | Compound | `(em:compound "name" (EncodedArgument ...))` |
501
-
502
- The empty list is the atom `"[]"`. Other compounds, including open lists,
503
- quoted graphs and Skolem terms, use the compound encoding. A string field
504
- containing a character RDF cannot represent uses an `em:utf16` typed literal
505
- whose lexical form is four lowercase hexadecimal digits per UTF-16 code
506
- unit. This retains every atom and variable name accepted by
507
- [Section 9.2](https://eyereasoner.github.io/eyemind/SPEC#92-canonical-atoms-numbers-variables-and-lists).
508
-
509
- A triple goal's display is an N3 quoted formula, or an SRL RDF triple term.
510
- Other goals use their tagged encoding. A step record also displays
511
- `pe:conclusion`, `pe:rule` for a `clause(N)` justification, `pe:source` for
512
- `source(N)`, or `pe:justification` for another justification. `pe:binding`
513
- is an ordered collection of `(VariableName Value)` pairs, and `pe:uses` an
514
- ordered collection of premise displays. Non-native binding values retain
515
- their tagged encoding. Search records display `pe:derived`, `pe:searched`
516
- or `pe:called` and an ordered `pe:answers` collection. Clause numbers name
517
- the compiled program's clauses, whose authority is still the source input.
518
- SRL proofs contain only `DATA` and declarations, never rules or imports.
519
-
520
- When an SRL rule set uses `NOW`, `UUID` or `STRUUID`, its compiled program
521
- includes one ground `srl_execution(Now, Seed)` fact. `Now` is an ISO UTC
522
- timestamp with milliseconds and `Seed` contains 64 lowercase hexadecimal
523
- digits. The compiler captures these external inputs once per compilation;
524
- they remain fixed throughout evaluation. To check a saved SRL proof, the
525
- format loader may recover this fact from its clause records, validate its
526
- two fields, and recompile the source with that execution context. All other
527
- clauses still come from the source, and all displays undergo C1–C10 as
528
- usual. This establishes consequences of the recorded context, without
529
- certifying a clock observation or the entropy of the seed.
530
-
531
- The reader decodes every record, verifies all displays and properties against
532
- those records, and applies the unchanged checks of
533
- [Section 11](https://eyereasoner.github.io/eyemind/SPEC#11-proof-checking) to the decoded
534
- certificate. A missing, extra, duplicate or inconsistent property fails C3.
535
- Numeric literal displays retain their decimal digits during this comparison;
536
- distinct decimal literals do not agree merely by rounding to binary64.
537
- Prefix aliases and reordering top-level properties are accepted, as is
538
- consistent blank-node renaming; the order of collections and formula triples
539
- is retained. Displayed claims cannot replace encoded claims, and neither
540
- representation can change the source authority or supply missing evidence.
541
-
542
468
  ### JSON check reports
543
469
 
544
470
  With `--json`, checking modes write a JSON report instead of a term document.
@@ -640,8 +566,7 @@ before exhaustion.
640
566
  | 2 | An invalid proof check; the report is printed as usual. |
641
567
  | 65 | The run concluded `'false'` and halted. |
642
568
 
643
- The command line, JSON output, additional input formats, native proof
644
- encodings, library API and browser interface describe this implementation.
569
+ The command line, JSON output, additional input formats, library API and browser interface describe this implementation.
645
570
  They are outside the language and proof specification.
646
571
 
647
572
  ### Resource limits
@@ -722,13 +647,6 @@ console.log(checkProof(socrates, result.proof, { goals }).valid);
722
647
 
723
648
  `run()` returns `conclusions`, `answers`, `bindings`, `inferred`, `stdout`, `proof`, `proofReport`, `stats` and `haltCode`, and takes `goal`, `goals`, `proof`, `maxDepth`, `maxIterations` and `maxInferences`; exceeding a bound throws an `EyemindError`. `conclusions` holds the answer terms; `answers`, `bindings` and `stdout` are rendered when first read. Ground N3 conclusions are written directly from their terms. `loadSources([[text, filename], ...], io)` loads several sources as one program; pass `nodeIO` from `eyemind/node` as `io` to let `facts_from(path)` read files. `checkProof(program, document, { goals, allowTrusted })` checks C1–C10, and `allowTrusted: false` rejects every obligation. `checkReport`, `readTerm`, `readTerms` and `write` format reports and read and write the canonical text.
724
649
 
725
- The core library's `result.proof` is the JavaScript certificate.
726
- `writeNativeProof(result.proof, { format: 'n3', prefixes })` writes its N3
727
- representation; use `format: 'srl'` for SRL. `readNativeProof(document)`
728
- returns the decoded terms, and `readProofTerms(document)` reads any supported
729
- proof as `[term, line]` pairs. Native records have line 0. `checkProof`
730
- accepts all three representations and never evaluates proof text.
731
-
732
650
  ## What is deliberately absent
733
651
 
734
652
  Cut, conditional commitment, mutable databases, attributed variables, constraint libraries, tabling, and filesystem or network built-ins. Without cut and a mutable database, a derivation is a function of the program and its input, which is what makes a certificate meaningful. Undefined predicates fail.
package/SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The eyemind Rule Language and Proof Format
5
- Version: eyemind 0.5.31
5
+ Version: eyemind 0.5.32
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.31",
3
+ "version": "0.5.32",
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/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // The eyemind command line.
2
2
  import { run, unusedClauses } from './engine.js';
3
- import { OUTPUT_FORMATS, defaultFormat, inputKind, loadInputs, rdfMessageFormat, scopeOf, writeConclusions, writeProof } from './formats.js';
3
+ import { OUTPUT_FORMATS, defaultFormat, inputKind, loadInputs, rdfMessageFormat, scopeOf, writeConclusions } from './formats.js';
4
4
  import { isRdfMessageLog, replayMessages, RdfMessageReader } from './messages.js';
5
5
  import { checkProof, checkReport, publicReport } from './proof.js';
6
6
  import { EyemindError } from './terms.js';
@@ -210,7 +210,7 @@ export function main(argv, io) {
210
210
  return report.valid ? result.haltCode || 0 : 2;
211
211
  }
212
212
  // Answers to goals are eyemind terms unless an output format is asked.
213
- const written = options.proof ? writeProof(loaded, result, { goals }) : writeConclusions(loaded, result, {
213
+ const written = options.proof ? result.proof : writeConclusions(loaded, result, {
214
214
  format: format ?? (goals.length ? 'eyemind' : defaultFormat(loaded.kind)), all, blankNodePrefix: io.blankNodePrefix,
215
215
  });
216
216
  stdout(written ?? result.stdout);
package/src/formats.js CHANGED
@@ -22,8 +22,6 @@ import { resultToN3, compileSources } from './n3.js';
22
22
  import { compileSrl, srlAnswers, srlQuads } from './srl.js';
23
23
  import { write } from './writer.js';
24
24
  import { isRdfMessageLog, parseRdfMessages } from './messages.js';
25
- import { writeNativeProof } from './native-proof.js';
26
- import { checkProof } from './proof.js';
27
25
 
28
26
  export const OUTPUT_FORMATS = ['eyemind', 'turtle', 'trig', 'n-triples', 'n-quads', 'n3'];
29
27
 
@@ -124,16 +122,6 @@ function importResolver(io) {
124
122
  // eyemind's own text for a program.
125
123
  export const defaultFormat = (kind) => ({ n3: 'n3', srl: 'turtle' })[kind] ?? 'eyemind';
126
124
 
127
- // The core certificate keeps its specified JavaScript form. Native inputs
128
- // expose the same evidence as N3 or SRL data at the format boundary.
129
- export function writeProof(loaded, result, { goals = null } = {}) {
130
- if (loaded.kind === 'js') return result.proof;
131
- const document = writeNativeProof(result.proof, { format: loaded.kind, prefixes: loaded.prefixes });
132
- const report = checkProof(loaded.program, document, { goals });
133
- if (!report.valid) throw new EyemindError(`generated ${loaded.kind} proof failed verification: ${report.failures[0].detail}`);
134
- return document;
135
- }
136
-
137
125
  // The conclusions of a run in an output format; null for eyemind's own text.
138
126
  // all also writes the given data. Throws when a conclusion is no triple.
139
127
  export function writeConclusions(loaded, result, { format, all = false, blankNodePrefix = '' } = {}) {
package/src/index.js CHANGED
@@ -10,7 +10,6 @@ export { readGoal } from './goals.js';
10
10
  export { FloatLiteral, build, loadSources, loadText, toTerm } from './lang.js';
11
11
  export { Program } from './program.js';
12
12
  export { checkProof, checkReport, publicReport, strict, verdictText } from './proof.js';
13
- export { readNativeProof, readProofTerms, writeNativeProof } from './native-proof.js';
14
13
  export { readTerm, readTerms } from './reader.js';
15
14
  export { EyemindError, Struct, Var } from './terms.js';
16
15
  export { write } from './writer.js';
package/src/n3-parser.js CHANGED
@@ -248,9 +248,8 @@ export const DEFAULT_PREFIXES = {
248
248
  };
249
249
 
250
250
  // Parse a document: { triples, prefixes, base }. Prefixes map names to IRIs
251
- // in declaration order. Native proof validation preserves numeric literal
252
- // text, so two different decimal displays cannot agree through rounding.
253
- export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}) {
251
+ // in declaration order.
252
+ export function parseN3(src, { base = '' } = {}) {
254
253
  src = String(src);
255
254
  const input = tokens(src);
256
255
  const ahead = [];
@@ -327,7 +326,7 @@ export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}
327
326
  if (isP('^^')) {
328
327
  next();
329
328
  const dt = iriTerm();
330
- return typedLiteral(text, dt.v, preserveNumericLiterals);
329
+ return typedLiteral(text, dt.v);
331
330
  }
332
331
  return { t: 'literal', v: text, dt: `${XSD}string` };
333
332
  }
@@ -381,7 +380,7 @@ export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}
381
380
  if (tok.k === 'var') return { t: 'var', v: tok.v, scope: 0 };
382
381
  if (tok.k === 'bnode') return { t: 'bnode', v: tok.v, scope: scope.id };
383
382
  if (tok.k === 'string') return literalTail(tok.v);
384
- if (tok.k === 'number') return numberTerm(tok.v, preserveNumericLiterals);
383
+ if (tok.k === 'number') return numberTerm(tok.v);
385
384
  if (tok.k === 'word') {
386
385
  if (tok.v === 'true' || tok.v === 'false') return { t: 'literal', v: tok.v, dt: `${XSD}boolean` };
387
386
  throw fail(`unexpected word '${tok.v}'; prefixed names need a colon, as in :${tok.v}`, tok);
@@ -510,9 +509,8 @@ export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}
510
509
  return { triples: top.triples, prefixes, base };
511
510
  }
512
511
 
513
- function numberTerm(text, preserve = false) {
512
+ function numberTerm(text) {
514
513
  if (/^[+-]?[0-9]+$/.test(text)) return { t: 'int', v: BigInt(text) };
515
- if (preserve) return { t: 'literal', v: text, dt: `${XSD}${/[eE]/.test(text) ? 'double' : 'decimal'}` };
516
514
  if (/[eE]/.test(text)) return { t: 'literal', v: String(Number(text)), dt: `${XSD}double` };
517
515
  return { t: 'float', v: Number(text) };
518
516
  }
@@ -522,10 +520,9 @@ const FLOAT_TYPES = new Set(['decimal']);
522
520
 
523
521
  // Native numbers represent integer and decimal. Float and double retain
524
522
  // their datatype so triple matching and log:equalTo distinguish them.
525
- export function typedLiteral(text, dt, preserve = false) {
523
+ export function typedLiteral(text, dt) {
526
524
  if (dt.startsWith(XSD)) {
527
525
  const local = dt.slice(XSD.length);
528
- if (preserve && ['decimal', 'float', 'double'].includes(local)) return { t: 'literal', v: text, dt };
529
526
  if (INTEGER_TYPES.has(local) && /^[+-]?[0-9]+$/.test(text)) return { t: 'int', v: BigInt(text) };
530
527
  if (FLOAT_TYPES.has(local) && /^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(text)) return { t: 'float', v: Number(text) };
531
528
  if ((local === 'double' || local === 'float') && Number.isFinite(Number(text)) && /^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(text)) return { t: 'literal', v: String(Number(text)), dt };
package/src/proof.js CHANGED
@@ -18,11 +18,11 @@ import { goalTerm } from './goals.js';
18
18
  import { checkCalls } from './fidelity.js';
19
19
  import { INSPECTION_KEYS, isInspection } from './inspection.js';
20
20
  import { CONTROL_KEYS, Program } from './program.js';
21
- import { readProofTerms } from './native-proof.js';
22
21
  import {
23
22
  Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, flattenConjunction, freshTerm,
24
23
  isCallable, isCollection, isFloat, isGround, isTerm, key, keyArity, keyName, listFromItems, properListItems, unify, variables,
25
24
  } from './terms.js';
25
+ import { readTerms } from './reader.js';
26
26
  import { Lettering, letterName, quote, write, writeNotingVariables } from './writer.js';
27
27
 
28
28
  // Several goals or conclusions are displayed as an array, as a program
@@ -434,7 +434,7 @@ function readDocument(program, document, fail, spellings) {
434
434
  const certificate = { tables: new Map(), calls: new Map(), listings: new Map(), order: [] };
435
435
  const empty = new Env();
436
436
  try {
437
- for (const [term] of readProofTerms(document)) {
437
+ for (const [term] of readTerms(document)) {
438
438
  if (isTerm(term, 'searched', 2) || isTerm(term, 'derived', 2) || isTerm(term, 'called', 2)) {
439
439
  readCertificate(term, certificate, fail, empty);
440
440
  continue;
package/src/srl.js CHANGED
@@ -41,7 +41,6 @@ import { Program, Source } from './program.js';
41
41
  import { DEFAULT_GRAPH } from './rdf.js';
42
42
  import { readTerms } from './reader.js';
43
43
  import { Struct, Var, conjunction, identity, isGround } from './terms.js';
44
- import { readProofTerms } from './native-proof.js';
45
44
  import { write } from './writer.js';
46
45
 
47
46
  export class SrlError extends Error {}
@@ -207,7 +206,7 @@ function executionContext(context) {
207
206
 
208
207
  export function srlContextFromProof(document) {
209
208
  try {
210
- const contexts = readProofTerms(document).map(([term]) => term)
209
+ const contexts = readTerms(document).map(([term]) => term)
211
210
  .filter((t) => t instanceof Struct && t.name === 'clause' && t.args.length === 2)
212
211
  .map((t) => t.args[1])
213
212
  .filter((t) => t instanceof Struct && t.name === 'fact' && t.args.length === 1)
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.5.31';
2
+ export const VERSION = '0.5.32';
@@ -1,316 +0,0 @@
1
- // Native proof documents keep the complete compiled certificate as RDF data.
2
- // Their formulas/triple terms are checked displays, never a second authority
3
- // for the claims, bindings or search tables checked by C1–C10.
4
- import { parseN3, RDF, XSD, typedLiteral } from './n3-parser.js';
5
- import { writeN3 } from './n3-writer.js';
6
- import { readTerms } from './reader.js';
7
- import { Parser } from './srl-parser.js';
8
- import { Env, EyemindError, Struct, Var, isTerm, listFromItems, properListItems } from './terms.js';
9
-
10
- export const PROOF_NS = 'https://eyereasoner.github.io/pe#';
11
- export const TERM_NS = 'https://eyereasoner.github.io/eyemind/proof#';
12
- const ROOT = 'urn:eyemind:proof';
13
- const iri = (value) => new Struct('iri', [value]);
14
- const rdfText = (value) => [...value].every((c) => {
15
- const n = c.codePointAt(0);
16
- return n !== 0 && !(n >= 0xd800 && n <= 0xdfff) && (n & 0xfffe) !== 0xfffe;
17
- });
18
- const iriText = (value) => typeof value === 'string' && rdfText(value) && !/[\u0000-\u0020<>"{}|^`\\]/.test(value);
19
- function literal(value) {
20
- if (rdfText(value)) return new Struct('literal', [value, new Struct('datatype', [`${XSD}string`])]);
21
- const hex = Array.from({ length: value.length }, (_, i) => value.charCodeAt(i).toString(16).padStart(4, '0')).join('');
22
- return new Struct('literal', [hex, new Struct('datatype', [`${TERM_NS}utf16`])]);
23
- }
24
- const list = listFromItems;
25
- const empty = new Env();
26
- const records = new Set(['clause/2', 'step/4', 'derived/2', 'searched/2', 'called/2']);
27
- const record = (term) => term instanceof Struct && records.has(`${term.name}/${term.args.length}`);
28
-
29
- // Tagged collections preserve atoms, exact integers, floats (including -0),
30
- // variable names and arbitrary compounds without embedding executable text.
31
- function encode(term) {
32
- if (term instanceof Var) return list([iri(`${TERM_NS}variable`), literal(term.name)]);
33
- if (typeof term === 'string') return list([iri(`${TERM_NS}atom`), literal(term)]);
34
- if (typeof term === 'bigint') return list([iri(`${TERM_NS}integer`), literal(String(term))]);
35
- if (typeof term === 'number') return list([iri(`${TERM_NS}float`), literal(Object.is(term, -0) ? '-0' : String(term))]);
36
- if (isTerm(term, 'iri', 1) && iriText(term.args[0])) return list([iri(`${TERM_NS}iri`), iri(term.args[0])]);
37
- if (isTerm(term, '.', 2)) {
38
- const items = properListItems(term, empty);
39
- if (items !== null) return list([iri(`${TERM_NS}list`), list(items.map(encode))]);
40
- }
41
- if (term instanceof Struct) return list([iri(`${TERM_NS}compound`), literal(term.name), list(term.args.map(encode))]);
42
- throw new EyemindError('a native proof record contains an unsupported term');
43
- }
44
-
45
- function native(term, format) {
46
- if (typeof term === 'bigint' || (typeof term === 'number' && Number.isFinite(term)) || term === '[]') return true;
47
- if (term instanceof Var) return format === 'n3' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(term.name);
48
- if (!(term instanceof Struct)) return false;
49
- if (isTerm(term, 'iri', 1)) return iriText(term.args[0]);
50
- if (isTerm(term, 'literal', 2)) {
51
- const [value, annotation] = term.args;
52
- return typeof value === 'string' && rdfText(value) && annotation instanceof Struct &&
53
- ((annotation.name === 'datatype' && annotation.args.length === 1 && iriText(annotation.args[0])) ||
54
- (annotation.name === 'lang' && [1, 2].includes(annotation.args.length) && annotation.args.every((arg) => typeof arg === 'string' && /^[A-Za-z0-9-]+$/.test(arg))));
55
- }
56
- if (isTerm(term, 'bnode', 2) || isTerm(term, 'skolem', 3)) return true;
57
- if (isTerm(term, 'qvar', 1) || isTerm(term, 'qbnode', 1)) return format === 'n3' && typeof term.args[0] === 'string';
58
- if (isTerm(term, '.', 2)) {
59
- const items = properListItems(term, empty);
60
- return items !== null && items.every((item) => native(item, format));
61
- }
62
- if (isTerm(term, 'triple', 3)) return term.args.every((arg) => native(arg, format));
63
- if (isTerm(term, 'graph', 1) && format === 'n3') {
64
- const triples = properListItems(term.args[0], empty);
65
- return triples !== null && triples.every((t) => isTerm(t, 'rdf', 3) && t.args.every((arg) => native(arg, format)));
66
- }
67
- return false;
68
- }
69
-
70
- function view(term, format) {
71
- if (term instanceof Struct && ['rdf', 'result', 'inf', 'base'].includes(term.name) &&
72
- term.args.length === 3 && term.args.every((arg) => native(arg, format))) {
73
- return format === 'n3' ? new Struct('graph', [list([new Struct('rdf', term.args)])]) : new Struct('triple', term.args);
74
- }
75
- return encode(term);
76
- }
77
-
78
- function graph(terms, format) {
79
- const triples = [];
80
- const add = (subject, predicate, object) => triples.push([iri(subject), iri(predicate), object]);
81
- add(ROOT, `${RDF}type`, iri(`${PROOF_NS}Proof`));
82
- add(ROOT, `${TERM_NS}format`, literal(format));
83
- add(ROOT, `${PROOF_NS}claims`, list(terms.filter((term) => !record(term)).map((term) => view(term, format))));
84
- terms.forEach((term, i) => {
85
- const id = `${ROOT}#record${i + 1}`;
86
- if (isTerm(term, 'step', 4)) {
87
- const [goal, by, bindings, uses] = term.args;
88
- add(id, `${PROOF_NS}conclusion`, view(goal, format));
89
- if (isTerm(by, 'clause', 1)) add(id, `${PROOF_NS}rule`, by.args[0]);
90
- else if (isTerm(by, 'source', 1)) add(id, `${PROOF_NS}source`, by.args[0]);
91
- else add(id, `${PROOF_NS}justification`, encode(by));
92
- const pairs = properListItems(bindings, empty);
93
- const premises = properListItems(uses, empty);
94
- if (pairs === null || premises === null || !pairs.every((pair) => isTerm(pair, '=', 2))) {
95
- throw new EyemindError('a native proof step needs bindings and uses as lists');
96
- }
97
- add(id, `${PROOF_NS}binding`, list(pairs.map(({ args: [name, value] }) =>
98
- list([literal(name), native(value, format) ? value : encode(value)]))));
99
- add(id, `${PROOF_NS}uses`, list(premises.map((premise) => view(premise, format))));
100
- } else if (term instanceof Struct && ['derived', 'searched', 'called'].includes(term.name) && term.args.length === 2) {
101
- add(id, `${PROOF_NS}${term.name}`, view(term.args[0], format));
102
- const answers = properListItems(term.args[1], empty);
103
- if (answers === null) throw new EyemindError('a native proof certificate needs an answers list');
104
- add(id, `${PROOF_NS}answers`, list(answers.map((answer) => view(answer, format))));
105
- }
106
- });
107
- // Present the readable steps first; the full compiled certificate follows.
108
- add(ROOT, `${TERM_NS}records`, list(terms.map((_, i) => iri(`${ROOT}#record${i + 1}`))));
109
- terms.forEach((term, i) => add(`${ROOT}#record${i + 1}`, `${TERM_NS}term`, encode(term)));
110
- return triples;
111
- }
112
-
113
- function render(terms, format, prefixes) {
114
- const names = new Map(prefixes instanceof Map ? prefixes : Object.entries(prefixes ?? {}));
115
- names.set('pe', PROOF_NS);
116
- names.set('em', TERM_NS);
117
- names.set('proof', `${ROOT}#`);
118
- const text = writeN3(graph(terms, format), { prefixes: names, strings: false });
119
- if (format === 'n3') return `# N3 proof: claims, steps and the complete C1–C10 certificate.\n${text}`;
120
- const end = text.indexOf('\n\n');
121
- const declarations = text.slice(0, end).split('\n').map((line) => line.slice(1, -2).replace(/^prefix /, 'PREFIX '));
122
- // Do not indent or otherwise rewrite the body: long literals can contain
123
- // newlines and text that itself looks like a prefix declaration.
124
- return `# SRL proof: DATA only; claims, steps and the complete C1–C10 certificate.\n${declarations.join('\n')}\n\nDATA {\n${text.slice(end + 2)}}\n`;
125
- }
126
-
127
- export function writeNativeProof(document, { format = 'n3', prefixes = null } = {}) {
128
- if (!['n3', 'srl'].includes(format)) throw new EyemindError('a native proof format must be n3 or srl');
129
- return render(readTerms(document).map(([term]) => term), format, prefixes);
130
- }
131
-
132
- function fail(message) { throw new EyemindError(`native proof: ${message}`); }
133
- function string(term) {
134
- if (term?.t === 'literal' && term.dt === `${TERM_NS}utf16` && /^(?:[0-9a-f]{4})*$/.test(term.v)) {
135
- return term.v.replace(/[0-9a-f]{4}/g, (hex) => String.fromCharCode(parseInt(hex, 16)));
136
- }
137
- if (term?.t !== 'literal' || term.dt !== `${XSD}string` || term.lang) fail('expected a plain string or em:utf16 literal');
138
- return term.v;
139
- }
140
- function collection(term) {
141
- if (term?.t !== 'list') fail('expected an RDF collection');
142
- return term.items;
143
- }
144
- function decode(term) {
145
- const items = collection(term);
146
- const tag = items[0]?.t === 'iri' ? items[0].v.slice(TERM_NS.length) : '';
147
- if (items[0]?.v !== `${TERM_NS}${tag}`) fail('unknown term tag');
148
- if (tag === 'compound' && items.length === 3) return new Struct(string(items[1]), collection(items[2]).map(decode));
149
- if (items.length !== 2) fail('a tagged term has the wrong number of fields');
150
- if (tag === 'list') return list(collection(items[1]).map(decode));
151
- if (tag === 'iri' && items[1]?.t === 'iri') return iri(items[1].v);
152
- if (tag === 'iri' && items[1]?.t === 'list' && !items[1].items.length) return iri(`${RDF}nil`);
153
- const value = string(items[1]);
154
- if (tag === 'atom') return value;
155
- if (tag === 'variable') return new Var(value);
156
- if (tag === 'integer' && /^-?(?:0|[1-9][0-9]*)$/.test(value)) return BigInt(value);
157
- if (tag === 'float' && value !== '' && Number.isFinite(Number(value))) return Number(value);
158
- fail(`invalid ${tag} term`);
159
- }
160
-
161
- // SRL expands collection syntax into rdf:first/rest cells. Fold only closed,
162
- // reachable, unambiguous lists back into the same data AST that N3 reads.
163
- function srlData(document) {
164
- const parsed = new Parser(document, { strictGrammar: true }).parseProgram();
165
- if (parsed.rules.length || parsed.imports.length) fail('an SRL proof contains DATA, never RULE or IMPORTS');
166
- const term = (t) => {
167
- if (t.type === 'iri') return { t: 'iri', v: t.value };
168
- if (t.type === 'blank') return { t: 'bnode', v: t.value, scope: 0 };
169
- if (t.type === 'literal') {
170
- // A displayed decimal must not lose digits before its record is
171
- // compared: adjacent exact values can round to the same binary64.
172
- const value = t.lexical ?? (Object.is(t.value, -0) ? '-0' : String(t.value));
173
- return t.lang ? { t: 'literal', v: value, dt: `${RDF}langString`, lang: t.lang, dir: t.langDir }
174
- : typedLiteral(value, t.datatype ?? `${XSD}string`, true);
175
- }
176
- if (t.type === 'triple') return { t: 'triple', s: term(t.s), p: term(t.p), o: term(t.o) };
177
- fail('an SRL proof must be ground RDF data');
178
- };
179
- const triples = parsed.data.map((t) => ({ s: term(t.s), p: term(t.p), o: term(t.o) }));
180
- const cells = new Map();
181
- for (const t of triples) if (t.s.t === 'bnode' && [`${RDF}first`, `${RDF}rest`].includes(t.p.v)) {
182
- if (!cells.has(t.s.v)) cells.set(t.s.v, new Map());
183
- const cell = cells.get(t.s.v);
184
- if (cell.has(t.p.v)) fail('duplicate collection link');
185
- cell.set(t.p.v, t.o);
186
- }
187
- const used = new Set();
188
- const expand = (t, ancestors = new Set()) => {
189
- if (t.t === 'iri' && t.v === `${RDF}nil`) return { t: 'list', items: [] };
190
- if (t.t === 'triple') return { ...t, s: expand(t.s, ancestors), p: expand(t.p, ancestors), o: expand(t.o, ancestors) };
191
- if (t.t !== 'bnode' || !cells.has(t.v)) return t;
192
- // Keep only the active path: copying all ancestors for each nested list
193
- // makes a long list of encoded terms quadratic. Siblings may share cells.
194
- const path = [];
195
- const items = [];
196
- while (t.t === 'bnode' && cells.has(t.v)) {
197
- if (ancestors.has(t.v)) fail('cyclic collection');
198
- ancestors.add(t.v);
199
- path.push(t.v);
200
- const cell = cells.get(t.v);
201
- if (cell.size !== 2) fail('an RDF collection needs first and rest');
202
- used.add(t.v);
203
- items.push(expand(cell.get(`${RDF}first`), ancestors));
204
- t = cell.get(`${RDF}rest`);
205
- }
206
- if (t.t !== 'iri' || t.v !== `${RDF}nil`) fail('an RDF collection must end in rdf:nil');
207
- for (const id of path) ancestors.delete(id);
208
- return { t: 'list', items };
209
- };
210
- const out = triples.filter((t) => !(t.s.t === 'bnode' && cells.has(t.s.v) && [`${RDF}first`, `${RDF}rest`].includes(t.p.v)))
211
- .map((t) => ({ s: expand(t.s), p: expand(t.p), o: expand(t.o) }));
212
- if (used.size !== cells.size) fail('unreferenced collection data');
213
- return { triples: out };
214
- }
215
-
216
- // Display comparison permits prefix changes, triple reordering and consistent
217
- // blank-node renaming. Every property is checked, including claims and uses;
218
- // an extra assertion or an altered display cannot bypass the certificate.
219
- function compare(actual, expected) {
220
- const properties = (triples) => {
221
- const found = new Map();
222
- for (const t of triples) {
223
- if (t.s.t !== 'iri' || t.p.t !== 'iri') fail('unexpected assertion outside a proof record');
224
- const key = JSON.stringify([t.s.v, t.p.v]);
225
- if (found.has(key)) fail('duplicate proof property');
226
- found.set(key, t.o);
227
- }
228
- return found;
229
- };
230
- const a = properties(actual);
231
- const e = properties(expected);
232
- if (a.size !== e.size) fail('missing or extra proof properties');
233
- const names = new Map();
234
- const reverse = new Map();
235
- const same = (x, y) => {
236
- if (!x || !y || x.t !== y.t) return false;
237
- if (x.t === 'bnode') {
238
- const kx = `${x.scope}:${x.v}`, ky = `${y.scope}:${y.v}`;
239
- if (names.has(kx)) return names.get(kx) === ky;
240
- if (reverse.has(ky)) return false;
241
- names.set(kx, ky); reverse.set(ky, kx);
242
- return true;
243
- }
244
- if (x.t === 'list') return x.items.length === y.items.length && x.items.every((t, i) => same(t, y.items[i]));
245
- if (x.t === 'graph') return x.triples.length === y.triples.length && x.triples.every((t, i) => sameTriple(t, y.triples[i]));
246
- if (x.t === 'triple') return sameTriple(x, y);
247
- return Object.is(x.v, y.v) && x.dt === y.dt && (x.lang ?? null) === (y.lang ?? null) && (x.dir ?? null) === (y.dir ?? null);
248
- };
249
- const sameTriple = (x, y) => same(x.s, y.s) && same(x.p, y.p) && same(x.o, y.o);
250
- for (const [key, value] of e) if (!same(a.get(key), value)) fail(`a displayed proof property differs from its record: ${key}`);
251
- }
252
-
253
- // Read the graph reconstructed from records with N3's direct collections,
254
- // avoiding SRL's expansion into first/rest cells and folding them back again.
255
- // SRL folds every rdf:nil, including an explicit IRI, to ().
256
- function expectedData(terms, format) {
257
- const parsed = parseN3(writeN3(graph(terms, format), { strings: false }), { preserveNumericLiterals: true });
258
- if (format === 'n3') return parsed;
259
- const fold = (t) => {
260
- if (t.t === 'iri' && t.v === `${RDF}nil`) return { t: 'list', items: [] };
261
- if (t.t === 'list') return { ...t, items: t.items.map(fold) };
262
- if (t.t === 'triple') return { ...t, s: fold(t.s), p: fold(t.p), o: fold(t.o) };
263
- return t;
264
- };
265
- return { triples: parsed.triples.map((t) => ({ s: fold(t.s), p: fold(t.p), o: fold(t.o) })) };
266
- }
267
-
268
- function readNative(document) {
269
- let parsed, format;
270
- try { parsed = parseN3(document, { preserveNumericLiterals: true }); format = 'n3'; }
271
- catch (n3Error) {
272
- try { parsed = srlData(document); format = 'srl'; }
273
- catch (error) { throw new EyemindError(`native proof: ${error.message}`); }
274
- }
275
- const properties = new Map();
276
- for (const t of parsed.triples) {
277
- if (t.s.t !== 'iri' || t.p.t !== 'iri') fail('unexpected assertion outside a proof record');
278
- const key = JSON.stringify([t.s.v, t.p.v]);
279
- if (properties.has(key)) fail('duplicate proof record property');
280
- properties.set(key, t.o);
281
- }
282
- const property = (subject, predicate) => {
283
- const value = properties.get(JSON.stringify([subject, predicate]));
284
- if (!value) fail('missing proof record property');
285
- return value;
286
- };
287
- if (string(property(ROOT, `${TERM_NS}format`)) !== format) fail('proof format does not match its syntax');
288
- const ids = collection(property(ROOT, `${TERM_NS}records`));
289
- const terms = ids.map((id, i) => {
290
- if (id.t !== 'iri' || id.v !== `${ROOT}#record${i + 1}`) fail('proof records must be numbered in document order');
291
- return decode(property(id.v, `${TERM_NS}term`));
292
- });
293
- const expected = expectedData(terms, format);
294
- compare(parsed.triples, expected.triples);
295
- return terms;
296
- }
297
-
298
- export function readNativeProof(document) {
299
- try { return readNative(document); }
300
- catch (error) {
301
- if (error instanceof EyemindError) throw error;
302
- throw new EyemindError(`native proof: ${error.message}`);
303
- }
304
- }
305
-
306
- // The command line reads an SRL proof's execution context before checking
307
- // the same document, so the last native document read is kept.
308
- let lastNative = null;
309
-
310
- export function readProofTerms(document) {
311
- if (/^\s*(?:#|@|PREFIX\b|BASE\b|DATA\b|<|_:)/i.test(document)) {
312
- if (lastNative?.document !== document) lastNative = { document, terms: readNativeProof(document) };
313
- return lastNative.terms.map((term) => [term, 0]);
314
- }
315
- return readTerms(document);
316
- }