eyemind 0.5.6 → 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.
@@ -0,0 +1,263 @@
1
+ // RDF Message Logs: delimit datasets before parsing them, so blank nodes and
2
+ // assertions stay local to a message. The replay view is ordinary N3 data.
3
+ // See https://w3c-cg.github.io/rsp/spec/messages and its companion tests.
4
+ import { DEFAULT_GRAPH, parseRdf } from './rdf.js';
5
+ import { readSources } from './n3.js';
6
+ import { tripleToEyemind } from './n3-writer.js';
7
+ import { EyemindError } from './terms.js';
8
+
9
+ export const MESSAGE_NS = 'https://eyereasoner.github.io/eyeling/vocab/message#';
10
+ const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
11
+ const LOG_NAME = 'http://www.w3.org/2000/10/swap/log#nameOf';
12
+ const GRAPH_CONTENT = 'https://eyereasoner.github.io/eyemind/graph#content';
13
+ const iri = (v) => ({ t: 'iri', v });
14
+ const triple = (s, p, o) => ({ s, p: iri(p), o });
15
+ const int = (v) => ({ t: 'int', v: BigInt(v) });
16
+ const wordEnd = (c) => c === undefined || /[\s<>"'{}\[\]();,]/.test(c);
17
+ const iriText = (v) => v.replace(/[\u0000-\u0020<>"{}|^`\\]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
18
+ function trivia(s, at, final) {
19
+ while (at < s.length) {
20
+ if (/\s/.test(s[at])) at++;
21
+ else if (s[at] === '#') {
22
+ const end = s.slice(at).search(/[\r\n]/);
23
+ if (end < 0) return final ? s.length : null;
24
+ at += end;
25
+ } else break;
26
+ }
27
+ return at;
28
+ }
29
+
30
+ // Accept strings incrementally. Only the current message and active directive
31
+ // context are retained; onMessage runs before reading any further input.
32
+ export class RdfMessageReader {
33
+ constructor({ format = 'trig', base = null, scope = 'messages', onMessage = () => {}, probe = false } = {}) {
34
+ if (!['turtle', 'trig', 'n-triples', 'n-quads'].includes(format)) throw new EyemindError(`RDF Messages do not support the format ${format}`);
35
+ this.format = format;
36
+ this.base = base;
37
+ this.scope = scope;
38
+ this.onMessage = onMessage;
39
+ this.probe = probe;
40
+ this.buffer = '';
41
+ this.at = 0;
42
+ this.quote = null;
43
+ this.comment = false;
44
+ this.inIri = false;
45
+ this.stack = [];
46
+ this.prefixes = {};
47
+ this.index = 0;
48
+ this.version = null;
49
+ this.isLog = false;
50
+ this.stopped = false;
51
+ this.hasPayload = false;
52
+ this.directive = false;
53
+ }
54
+
55
+ write(text) {
56
+ if (this.stopped) return;
57
+ this.buffer += text;
58
+ this.scan(false);
59
+ if (this.probe) {
60
+ this.buffer = this.buffer.slice(this.at);
61
+ this.at = 0;
62
+ }
63
+ }
64
+
65
+ finish() {
66
+ if (this.stopped) { this.buffer = ''; return; }
67
+ this.scan(true);
68
+ if (!this.probe) {
69
+ if (!this.isLog) throw new EyemindError('RDF Message Log needs a VERSION "*-messages" directive');
70
+ this.emit(this.buffer, false);
71
+ }
72
+ this.buffer = '';
73
+ }
74
+
75
+ emit(text, boundary) {
76
+ if (this.probe) return;
77
+ const line = this.format === 'n-triples' || this.format === 'n-quads';
78
+ const context = line ? '' : Object.entries(this.prefixes).map(([name, ns]) => `PREFIX ${name}: <${iriText(ns)}>\n`).join('');
79
+ const number = this.index + 1;
80
+ try {
81
+ const parsed = parseRdf(`${context}${text}`, { format: this.format, base: this.base, scope: `${this.scope}#message${this.index + 1}` });
82
+ this.base = parsed.base;
83
+ this.prefixes = parsed.prefixes;
84
+ // A delimiter closes even an empty message. EOF opens no new message
85
+ // for a trailing delimiter, comments or directives alone.
86
+ if (boundary || parsed.quads.length) this.stopped = this.onMessage({ ...parsed, index: ++this.index }) === false;
87
+ } catch (error) {
88
+ throw new EyemindError(`RDF Message Log message ${number}: ${error.message}`);
89
+ }
90
+ }
91
+
92
+ scan(final) {
93
+ while (!this.stopped && this.at < this.buffer.length) {
94
+ const s = this.buffer;
95
+ const i = this.at;
96
+ const c = s[i];
97
+ if (this.comment) {
98
+ if (c === '\n' || c === '\r') this.comment = false;
99
+ this.at++;
100
+ } else if (this.quote) {
101
+ if (c === '\\') {
102
+ if (i + 1 === s.length && !final) break;
103
+ this.at += 2;
104
+ } else if (c === this.quote[0]) {
105
+ if (i + this.quote.length > s.length && !final) break;
106
+ if (s.startsWith(this.quote, i)) {
107
+ this.at += this.quote.length;
108
+ this.quote = null;
109
+ } else this.at++;
110
+ } else this.at++;
111
+ } else if (this.inIri) {
112
+ this.at++;
113
+ if (c === '>') {
114
+ this.inIri = false;
115
+ this.directive = false;
116
+ }
117
+ } else if (/\s|\uFEFF/.test(c)) this.at++;
118
+ else if (c === '#') {
119
+ this.comment = true;
120
+ this.at++;
121
+ } else if (c === '"' || c === "'") {
122
+ if (i + 3 > s.length && !final) break;
123
+ this.quote = s.startsWith(c.repeat(3), i) ? c.repeat(3) : c;
124
+ if (!this.directive) this.hasPayload = true;
125
+ this.at += this.quote.length;
126
+ } else if (c === '<') {
127
+ if (i + 1 === s.length && !final) break;
128
+ if (s[i + 1] === '<') {
129
+ if (!this.probe && this.version !== '1.2') throw new EyemindError('triple terms require VERSION "1.2-messages"');
130
+ this.stack.push('>>');
131
+ this.at += 2;
132
+ } else {
133
+ if (!this.directive) this.hasPayload = true;
134
+ this.inIri = true;
135
+ this.at++;
136
+ }
137
+ } else if (c === '>' && i + 1 === s.length && !final) break;
138
+ else if (s.startsWith('>>', i)) {
139
+ if (this.stack.at(-1) === '>>') this.stack.pop();
140
+ this.at += 2;
141
+ } else if ('{[('.includes(c)) {
142
+ if (c === '{' && i + 1 === s.length && !final) break;
143
+ if (!this.probe && c === '{' && s[i + 1] === '|' && this.version !== '1.2') {
144
+ throw new EyemindError('annotations require VERSION "1.2-messages"');
145
+ }
146
+ this.hasPayload = true;
147
+ this.stack.push({ '{': '}', '[': ']', '(': ')' }[c]);
148
+ this.at++;
149
+ } else if ('}])'.includes(c)) {
150
+ if (this.stack.at(-1) === c) this.stack.pop();
151
+ this.at++;
152
+ } else if (';,'.includes(c) || c === '>') this.at++;
153
+ else {
154
+ let end = i;
155
+ while (end < s.length && !wordEnd(s[end])) end += s[end] === '\\' ? 2 : 1;
156
+ if (end >= s.length && !final) break;
157
+ const word = s.slice(i, end);
158
+ if (word.toUpperCase() === 'VERSION' || word === '@version') {
159
+ const rest = s.slice(end);
160
+ const match = /^\s+(["'])([^"'\r\n]*)\1/.exec(rest);
161
+ if (!match) {
162
+ if (!final && /^\s*(?:["'][^"'\r\n]*)?$/.test(rest)) break;
163
+ throw new EyemindError(`${word} needs a short quoted version label`);
164
+ }
165
+ if (this.stack.length) throw new EyemindError('VERSION is only allowed between statements');
166
+ const label = match[2];
167
+ this.isLog ||= label.endsWith('-messages');
168
+ const version = label.replace(/-messages$/, '');
169
+ if (!this.probe && (!this.isLog || !['1.1', '1.2-basic', '1.2'].includes(version))) {
170
+ throw new EyemindError(`unsupported RDF Message Log version: ${label}`);
171
+ }
172
+ this.version = version;
173
+ // Keep the underlying directive for the strict RDF parser to check
174
+ // its spelling, placement and punctuation in the selected format.
175
+ const valueStart = end + match[0].indexOf(match[1]);
176
+ const valueEnd = end + match[0].length;
177
+ this.buffer = `${s.slice(0, valueStart)}${match[1]}${version}${match[1]}${s.slice(valueEnd)}`;
178
+ this.at = valueStart + version.length + 2;
179
+ } else if (word.toUpperCase() === 'MESSAGE' || /^@message(?:\.|$)/.test(word)) {
180
+ if (!this.isLog && !this.probe) throw new EyemindError('MESSAGE needs a VERSION "*-messages" directive');
181
+ if (this.stack.length) throw new EyemindError('MESSAGE is only allowed between top-level statements');
182
+ if (word.toUpperCase() !== 'MESSAGE') {
183
+ const dot = trivia(s, i + 8, final);
184
+ if (dot === null || (dot === s.length && !final)) break;
185
+ if (s[dot] !== '.') {
186
+ throw new EyemindError('@message ends with a dot');
187
+ }
188
+ if (this.format === 'n-triples' || this.format === 'n-quads') throw new EyemindError('@message is not allowed in N-Triples or N-Quads; write MESSAGE');
189
+ end = dot + 1;
190
+ }
191
+ if (this.format === 'n-triples' || this.format === 'n-quads') {
192
+ if (word !== 'MESSAGE') throw new EyemindError('MESSAGE is case-sensitive in N-Triples and N-Quads');
193
+ const start = Math.max(s.lastIndexOf('\n', i - 1), s.lastIndexOf('\r', i - 1)) + 1;
194
+ const newline = s.slice(end).search(/[\r\n]/);
195
+ if (newline < 0 && !final) break;
196
+ const rest = s.slice(end, newline < 0 ? s.length : end + newline).replace(/#.*$/, '');
197
+ if (s.slice(start, i).trim() || rest.trim()) throw new EyemindError('MESSAGE must be on its own line in N-Triples and N-Quads');
198
+ }
199
+ this.emit(s.slice(0, i), true);
200
+ this.buffer = s.slice(end);
201
+ this.at = 0;
202
+ } else {
203
+ if (!this.probe && this.version === '1.1' && /^@[A-Za-z].*--(?:ltr|rtl)(?:\.|$)/.test(word)) {
204
+ throw new EyemindError('directional language strings require RDF 1.2 Messages');
205
+ }
206
+ if (!this.probe && this.version !== '1.2' && /(^|[^\\])~/.test(word)) {
207
+ throw new EyemindError('reification syntax requires VERSION "1.2-messages"');
208
+ }
209
+ if (['PREFIX', 'BASE'].includes(word.toUpperCase()) || ['@prefix', '@base'].includes(word)) this.directive = true;
210
+ else if (word !== '.' && !this.directive) this.hasPayload = true;
211
+ this.at = end;
212
+ }
213
+ }
214
+ }
215
+ }
216
+ }
217
+
218
+ export function isRdfMessageLog(text) {
219
+ const reader = new RdfMessageReader({ probe: true });
220
+ try {
221
+ reader.write(String(text));
222
+ reader.finish();
223
+ } catch { /* The selected parser reports malformed inputs. */ }
224
+ return reader.isLog;
225
+ }
226
+
227
+ // Materialize the application's replay vocabulary. Neither envelope links nor
228
+ // log:nameOf assert the payload's triples in the surrounding default graph.
229
+ export function replayMessages(messages, { scope = 'messages' } = {}) {
230
+ const root = `urn:eyemind:message-log:${encodeURIComponent(scope)}`;
231
+ const stream = iri(`${root}#stream`);
232
+ const envelopes = messages.map((m) => iri(`${root}#message${m.index}`));
233
+ const triples = [triple(stream, RDF_TYPE, iri(`${MESSAGE_NS}RDFMessageStream`)),
234
+ triple(stream, `${MESSAGE_NS}messageCount`, int(messages.length)),
235
+ triple(stream, `${MESSAGE_NS}orderedEnvelopes`, { t: 'list', items: envelopes })];
236
+ if (envelopes.length) triples.push(triple(stream, `${MESSAGE_NS}firstEnvelope`, envelopes[0]),
237
+ triple(stream, `${MESSAGE_NS}lastEnvelope`, envelopes.at(-1)));
238
+ const prefixes = { eymsg: MESSAGE_NS };
239
+ messages.forEach((message, i) => {
240
+ Object.assign(prefixes, message.prefixes);
241
+ const envelope = envelopes[i];
242
+ triples.push(triple(stream, `${MESSAGE_NS}envelope`, envelope),
243
+ triple(envelope, RDF_TYPE, iri(`${MESSAGE_NS}MessageEnvelope`)),
244
+ triple(envelope, `${MESSAGE_NS}offset`, int(message.index)),
245
+ triple(envelope, `${MESSAGE_NS}payloadKind`, iri(`${MESSAGE_NS}${message.quads.length ? 'nonEmpty' : 'empty'}`)));
246
+ if (envelopes[i + 1]) triples.push(triple(envelope, `${MESSAGE_NS}nextEnvelope`, envelopes[i + 1]));
247
+ if (message.quads.length) {
248
+ const payload = iri(`${envelope.v}/payload`);
249
+ const contents = readSources([message]).triples.map((t) => t.p.v === GRAPH_CONTENT && t.o.t === 'graph' ? { ...t, p: iri(LOG_NAME) } : t);
250
+ triples.push(triple(envelope, `${MESSAGE_NS}payloadGraph`, payload),
251
+ triple(payload, LOG_NAME, { t: 'graph', triples: contents, scope: 0 }));
252
+ }
253
+ });
254
+ return { triples, prefixes, quads: triples.map((t) => [...tripleToEyemind(t), DEFAULT_GRAPH]) };
255
+ }
256
+
257
+ export function parseRdfMessages(text, options = {}) {
258
+ const messages = [];
259
+ const reader = new RdfMessageReader({ ...options, onMessage: (m) => messages.push(m) });
260
+ reader.write(String(text));
261
+ reader.finish();
262
+ return { ...replayMessages(messages, options), messages };
263
+ }
package/src/n3-writer.js CHANGED
@@ -38,8 +38,8 @@ function tripleTerm(term) {
38
38
  // N3 text for triples given as [S, P, O] eyemind terms. With strings
39
39
  // 'auto', a result that has log:outputString triples is written as their
40
40
  // strings, ordered by subject, as N3 reasoners do.
41
- export function writeN3(triples, { prefixes = new Map(), strings = 'auto' } = {}) {
42
- const w = new Writer(prefixes);
41
+ export function writeN3(triples, { prefixes = new Map(), strings = 'auto', blankNodePrefix = '' } = {}) {
42
+ const w = new Writer(prefixes, blankNodePrefix);
43
43
  const outputs = triples.filter(([, p]) => isIri(p, `${LOG}outputString`));
44
44
  if (strings === true || (strings === 'auto' && outputs.length > 0)) {
45
45
  const keyed = outputs.map(([s, , o], i) => ({ s, o, i }));
@@ -99,10 +99,11 @@ function compareKeys(a, b) {
99
99
  const PN_LOCAL = /^(?:[A-Za-z_0-9À-�]|:)(?:[A-Za-z_0-9·À-�.:-]*[A-Za-z_0-9·À-�:-])?$/u;
100
100
 
101
101
  class Writer {
102
- constructor(prefixes) {
102
+ constructor(prefixes, blankNodePrefix) {
103
103
  this.prefixes = [...prefixes].sort((a, b) => b[1].length - a[1].length);
104
104
  this.used = new Set();
105
105
  this.bnodes = new Map();
106
+ this.blankNodePrefix = blankNodePrefix;
106
107
  }
107
108
 
108
109
  iri(v) {
@@ -126,7 +127,7 @@ class Writer {
126
127
  }
127
128
 
128
129
  bnode(key) {
129
- if (!this.bnodes.has(key)) this.bnodes.set(key, `_:b${this.bnodes.size}`);
130
+ if (!this.bnodes.has(key)) this.bnodes.set(key, `_:${this.blankNodePrefix}b${this.bnodes.size}`);
130
131
  return this.bnodes.get(key);
131
132
  }
132
133
 
package/src/n3.js CHANGED
@@ -804,7 +804,7 @@ export function readSources(sources, { base = '', baseOf = () => '' } = {}) {
804
804
  if (typeof sources === 'string') sources = [[sources, 'input']];
805
805
  const docs = sources.map((source) => (Array.isArray(source)
806
806
  ? parseN3(source[0], { base: base || baseOf(source[1]) })
807
- : { triples: rdfQuadsToN3(source.quads), prefixes: new Map(Object.entries(source.prefixes ?? {})) }));
807
+ : { triples: source.triples ?? rdfQuadsToN3(source.quads), prefixes: new Map(Object.entries(source.prefixes ?? {})) }));
808
808
  const doc = { triples: [], prefixes: new Map() };
809
809
  const graphs = new Map();
810
810
  docs.forEach((d, k) => {
@@ -840,12 +840,12 @@ const sourceNames = (sources) => (typeof sources === 'string' ? 'input' : source
840
840
  // The triples of eyemind answers as N3: the derived ones, every triple with
841
841
  // mode 'all', and the document's own log:outputString strings when the
842
842
  // result writes strings.
843
- export function answersToN3(doc, answers, { mode = 'new', strings = 'auto' } = {}) {
843
+ export function answersToN3(doc, answers, { mode = 'new', strings = 'auto', blankNodePrefix = '' } = {}) {
844
844
  let { triples, contradiction } = triplesFromEyemind(answers.join('\n'));
845
845
  const given = doc.triples.filter((x) => !isRule(x)).map(tripleToEyemind);
846
846
  if (mode === 'all') triples = [...given, ...triples];
847
847
  else if (strings !== false && triples.some(isOutputString)) triples = [...given.filter(isOutputString), ...triples];
848
- return { n3: writeN3(triples, { prefixes: doc.prefixes, strings }), triples, contradiction };
848
+ return { n3: writeN3(triples, { prefixes: doc.prefixes, strings, blankNodePrefix }), triples, contradiction };
849
849
  }
850
850
 
851
851
  // Generous bounds: N3 programs often run longer than eyemind's defaults.
@@ -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
+ }