eyemind 0.5.7 → 0.5.8

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
@@ -143,7 +143,7 @@ for (let level = 1; level <= 10; level++) {
143
143
  - **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).
144
144
  - **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.
145
145
  - **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']))`.
146
- - **Data is not a program.** Everything eyemind writes is a *document* of 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.
146
+ - **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.
147
147
 
148
148
  ### Deriving rules
149
149
 
@@ -192,7 +192,7 @@ eyemind --to trig rules.js data.trig # the conclusions as TriG
192
192
  | Triple term | `triple(S, P, O)`, which may nest |
193
193
  | Default graph, named graph | `'default_graph'`, `iri(Name)` |
194
194
 
195
- A reified triple `<< s p o >>` and an annotation `{| ... |}` become their reifier and its `rdf:reifies` triple, as RDF 1.2 defines. A Skolem term is written as a blank node, the same one for the same rule firing. The RDF examples load Turtle or TriG files from `examples/data/` alongside companion rules in `examples/`. They show triple terms, annotations, directional strings, typed numbers and named graphs. The W3C RDF test suites run in `npm test` from the mirror in `test/w3c/rdf-tests`: all 1055 tests of N-Triples, N-Quads, Turtle and TriG, in RDF 1.1 and 1.2, pass.
195
+ A reified triple `<< s p o >>` and an annotation `{| ... |}` become their reifier and its `rdf:reifies` triple, as RDF 1.2 defines. A Skolem term is written as a blank node, the same one for the same rule firing. The RDF examples load Turtle or TriG files from `examples/data/` alongside companion rules in `examples/`. They show triple terms, annotations, directional strings, typed numbers and named graphs. The W3C RDF test suites run in `npm test` from the mirror in `test/w3c/rdf-tests`: all 1065 tests of N-Triples, N-Quads, Turtle and TriG, in RDF 1.1 and 1.2, pass.
196
196
 
197
197
  ### Notation3
198
198
 
@@ -251,7 +251,7 @@ Whole-log replay gives N3 or JavaScript rules an ordered view of the messages:
251
251
  ```sh
252
252
  eyemind examples/message-boundaries.n3 examples/data/message-boundaries.trig
253
253
  eyemind --proof examples/message-boundaries.n3 examples/data/message-boundaries.trig
254
- eyemind --check-proof examples/proof/message-boundaries.js examples/message-boundaries.n3 examples/data/message-boundaries.trig
254
+ eyemind --check-proof examples/proof/message-boundaries.n3 examples/message-boundaries.n3 examples/data/message-boundaries.trig
255
255
  ```
256
256
 
257
257
  The replay vocabulary is `eymsg:`, with namespace
@@ -331,7 +331,32 @@ The two work together: a forward rule's premise can call a backward definition,
331
331
 
332
332
  ## Proofs, and what checking one means
333
333
 
334
- A proof holds the claims, the source clauses it cites, and one `step(...)` per inference. Checking applies ten conditions:
334
+ A proof holds the claims, the source clauses it cites, and each recorded
335
+ inference. JavaScript programs write `step(...)` records. N3 inputs write
336
+ N3 proofs, and SRL inputs write SRL `DATA` proofs:
337
+
338
+ ```sh
339
+ eyemind --proof examples/socrates.n3 > /tmp/socrates-proof.n3
340
+ eyemind --check-proof /tmp/socrates-proof.n3 examples/socrates.n3
341
+ eyemind --proof examples/socrates.srl > /tmp/socrates-proof.srl
342
+ eyemind --check-proof /tmp/socrates-proof.srl examples/socrates.srl
343
+ ```
344
+
345
+ Native proofs use `pe:`, `https://eyereasoner.github.io/pe#`, for the claims,
346
+ conclusions, rule numbers, bindings and ordered uses. N3 displays statements
347
+ as quoted formulas; SRL displays them as RDF triple terms. Rule numbers name
348
+ clauses of the compiled eyemind program. The `em:` vocabulary,
349
+ `https://eyereasoner.github.io/eyemind/proof#`, keeps the exact terms and
350
+ ordered records, including all C9 search and C10 call tables. The checker
351
+ validates the displays against those records, then checks the certificate
352
+ against the source program. Altered displays, duplicate properties and extra
353
+ assertions fail checking. Proofs can be read as data by other N3 or SRL rules.
354
+
355
+ `--check-proof` recognizes the content, independently of the filename, and
356
+ continues to accept JavaScript certificates for native inputs. Check reports
357
+ remain JavaScript term documents, or JSON with `--json`.
358
+
359
+ Checking applies ten conditions:
335
360
 
336
361
  | | Condition | What it establishes |
337
362
  | --- | --- | --- |
@@ -474,6 +499,13 @@ console.log(checkProof(socrates, result.proof, { goals }).valid);
474
499
 
475
500
  `run()` returns `answers`, `bindings`, `inferred`, `stdout`, `proof`, `proofReport`, `stats` and `haltCode`, and takes `goal`, `goals`, `proof`, `maxDepth`, `maxIterations` and `maxInferences`; exceeding a bound throws an `EyemindError`. `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.
476
501
 
502
+ The core library's `result.proof` is the JavaScript certificate.
503
+ `writeNativeProof(result.proof, { format: 'n3', prefixes })` writes its N3
504
+ representation; use `format: 'srl'` for SRL. `readNativeProof(document)`
505
+ returns the decoded terms, and `readProofTerms(document)` reads any supported
506
+ proof as `[term, line]` pairs. Native records have line 0. `checkProof`
507
+ accepts all three representations and never evaluates proof text.
508
+
477
509
  ## What is deliberately absent
478
510
 
479
511
  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.
@@ -482,23 +514,47 @@ Cut, conditional commitment, mutable databases, attributed variables, constraint
482
514
 
483
515
  ```sh
484
516
  npm test # unit, examples, conformance, command line, playground
485
- npm test -- unit examples # only these sections
517
+ npm test -- unit examples # these sections, plus W3C EARL
486
518
  npm test -- -k skolem # only tests whose line contains "skolem"
487
519
  EYEMIND_PROPERTY_SCALE=20 npm test -- -k properties # deeper generated tests
488
520
  node tools/update-examples.js # regenerate example artifacts after an intended change
489
521
  node tools/report.js # the table npm test ends with, into REPORT.md
490
522
  node tools/notation3tests.js # the saved Notation3 suite, without network access
491
- node tools/sync-notation3tests.js # refresh its tests and document fixtures from upstream
523
+ npm run sync # refresh all three upstream test suites
492
524
  node conformance/run.js --command "my-eyemind" # run the conformance suite against another implementation
493
525
  ```
494
526
 
495
527
  The full suite needs a few GB of memory; on a small machine run it under a cap, such as `systemd-run --user --scope -q -p MemoryMax=3G -p MemorySwapMax=0 -- npm test`. Generated tests forge saved proofs at random and require the checker to reject every forgery that claims more than the program entails. The playground tests need Chrome (`CHROME` names it). When adding an example, register it in [examples/manifest.json](https://github.com/eyereasoner/eyemind/blob/main/examples/manifest.json), write its deck in `examples/deck/`, and generate its artifacts.
496
528
 
497
- The [Notation3 mirror](test/notation3tests/README.md) pins the upstream tests and their remote document inputs. Ordinary runs use those fixtures, with no network fallback. The sync command refreshes them for review; the scorer's `--live` option checks the current remote resources instead.
529
+ Every `npm test` invocation, including a filtered run, also runs both mirrored
530
+ W3C format suites and rewrites [reports/w3c-rdf-earl.ttl](reports/w3c-rdf-earl.ttl)
531
+ and [reports/w3c-sparql-rl-earl.ttl](reports/w3c-sparql-rl-earl.ttl).
532
+ These [EARL](https://www.w3.org/TR/EARL10-Schema/) reports contain one
533
+ assertion per manifest case, its actual outcome and diagnostic, the eyemind
534
+ version and the run date. A W3C failure makes the command fail. A negative
535
+ syntax test passes when the parser rejects its input as required.
536
+
537
+ `npm run sync` refreshes the [Notation3 mirror](test/notation3tests/README.md),
538
+ the [W3C RDF mirror and SPARQL RL mirror](test/w3c/README.md), and the
539
+ Notation3 document fixtures. It needs Git and network access. Each mirror
540
+ records its upstream revision in `upstream.json` and keeps upstream licensing
541
+ and documentation. Downloads and manifest resource checks finish before the
542
+ three generated mirrors are replaced; a failed refresh retains the old set.
543
+ Review the changes, then run `npm test` to verify the suites and refresh EARL.
544
+
545
+ Local Git checkouts can supply any of the sources:
546
+
547
+ ```sh
548
+ npm run sync -- --notation3tests /path/to/notation3tests --w3c-rdf /path/to/rdf-tests --w3c-sparql-rl /path/to/data-shapes
549
+ ```
550
+
551
+ `node tools/sync-notation3tests.js [UPSTREAM_CHECKOUT]` still refreshes only
552
+ Notation3. Ordinary test runs use saved documents with no network fallback;
553
+ the scorer's `--live` option checks the current remote resources instead.
498
554
 
499
555
  ### Releases
500
556
 
501
- `./release patch "Describe the changes"` (or `minor`, `major`) requires a clean tree, pulls `main`, runs the tests, bumps the version, and pushes `main` with an annotated tag. The tag creates the GitHub release, which Zenodo archives, and publishes to npm through trusted publishing, with no stored token. To publish an existing tag again, use **Actions → Publish to npm → Run workflow**.
557
+ `./release patch "Describe the changes"` (or `minor`, `major`) requires a clean tree, pulls `main`, runs the tests, bumps the version, refreshes and checks EARL with that version, and pushes `main` with an annotated tag. The tag creates the GitHub release, which Zenodo archives, and publishes to npm through trusted publishing, with no stored token. To publish an existing tag again, use **Actions → Publish to npm → Run workflow**.
502
558
 
503
559
  ## The name
504
560
 
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.7
5
+ Version: eyemind 0.5.8
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
@@ -2149,6 +2149,58 @@ describes the mappings. Such formats are outside conformance: a conforming
2149
2149
  implementation need not read them, and the suite does not test them. The
2150
2150
  proofs and checks of a compiled program are those of any program.
2151
2151
 
2152
+ For N3 and SRL inputs, `--proof` writes native proof data, `.n3` and `.srl`
2153
+ respectively. This is an additional representation of the complete proof of
2154
+ [Section 10](#10-proof-documents), outside conformance. JavaScript programs and the core library
2155
+ continue to write the canonical representation. `--check-proof` recognizes
2156
+ all three representations from their contents, regardless of filename;
2157
+ check reports retain the representation of [Section 12](#12-check-reports).
2158
+
2159
+ The native proof resource is `<urn:eyemind:proof>`, of type `pe:Proof`, where
2160
+ `pe:` is `https://eyereasoner.github.io/pe#` and `em:` is
2161
+ `https://eyereasoner.github.io/eyemind/proof#`. It has `em:format` equal to
2162
+ `"n3"` or `"srl"`, `pe:claims` as an ordered collection of claim displays,
2163
+ and `em:records` as an ordered collection of record IRIs. Record `N`, counted
2164
+ from 1, is `<urn:eyemind:proof#recordN>` and has one `em:term` containing its
2165
+ [Section 10](#10-proof-documents) statement, encoded as a tagged collection:
2166
+
2167
+ | Term | Collection |
2168
+ | --- | --- |
2169
+ | Atom | `(em:atom "text")` |
2170
+ | Integer | `(em:integer "digits")`, with a minus for a negative integer |
2171
+ | Float | `(em:float "number")`, preserving signed zero as `"-0"` |
2172
+ | Variable | `(em:variable "name")`, including anonymous-variable status |
2173
+ | `iri(I)` with an RDF-compatible IRI | `(em:iri <I>)` |
2174
+ | Nonempty proper list | `(em:list (EncodedItem ...))` |
2175
+ | Compound | `(em:compound "name" (EncodedArgument ...))` |
2176
+
2177
+ The empty list is the atom `"[]"`. Other compounds, including open lists,
2178
+ quoted graphs and Skolem terms, use the compound encoding. A string field
2179
+ containing a character RDF cannot represent uses an `em:utf16` typed literal
2180
+ whose lexical form is four lowercase hexadecimal digits per UTF-16 code
2181
+ unit. This retains every atom and variable name accepted by
2182
+ [Section 9.2](#92-canonical-atoms-numbers-variables-and-lists).
2183
+
2184
+ A triple goal's display is an N3 quoted formula, or an SRL RDF triple term.
2185
+ Other goals use their tagged encoding. A step record also displays
2186
+ `pe:conclusion`, `pe:rule` for a `clause(N)` justification, `pe:source` for
2187
+ `source(N)`, or `pe:justification` for another justification. `pe:binding`
2188
+ is an ordered collection of `(VariableName Value)` pairs, and `pe:uses` an
2189
+ ordered collection of premise displays. Non-native binding values retain
2190
+ their tagged encoding. Search records display `pe:derived`, `pe:searched`
2191
+ or `pe:called` and an ordered `pe:answers` collection. Clause numbers name
2192
+ the compiled program's clauses, whose authority is still the source input.
2193
+ SRL proofs contain only `DATA` and declarations, never rules or imports.
2194
+
2195
+ The reader decodes every record, verifies all displays and properties against
2196
+ those records, and applies the unchanged checks of
2197
+ [Section 11](#11-proof-checking) to the decoded
2198
+ certificate. A missing, extra, duplicate or inconsistent property fails C3.
2199
+ Prefix aliases and reordering top-level properties are accepted, as is
2200
+ consistent blank-node renaming; the order of collections and formula triples
2201
+ is retained. Displayed claims cannot replace encoded claims, and neither
2202
+ representation can change the source authority or supply missing evidence.
2203
+
2152
2204
  eyemind also reads RDF Message Logs in these four RDF syntaxes, announced by
2153
2205
  a `*-messages` version. Replay supplies ordered envelopes and quoted payloads
2154
2206
  to N3 or JavaScript rules; `--stream-messages` evaluates each message
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.7",
3
+ "version": "0.5.8",
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",
@@ -20,7 +20,8 @@
20
20
  "LICENSE.md"
21
21
  ],
22
22
  "scripts": {
23
- "test": "node test/run.js"
23
+ "test": "node test/run.js",
24
+ "sync": "node tools/sync.js"
24
25
  },
25
26
  "engines": {
26
27
  "node": ">=18"
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, loadInputs, rdfMessageFormat, scopeOf, writeConclusions } from './formats.js';
3
+ import { OUTPUT_FORMATS, defaultFormat, loadInputs, rdfMessageFormat, scopeOf, writeConclusions, writeProof } 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';
@@ -10,7 +10,7 @@ export const HELP = `Usage: eyemind [OPTION ...] [FILE ...]
10
10
  Programs are JavaScript; forward rules run to a fixpoint. Other files are read
11
11
  by their extension: .ttl, .trig, .nt and .nq as RDF 1.2 data, .n3 as Notation3
12
12
  and .srl as a SPARQL 1.2 RL rule set, both compiled to an eyemind program.
13
- -p, --proof Print the claims with clause(...) and step(...) records
13
+ -p, --proof Print a proof in the input's format (JavaScript, N3, SRL)
14
14
  -c, --prove-and-check Generate a proof and check it against the input program
15
15
  --check-proof FILE Print checked answers and a proof check report (- for stdin)
16
16
  --json Print the check report as JSON instead
@@ -207,7 +207,7 @@ export function main(argv, io) {
207
207
  return report.valid ? result.haltCode || 0 : 2;
208
208
  }
209
209
  // Answers to goals are eyemind terms unless an output format is asked.
210
- const written = options.proof ? null : writeConclusions(loaded, result, {
210
+ const written = options.proof ? writeProof(loaded, result, { goals }) : writeConclusions(loaded, result, {
211
211
  format: format ?? (goals.length ? 'eyemind' : defaultFormat(loaded.kind)), all, blankNodePrefix: io.blankNodePrefix,
212
212
  });
213
213
  stdout(written ?? result.stdout);
package/src/formats.js CHANGED
@@ -22,6 +22,8 @@ import { answersToN3, compileSources } from './n3.js';
22
22
  import { compileSrl, 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';
25
27
 
26
28
  export const OUTPUT_FORMATS = ['eyemind', 'turtle', 'trig', 'n-triples', 'n-quads', 'n3'];
27
29
 
@@ -120,6 +122,16 @@ function importResolver(io) {
120
122
  // eyemind's own text for a program.
121
123
  export const defaultFormat = (kind) => ({ n3: 'n3', srl: 'turtle' })[kind] ?? 'eyemind';
122
124
 
125
+ // The core certificate keeps its specified JavaScript form. Native inputs
126
+ // expose the same evidence as N3 or SRL data at the format boundary.
127
+ export function writeProof(loaded, result, { goals = null } = {}) {
128
+ if (loaded.kind === 'js') return result.proof;
129
+ const document = writeNativeProof(result.proof, { format: loaded.kind, prefixes: loaded.prefixes });
130
+ const report = checkProof(loaded.program, document, { goals });
131
+ if (!report.valid) throw new EyemindError(`generated ${loaded.kind} proof failed verification: ${report.failures[0].detail}`);
132
+ return document;
133
+ }
134
+
123
135
  // The conclusions of a run in an output format; null for eyemind's own text.
124
136
  // all also writes the given data. Throws when a conclusion is no triple.
125
137
  export function writeConclusions(loaded, result, { format, all = false, blankNodePrefix = '' } = {}) {
package/src/index.js CHANGED
@@ -10,6 +10,7 @@ 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';
13
14
  export { readTerm, readTerms } from './reader.js';
14
15
  export { EyemindError, Struct, Var } from './terms.js';
15
16
  export { write } from './writer.js';
@@ -0,0 +1,288 @@
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
+ const value = Object.is(t.value, -0) ? '-0' : String(t.value);
171
+ return t.lang ? { t: 'literal', v: value, dt: `${RDF}langString`, lang: t.lang, dir: t.langDir }
172
+ : typedLiteral(value, t.datatype ?? `${XSD}string`);
173
+ }
174
+ if (t.type === 'triple') return { t: 'triple', s: term(t.s), p: term(t.p), o: term(t.o) };
175
+ fail('an SRL proof must be ground RDF data');
176
+ };
177
+ const triples = parsed.data.map((t) => ({ s: term(t.s), p: term(t.p), o: term(t.o) }));
178
+ const cells = new Map();
179
+ for (const t of triples) if (t.s.t === 'bnode' && [`${RDF}first`, `${RDF}rest`].includes(t.p.v)) {
180
+ if (!cells.has(t.s.v)) cells.set(t.s.v, new Map());
181
+ const cell = cells.get(t.s.v);
182
+ if (cell.has(t.p.v)) fail('duplicate collection link');
183
+ cell.set(t.p.v, t.o);
184
+ }
185
+ const used = new Set();
186
+ const expand = (t, ancestors = new Set()) => {
187
+ if (t.t === 'iri' && t.v === `${RDF}nil`) return { t: 'list', items: [] };
188
+ if (t.t === 'triple') return { ...t, s: expand(t.s, ancestors), p: expand(t.p, ancestors), o: expand(t.o, ancestors) };
189
+ if (t.t !== 'bnode' || !cells.has(t.v)) return t;
190
+ const path = new Set(ancestors);
191
+ const items = [];
192
+ while (t.t === 'bnode' && cells.has(t.v)) {
193
+ if (path.has(t.v)) fail('cyclic collection');
194
+ path.add(t.v);
195
+ const cell = cells.get(t.v);
196
+ if (cell.size !== 2) fail('an RDF collection needs first and rest');
197
+ used.add(t.v);
198
+ items.push(expand(cell.get(`${RDF}first`), path));
199
+ t = cell.get(`${RDF}rest`);
200
+ }
201
+ if (t.t !== 'iri' || t.v !== `${RDF}nil`) fail('an RDF collection must end in rdf:nil');
202
+ return { t: 'list', items };
203
+ };
204
+ const out = triples.filter((t) => !(t.s.t === 'bnode' && cells.has(t.s.v) && [`${RDF}first`, `${RDF}rest`].includes(t.p.v)))
205
+ .map((t) => ({ s: expand(t.s), p: expand(t.p), o: expand(t.o) }));
206
+ if (used.size !== cells.size) fail('unreferenced collection data');
207
+ return { triples: out };
208
+ }
209
+
210
+ // Display comparison permits prefix changes, triple reordering and consistent
211
+ // blank-node renaming. Every property is checked, including claims and uses;
212
+ // an extra assertion or an altered display cannot bypass the certificate.
213
+ function compare(actual, expected) {
214
+ const properties = (triples) => {
215
+ const found = new Map();
216
+ for (const t of triples) {
217
+ if (t.s.t !== 'iri' || t.p.t !== 'iri') fail('unexpected assertion outside a proof record');
218
+ const key = JSON.stringify([t.s.v, t.p.v]);
219
+ if (found.has(key)) fail('duplicate proof property');
220
+ found.set(key, t.o);
221
+ }
222
+ return found;
223
+ };
224
+ const a = properties(actual);
225
+ const e = properties(expected);
226
+ if (a.size !== e.size) fail('missing or extra proof properties');
227
+ const names = new Map();
228
+ const reverse = new Map();
229
+ const same = (x, y) => {
230
+ if (!x || !y || x.t !== y.t) return false;
231
+ if (x.t === 'bnode') {
232
+ const kx = `${x.scope}:${x.v}`, ky = `${y.scope}:${y.v}`;
233
+ if (names.has(kx)) return names.get(kx) === ky;
234
+ if (reverse.has(ky)) return false;
235
+ names.set(kx, ky); reverse.set(ky, kx);
236
+ return true;
237
+ }
238
+ if (x.t === 'list') return x.items.length === y.items.length && x.items.every((t, i) => same(t, y.items[i]));
239
+ if (x.t === 'graph') return x.triples.length === y.triples.length && x.triples.every((t, i) => sameTriple(t, y.triples[i]));
240
+ if (x.t === 'triple') return sameTriple(x, y);
241
+ return Object.is(x.v, y.v) && x.dt === y.dt && (x.lang ?? null) === (y.lang ?? null) && (x.dir ?? null) === (y.dir ?? null);
242
+ };
243
+ const sameTriple = (x, y) => same(x.s, y.s) && same(x.p, y.p) && same(x.o, y.o);
244
+ for (const [key, value] of e) if (!same(a.get(key), value)) fail(`a displayed proof property differs from its record: ${key}`);
245
+ }
246
+
247
+ function readNative(document) {
248
+ let parsed, format;
249
+ try { parsed = parseN3(document); format = 'n3'; }
250
+ catch (n3Error) {
251
+ try { parsed = srlData(document); format = 'srl'; }
252
+ catch (error) { throw new EyemindError(`native proof: ${error.message}`); }
253
+ }
254
+ const properties = new Map();
255
+ for (const t of parsed.triples) {
256
+ if (t.s.t !== 'iri' || t.p.t !== 'iri') fail('unexpected assertion outside a proof record');
257
+ const key = JSON.stringify([t.s.v, t.p.v]);
258
+ if (properties.has(key)) fail('duplicate proof record property');
259
+ properties.set(key, t.o);
260
+ }
261
+ const property = (subject, predicate) => {
262
+ const value = properties.get(JSON.stringify([subject, predicate]));
263
+ if (!value) fail('missing proof record property');
264
+ return value;
265
+ };
266
+ if (string(property(ROOT, `${TERM_NS}format`)) !== format) fail('proof format does not match its syntax');
267
+ const ids = collection(property(ROOT, `${TERM_NS}records`));
268
+ const terms = ids.map((id, i) => {
269
+ if (id.t !== 'iri' || id.v !== `${ROOT}#record${i + 1}`) fail('proof records must be numbered in document order');
270
+ return decode(property(id.v, `${TERM_NS}term`));
271
+ });
272
+ const expected = format === 'n3' ? parseN3(render(terms, format)) : srlData(render(terms, format));
273
+ compare(parsed.triples, expected.triples);
274
+ return terms;
275
+ }
276
+
277
+ export function readNativeProof(document) {
278
+ try { return readNative(document); }
279
+ catch (error) {
280
+ if (error instanceof EyemindError) throw error;
281
+ throw new EyemindError(`native proof: ${error.message}`);
282
+ }
283
+ }
284
+
285
+ export function readProofTerms(document) {
286
+ if (/^\s*(?:#|@|PREFIX\b|BASE\b|DATA\b|<|_:)/i.test(document)) return readNativeProof(document).map((term) => [term, 0]);
287
+ return readTerms(document);
288
+ }
package/src/proof.js CHANGED
@@ -6,6 +6,8 @@
6
6
  // implied_by(...)), then one step(Goal, By, Bindings, Uses) per inference,
7
7
  // then the search certificate that settles its negations and collections. The
8
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.
9
11
  //
10
12
  // Verification follows recorded uses; it never asks the solver to find a
11
13
  // missing derivation. Only pure primitives are independently recomputed.
@@ -16,7 +18,7 @@ import { goalTerm } from './goals.js';
16
18
  import { checkCalls } from './fidelity.js';
17
19
  import { INSPECTION_KEYS, isInspection } from './inspection.js';
18
20
  import { CONTROL_KEYS, Program } from './program.js';
19
- import { readTerms } from './reader.js';
21
+ import { readProofTerms } from './native-proof.js';
20
22
  import {
21
23
  Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, flattenConjunction, freshTerm,
22
24
  isCallable, isFloat, isGround, isTerm, key, keyArity, keyName, listFromItems, properListItems, unify, variables,
@@ -402,7 +404,7 @@ function readDocument(program, document, fail, spellings) {
402
404
  const certificate = { tables: new Map(), calls: new Map(), listings: new Map(), order: [] };
403
405
  const empty = new Env();
404
406
  try {
405
- for (const [term] of readTerms(document)) {
407
+ for (const [term] of readProofTerms(document)) {
406
408
  if (isTerm(term, 'searched', 2) || isTerm(term, 'derived', 2) || isTerm(term, 'called', 2)) {
407
409
  readCertificate(term, certificate, fail, empty);
408
410
  continue;
package/src/rdf.js CHANGED
@@ -135,9 +135,13 @@ function literalTerm(raw) {
135
135
  const tagged = /^(".*")@([A-Za-z]+(?:-[A-Za-z0-9]+)*)(?:--(ltr|rtl))?$/s.exec(text);
136
136
  if (tagged) {
137
137
  const lang = tagged[2].toLowerCase();
138
+ if (!/^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/.test(lang)) throw new SyntaxError(`invalid RDF 1.2 language tag @${tagged[2]}`);
138
139
  return st('literal', unquote(tagged[1]), tagged[3] ? st('lang', lang, tagged[3]) : st('lang', lang));
139
140
  }
140
141
  const [lexical, datatype] = literalParts(text);
142
+ if (datatype === `${RDF_NS}langString` || datatype === `${RDF_NS}dirLangString`) {
143
+ throw new SyntaxError(`RDF datatype ${datatype} requires a language tag`);
144
+ }
141
145
  const quoted = typeof lexical === 'string' && lexical.length >= 2 && lexical[0] === '"' && lexical.at(-1) === '"';
142
146
  const value = quoted ? unquote(lexical) : lexical;
143
147
  return literalOf(value, datatype ?? (quoted ? `${XSD}string` : bareDatatype(value)));
package/src/srl-parser.js CHANGED
@@ -29,6 +29,10 @@ class Parser {
29
29
  this.version = null;
30
30
  this.imports = [];
31
31
  this.bnodeCounter = 0;
32
+ // eyemind: collection/property-list nodes must not capture an explicit
33
+ // blank-node label, including a label appearing later in the document.
34
+ this.usedBlankNodeLabels = new Set(this.tokens.filter((token) => token.type === 'word' && token.value.startsWith('_:'))
35
+ .map((token) => token.value.slice(2)));
32
36
  this.bodyBnodeLabels = null;
33
37
  // Body blank nodes must become variables not used anywhere in the rule,
34
38
  // including in the head or in expressions that occur later in the body.
@@ -228,7 +232,8 @@ class Parser {
228
232
  freshGraphNode(options = {}) {
229
233
  do {
230
234
  this.bnodeCounter += 1;
231
- } while (options.context === 'body' && this.usedVariableNames.has(`__b${this.bnodeCounter}`));
235
+ } while (this.usedBlankNodeLabels.has(`b${this.bnodeCounter}`) ||
236
+ (options.context === 'body' && this.usedVariableNames.has(`__b${this.bnodeCounter}`)));
232
237
  const id = `b${this.bnodeCounter}`;
233
238
  if (options.context !== 'body') return blankNode(id);
234
239
  this.usedVariableNames.add(`__${id}`);
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.7';
2
+ export const VERSION = '0.5.8';