eyeling 1.27.6 → 1.27.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
@@ -3,20 +3,1239 @@
3
3
  [![npm version](https://img.shields.io/npm/v/eyeling.svg)](https://www.npmjs.com/package/eyeling)
4
4
  [![DOI](https://img.shields.io/badge/DOI-10.5281%2Fzenodo.19068086-blue.svg)](https://doi.org/10.5281/zenodo.19068086)
5
5
 
6
- ![Eyeling](eyeling.png)
7
-
8
6
  A compact [Notation3 (N3)](https://notation3.org/) reasoner in **JavaScript**.
9
7
 
8
+ Eyeling is characterized by:
9
+
10
+ - **Notation3 reasoning in a small JavaScript package** — facts, quoted formulas, and N3 rules are parsed and reasoned over directly.
11
+ - **Forward and backward chaining** — `=>` rules derive new facts, while `<=` rules act as goal-directed definitions.
12
+ - **Backward proving inside forward rules** — forward-rule bodies are solved with the backward engine, so rules can use derived predicates and built-ins without materializing everything first.
13
+ - **Built-ins in rule bodies** — N3 programs can combine logical rules with computations such as math, string, list, time, and web-oriented predicates.
14
+ - **Streaming RDF Messages** — supports RDF Messages streams, enabling Eyeling to fit into streaming RDF pipelines.
15
+ - **Node.js, npm, and browser use** — run it from the command line, call it from JavaScript, or use the browser-oriented bundle.
16
+ - **RDF-JS interoperability** — use N3 text, RDF-JS quads, datasets, or Eyeling’s own AST-level API.
17
+
18
+
19
+ This README is the primary guide to using, extending, and maintaining Eyeling.
20
+
21
+ | Project fact | Value |
22
+ |---|---|
23
+ | Package | `eyeling` |
24
+ | Runtime | Node.js `>=18` |
25
+ | License | MIT |
26
+ | Main entry point | `index.js` |
27
+ | CLI binary | `eyeling` |
28
+ | Browser entry point | `eyeling/browser` |
29
+
30
+ Eyeling is designed for people who want a small, inspectable reasoner that can run N3 rules in Node.js, the browser, tests, and RDF-oriented data pipelines.
31
+
32
+ ## Project links
33
+
34
+ - [Playground](https://eyereasoner.github.io/eyeling/playground)
35
+ - [Conformance report](https://codeberg.org/phochste/notation3tests/src/branch/main/reports/report.md)
36
+
37
+ ---
38
+
39
+ ## Table of contents
40
+
41
+ 1. [What Eyeling is](#what-eyeling-is)
42
+ 2. [Quick start](#quick-start)
43
+ 3. [Core concepts](#core-concepts)
44
+ 4. [Command-line interface](#command-line-interface)
45
+ 5. [JavaScript API](#javascript-api)
46
+ 6. [RDF-JS integration](#rdf-js-integration)
47
+ 7. [RDF compatibility mode and RDF 1.2](#rdf-compatibility-mode-and-rdf-12)
48
+ 8. [RDF Message Logs](#rdf-message-logs)
49
+ 9. [Built-ins](#built-ins)
50
+ 10. [Custom built-ins](#custom-built-ins)
51
+ 11. [Reasoning model](#reasoning-model)
52
+ 12. [Architecture](#architecture)
53
+ 13. [Repository layout](#repository-layout)
54
+ 14. [Examples guide](#examples-guide)
55
+ 15. [Testing and quality checks](#testing-and-quality-checks)
56
+ 16. [Development workflow](#development-workflow)
57
+ 17. [Publishing and release notes](#publishing-and-release-notes)
58
+ 18. [Troubleshooting](#troubleshooting)
59
+ 19. [Security and operational notes](#security-and-operational-notes)
60
+ 20. [Glossary](#glossary)
61
+
62
+ ---
63
+
64
+ ## What Eyeling is
65
+
66
+ Eyeling is a compact [Notation3](https://notation3.org/) reasoner implemented in JavaScript.
67
+
68
+ It accepts facts and rules written in N3-style syntax, computes the logical consequences of those rules, and emits newly derived results. It can be used as:
69
+
70
+ - a command-line tool through `npx eyeling` or the `eyeling` binary;
71
+ - a CommonJS API from Node.js through `require('eyeling')`;
72
+ - a browser/worker API through `eyeling/browser`;
73
+ - an RDF-JS adapter for applications that work with quads and data factories;
74
+ - a streaming tool for RDF Message Logs.
75
+
76
+ Eyeling is intentionally small and dependency-light. The source tree is organized as a miniature compiler and inference engine: lexer, parser, term model, rule normalization, built-ins, forward chaining, backward proving, printing, RDF-JS adapters, and CLI wiring.
77
+
78
+ ### What Eyeling is not
79
+
80
+ Eyeling is not a database, a triple store, or a full web crawler. It is a reasoner. It reads a finite set of sources, reasons over them, and returns derived output. For persistent storage, indexing at scale, access control, or distributed querying, pair Eyeling with the appropriate storage and application layer.
81
+
82
+ ---
83
+
10
84
  ## Quick start
11
85
 
86
+ ### Run without installing
87
+
12
88
  ```bash
13
89
  echo '@prefix : <http://example.org/> .
14
90
  :Socrates a :Man .
15
91
  { ?x a :Man } => { ?x a :Mortal } .' | npx eyeling
16
92
  ```
17
93
 
18
- ## Read more
94
+ Expected output:
19
95
 
20
- - [Handbook](https://eyereasoner.github.io/eyeling/HANDBOOK)
21
- - [Playground](https://eyereasoner.github.io/eyeling/playground)
22
- - [Conformance report](https://codeberg.org/phochste/notation3tests/src/branch/main/reports/report.md)
96
+ ```n3
97
+ @prefix : <http://example.org/> .
98
+
99
+ :Socrates a :Mortal .
100
+ ```
101
+
102
+ By default, the CLI prints newly derived triples, not the original input facts.
103
+
104
+ ### Install in a project
105
+
106
+ ```bash
107
+ npm install eyeling
108
+ ```
109
+
110
+ Use it from JavaScript:
111
+
112
+ ```js
113
+ const { reason } = require('eyeling');
114
+
115
+ const output = reason({}, `
116
+ @prefix : <http://example.org/> .
117
+
118
+ :Socrates a :Man .
119
+ { ?x a :Man } => { ?x a :Mortal } .
120
+ `);
121
+
122
+ console.log(output);
123
+ ```
124
+
125
+ ### Run an included example
126
+
127
+ ```bash
128
+ node eyeling.js examples/socrates.n3
129
+ ```
130
+
131
+ For proof output:
132
+
133
+ ```bash
134
+ node eyeling.js --proof examples/socrates.n3
135
+ ```
136
+
137
+ ---
138
+
139
+ ## Core concepts
140
+
141
+ ### Facts
142
+
143
+ A fact is an RDF-like triple:
144
+
145
+ ```n3
146
+ :Socrates a :Human .
147
+ :Human rdfs:subClassOf :Mortal .
148
+ ```
149
+
150
+ Each triple has a subject, predicate, and object. Eyeling supports IRIs, prefixed names, literals, blank nodes, variables, lists, and quoted formulas in the supported N3 subset.
151
+
152
+ ### Forward rules
153
+
154
+ A forward rule uses `=>`:
155
+
156
+ ```n3
157
+ { ?s a ?class . ?class rdfs:subClassOf ?super . }
158
+ =>
159
+ { ?s a ?super . } .
160
+ ```
161
+
162
+ Read it as: if the body is provable, derive the head.
163
+
164
+ ### Backward rules
165
+
166
+ A backward rule uses `<=`:
167
+
168
+ ```n3
169
+ { ?x :moreInterestingThan ?y . }
170
+ <=
171
+ { ?x math:greaterThan ?y . } .
172
+ ```
173
+
174
+ Read it as: to prove the head, prove the body.
175
+
176
+ Backward rules are especially useful for derived predicates, reusable definitions, and built-in-backed computations that should not be materialized until needed.
177
+
178
+ ### Built-ins
179
+
180
+ Built-ins are predicates implemented by the engine. Examples include:
181
+
182
+ ```n3
183
+ (2 3 5) math:sum ?total .
184
+ "Hello Eyeling" string:contains "Eye" .
185
+ (1 2 3) list:length ?n .
186
+ ```
187
+
188
+ Built-ins are used in rule bodies to test conditions, bind variables, inspect formulas, format strings, work with lists, perform numeric operations, or dereference content.
189
+
190
+ ### Query output
191
+
192
+ Eyeling supports `log:query` as an output-selection mechanism. A program can derive a full closure internally and emit only the results selected by query-style rules.
193
+
194
+ For human-readable text output, use `log:outputString`:
195
+
196
+ ```n3
197
+ @prefix : <http://example.org/> .
198
+ @prefix log: <http://www.w3.org/2000/10/swap/log#> .
199
+
200
+ :run :value "hello" .
201
+
202
+ { :run :value ?text }
203
+ =>
204
+ { :run log:outputString ?text } .
205
+ ```
206
+
207
+ The CLI renders the `log:outputString` values directly:
208
+
209
+ ```text
210
+ hello
211
+ ```
212
+
213
+ ---
214
+
215
+ ## Command-line interface
216
+
217
+ The CLI is exposed as `eyeling` and backed by `bin/eyeling.cjs`, which loads the bundled `eyeling.js` runtime.
218
+
219
+ ```bash
220
+ eyeling [options] [file-or-url.n3|- ...]
221
+ ```
222
+
223
+ When no file is given and stdin is piped, Eyeling reads from stdin. When multiple inputs are given, Eyeling parses each source separately, merges the ASTs, and reasons once over the merged document.
224
+
225
+ ### Common commands
226
+
227
+ Run a local file:
228
+
229
+ ```bash
230
+ eyeling examples/socrates.n3
231
+ ```
232
+
233
+ Pipe a program from stdin:
234
+
235
+ ```bash
236
+ cat examples/socrates.n3 | eyeling
237
+ ```
238
+
239
+ Use explicit stdin:
240
+
241
+ ```bash
242
+ eyeling - < examples/socrates.n3
243
+ ```
244
+
245
+ Run facts and rules from separate files:
246
+
247
+ ```bash
248
+ eyeling facts.n3 rules.n3
249
+ ```
250
+
251
+ Print proof explanations:
252
+
253
+ ```bash
254
+ eyeling --proof examples/socrates.n3
255
+ ```
256
+
257
+ Print the parsed AST:
258
+
259
+ ```bash
260
+ eyeling --ast examples/socrates.n3
261
+ ```
262
+
263
+ Enable RDF/TriG compatibility mode:
264
+
265
+ ```bash
266
+ eyeling --rdf data.trig rules.n3
267
+ ```
268
+
269
+ Process an RDF Message Log one message at a time:
270
+
271
+ ```bash
272
+ eyeling --rdf --stream-messages rules.n3 messages.trig
273
+ ```
274
+
275
+ ### CLI options
276
+
277
+ | Option | Meaning |
278
+ |---|---|
279
+ | `-a`, `--ast` | Print the parsed AST as JSON and exit. |
280
+ | `--builtin <module.js>` | Load a custom built-in module. Repeatable. |
281
+ | `-d`, `--deterministic-skolem` | Make `log:skolem` stable across reasoning runs. |
282
+ | `-e`, `--enforce-https` | Rewrite `http://` IRIs to `https://` for log dereferencing built-ins. |
283
+ | `-h`, `--help` | Show help and exit. |
284
+ | `-p`, `--proof` | Enable proof explanations. |
285
+ | `-r`, `--rdf` | Enable RDF/TriG input and output compatibility. |
286
+ | `--stream-messages` | Process RDF Message Logs one message at a time under `--rdf`. |
287
+ | `-s`, `--super-restricted` | Disable all built-ins except implication handling. |
288
+ | `-t`, `--stream` | Stream derived triples as soon as they are derived. |
289
+ | `-v`, `--version` | Print the package version and exit. |
290
+
291
+ ### Output behavior
292
+
293
+ The CLI has three important output modes:
294
+
295
+ 1. **Default mode**: derive everything first, then print newly derived triples.
296
+ 2. **Streaming mode**: with `--stream`, print derived triples as they are found.
297
+ 3. **Query mode**: when `log:query` rules are present, derive the full closure, then print only query-selected triples.
298
+
299
+ When `log:outputString` appears in the output set, Eyeling writes the string values directly to stdout. This is useful for examples that generate Markdown, reports, or concise verdicts.
300
+
301
+ ### Exit codes
302
+
303
+ A rule that derives `false` triggers Eyeling's inference fuse and exits with code `65`. JavaScript API calls expose the same code on thrown errors where applicable.
304
+
305
+ ---
306
+
307
+ ## JavaScript API
308
+
309
+ Import from the package root for Node.js:
310
+
311
+ ```js
312
+ const {
313
+ reason,
314
+ reasonStream,
315
+ reasonRdfJs,
316
+ rdfjs,
317
+ registerBuiltin,
318
+ unregisterBuiltin,
319
+ registerBuiltinModule,
320
+ loadBuiltinModule,
321
+ listBuiltinIris,
322
+ INFERENCE_FUSE_EXIT_CODE,
323
+ } = require('eyeling');
324
+ ```
325
+
326
+ ### `reason(options, input)`
327
+
328
+ `reason()` is the simplest API. It runs the bundled reasoner in a child process and returns stdout as a string.
329
+
330
+ ```js
331
+ const { reason } = require('eyeling');
332
+
333
+ const out = reason({ proof: false }, `
334
+ @prefix : <http://example.org/> .
335
+ :a :p :b .
336
+ { ?s :p ?o } => { ?s :q ?o } .
337
+ `);
338
+
339
+ console.log(out);
340
+ ```
341
+
342
+ Useful options:
343
+
344
+ | Option | Description |
345
+ |---|---|
346
+ | `proof` | Include proof explanations when true. Defaults to false for API output. |
347
+ | `rdf` | Enable RDF/TriG compatibility mode. |
348
+ | `args` | Extra CLI-style arguments. |
349
+ | `maxBuffer` | Child-process output buffer limit. |
350
+ | `builtinModules` | Custom built-in module path or paths. |
351
+
352
+ `reason()` accepts N3 text, supported RDF-JS input objects, AST bundles, and multi-source inputs.
353
+
354
+ ### Multi-source input
355
+
356
+ Use `sources` when facts and rules should be parsed as separate documents and then merged:
357
+
358
+ ```js
359
+ const { reason } = require('eyeling');
360
+
361
+ const output = reason({}, {
362
+ sources: [
363
+ '@prefix : <http://example.org/> .\n:Socrates a :Man .\n',
364
+ '@prefix : <http://example.org/> .\n{ ?x a :Man } => { ?x a :Mortal } .\n',
365
+ ],
366
+ });
367
+ ```
368
+
369
+ Parsing sources separately prevents accidental blank-node label collisions across files.
370
+
371
+ ### `reasonStream(input, options)`
372
+
373
+ `reasonStream()` runs in process and returns a structured result:
374
+
375
+ ```js
376
+ const { reasonStream } = require('eyeling');
377
+
378
+ const result = reasonStream(`
379
+ @prefix : <http://example.org/> .
380
+ :a :p :b .
381
+ { ?s :p ?o } => { ?s :q ?o } .
382
+ `, {
383
+ includeInputFactsInClosure: false,
384
+ onDerived({ triple }) {
385
+ console.log('derived:', triple);
386
+ },
387
+ });
388
+
389
+ console.log(result.closureN3);
390
+ ```
391
+
392
+ Result shape:
393
+
394
+ | Field | Meaning |
395
+ |---|---|
396
+ | `prefixes` | Prefix environment used for parsing and printing. |
397
+ | `facts` | Saturated closure as internal triples. |
398
+ | `derived` | Derived facts with explanation metadata. |
399
+ | `queryMode` | True when `log:query` output selection was used. |
400
+ | `queryTriples` | Query-selected output triples. |
401
+ | `queryDerived` | Query-selected derived facts with metadata. |
402
+ | `closureN3` | Rendered closure or selected output as N3/TriG-compatible text. |
403
+ | `closureQuads` | RDF-JS quads when `rdfjs: true` is used. |
404
+ | `queryQuads` | RDF-JS query output quads when available. |
405
+
406
+ Useful options:
407
+
408
+ | Option | Description |
409
+ |---|---|
410
+ | `baseIri` | Base IRI for relative IRI resolution. |
411
+ | `proof` | Include proof explanations in `closureN3`. |
412
+ | `includeInputFactsInClosure` | Include original facts in `closureN3`. Defaults to true. |
413
+ | `onDerived` | Callback called for derived or query-selected output. |
414
+ | `enforceHttps` | Apply HTTPS rewriting for dereferencing built-ins. |
415
+ | `rdf` | Enable RDF/TriG compatibility mode. |
416
+ | `rdfjs` | Also emit RDF-JS quads where conversion is possible. |
417
+ | `dataFactory` | Custom RDF-JS DataFactory. |
418
+ | `skipUnsupportedRdfJs` | Skip N3-only terms when producing RDF-JS quads. |
419
+ | `builtinModules` | Register custom built-ins before reasoning. |
420
+
421
+ ### `reasonRdfJs(input, options)`
422
+
423
+ `reasonRdfJs()` returns an async iterable of derived RDF-JS quads:
424
+
425
+ ```js
426
+ const { reasonRdfJs } = require('eyeling');
427
+
428
+ for await (const quad of reasonRdfJs({
429
+ n3: `
430
+ @prefix : <http://example.org/> .
431
+ :a :p :b .
432
+ { ?s :p ?o } => { ?s :q ?o } .
433
+ `,
434
+ })) {
435
+ console.log(quad.subject.value, quad.predicate.value, quad.object.value);
436
+ }
437
+ ```
438
+
439
+ Use `skipUnsupportedRdfJs: true` when your rules may derive N3-only terms such as quoted formulas that cannot be represented as ordinary RDF-JS quads.
440
+
441
+ ### Browser API
442
+
443
+ Use the browser entry point in browser or worker runtimes:
444
+
445
+ ```js
446
+ import eyeling, { reasonStream } from 'eyeling/browser';
447
+
448
+ const result = reasonStream(`
449
+ @prefix : <http://example.org/> .
450
+ :a :p :b .
451
+ { ?s :p ?o } => { ?s :q ?o } .
452
+ `);
453
+
454
+ console.log(result.closureN3);
455
+ console.log(eyeling.version);
456
+ ```
457
+
458
+ The browser entry loads `dist/browser/eyeling.browser.js` and exposes the API through `globalThis.eyeling`.
459
+
460
+ ---
461
+
462
+ ## RDF-JS integration
463
+
464
+ Eyeling includes a lightweight RDF-JS DataFactory and adapters for supported RDF-JS terms and quads.
465
+
466
+ ```js
467
+ const { reasonStream, rdfjs } = require('eyeling');
468
+
469
+ const ex = 'http://example.org/';
470
+
471
+ const input = {
472
+ quads: [
473
+ rdfjs.quad(
474
+ rdfjs.namedNode(`${ex}Socrates`),
475
+ rdfjs.namedNode(`${ex}type`),
476
+ rdfjs.namedNode(`${ex}Man`),
477
+ ),
478
+ ],
479
+ n3: `
480
+ @prefix : <http://example.org/> .
481
+ { ?x :type :Man } => { ?x :type :Mortal } .
482
+ `,
483
+ };
484
+
485
+ const result = reasonStream(input, { rdfjs: true });
486
+ console.log(result.closureQuads);
487
+ ```
488
+
489
+ Supported RDF-JS input terms include named nodes, blank nodes, literals, variables, default graph terms, and default-graph quads. Named-graph input quads are rejected clearly unless handled through N3/TriG compatibility mode.
490
+
491
+ Use RDF-JS when you want Eyeling to sit inside a JavaScript RDF pipeline. Use raw N3 input when you need N3-only features such as quoted formulas or N3 rules represented directly in source text.
492
+
493
+ ---
494
+
495
+ ## RDF compatibility mode and RDF 1.2
496
+
497
+ RDF compatibility mode is enabled with `--rdf` on the CLI or `{ rdf: true }` in the API.
498
+
499
+ Use it when working with RDF/TriG-oriented syntax and RDF 1.2 constructs:
500
+
501
+ ```bash
502
+ eyeling --rdf input.trig rules.n3
503
+ ```
504
+
505
+ ```js
506
+ const result = reasonStream(input, { rdf: true });
507
+ ```
508
+
509
+ In RDF mode, Eyeling accepts and serializes RDF-compatible forms such as:
510
+
511
+ - uppercase `PREFIX` and `BASE` directives;
512
+ - TriG-style datasets;
513
+ - RDF 1.2 triple terms where supported;
514
+ - RDF 1.2 annotation syntax after objects;
515
+ - RDF Message Log replay syntax under the message-log mode described below.
516
+
517
+ RDF 1.2 triple terms require explicit RDF compatibility mode. This protects ordinary N3 users from accidentally mixing parser modes.
518
+
519
+ ---
520
+
521
+ ## RDF Message Logs
522
+
523
+ Eyeling supports RDF Message Logs, including parser-level message delimiters, under RDF compatibility mode.
524
+
525
+ A message log starts with a message version and separates messages with `MESSAGE`:
526
+
527
+ ```trig
528
+ VERSION "1.2-messages"
529
+ PREFIX : <https://example.org/messages#>
530
+
531
+ :obs1 :value 21 .
532
+
533
+ MESSAGE
534
+
535
+ # Empty heartbeat message.
536
+
537
+ MESSAGE
538
+
539
+ :obs2 :value 22 .
540
+ ```
541
+
542
+ Run the message log with rules:
543
+
544
+ ```bash
545
+ eyeling --rdf rules.n3 messages.trig
546
+ ```
547
+
548
+ For one-message-at-a-time processing:
549
+
550
+ ```bash
551
+ eyeling --rdf --stream-messages rules.n3 messages.trig
552
+ ```
553
+
554
+ Eyeling materializes a replay view under the `eymsg:` vocabulary:
555
+
556
+ ```n3
557
+ @prefix eymsg: <https://eyereasoner.github.io/eyeling/vocab/message#> .
558
+ ```
559
+
560
+ The replay view includes stream resources, ordered envelopes, offsets, payload kind, and payload graphs. Rules can inspect each payload graph with formula-aware built-ins such as `log:includes`, preserving message boundaries instead of treating all messages as one merged graph.
561
+
562
+ Important semantics:
563
+
564
+ - Message boundaries are explicit.
565
+ - Empty heartbeat messages are valid.
566
+ - Payloads are contextualized by message envelope.
567
+ - Blank-node labels are scoped per message.
568
+ - Remote text/plain RDF Message Logs can be streamed over HTTP by the CLI.
569
+
570
+ See the included examples:
571
+
572
+ ```bash
573
+ eyeling -r examples/rdf-messages.n3 examples/input/rdf-messages.trig
574
+ eyeling -r examples/rdf-message-flow.n3 examples/input/rdf-message-flow.trig
575
+ eyeling -r --stream-messages examples/rdf-message-flow.n3 examples/input/rdf-message-flow.trig
576
+ ```
577
+
578
+ ---
579
+
580
+ ## Built-ins
581
+
582
+ Eyeling implements SWAP-style built-ins across these namespaces:
583
+
584
+ | Namespace | Examples | Purpose |
585
+ |---|---|---|
586
+ | `crypto:` | `sha`, `md5`, `sha256`, `sha512` | Hashing. |
587
+ | `math:` | `sum`, `product`, `difference`, `greaterThan`, `sin`, `cos` | Numeric computation and comparison. |
588
+ | `time:` | `year`, `month`, `day`, `localTime` | `xsd:dateTime` helpers. |
589
+ | `list:` | `first`, `rest`, `member`, `length`, `map`, `sort` | N3 and RDF list operations. |
590
+ | `rdf:` | `first`, `rest` | Aliases for list traversal over RDF collections. |
591
+ | `log:` | `includes`, `notIncludes`, `semantics`, `conclusion`, `query`, `outputString` | Formula, dereferencing, query, and output operations. |
592
+ | `string:` | `contains`, `matches`, `replace`, `format`, `length` | String tests and transformations. |
593
+
594
+ The authoritative built-in catalog is `eyeling-builtins.ttl`. It documents each built-in as RDF, including its kind:
595
+
596
+ - `ex:Test`: succeeds or fails without necessarily binding variables;
597
+ - `ex:Function`: computes an output and may bind variables;
598
+ - `ex:Relation`: unification-based relation;
599
+ - `ex:Generator`: may yield multiple solutions;
600
+ - `ex:IO`: may dereference or parse external content;
601
+ - `ex:Meta`: operates on formulas or types;
602
+ - `ex:SideEffect`: produces output.
603
+
604
+ ### Numeric built-ins
605
+
606
+ Numeric built-ins support common XSD numeric literals. Integer-oriented operations use `BigInt` where possible, with safety limits to avoid accidental memory exhaustion. Date/time comparisons and timestamp arithmetic are supported for relevant operations.
607
+
608
+ Example:
609
+
610
+ ```n3
611
+ @prefix : <http://example.org/> .
612
+ @prefix math: <http://www.w3.org/2000/10/swap/math#> .
613
+
614
+ {
615
+ (2 3 5) math:sum ?total .
616
+ }
617
+ =>
618
+ {
619
+ :calculation :total ?total .
620
+ } .
621
+ ```
622
+
623
+ ### List built-ins
624
+
625
+ Eyeling supports both native N3 list terms and materialized RDF collections. Anonymous `rdf:first`/`rdf:rest` collections can be materialized into list terms, while named list nodes keep their identity.
626
+
627
+ Example:
628
+
629
+ ```n3
630
+ @prefix : <http://example.org/> .
631
+ @prefix list: <http://www.w3.org/2000/10/swap/list#> .
632
+
633
+ {
634
+ ("red" "green" "blue") list:length ?n .
635
+ }
636
+ =>
637
+ {
638
+ :palette :size ?n .
639
+ } .
640
+ ```
641
+
642
+ ### Formula and log built-ins
643
+
644
+ Formula-aware built-ins make Eyeling useful for meta-reasoning:
645
+
646
+ ```n3
647
+ @prefix : <http://example.org/> .
648
+ @prefix log: <http://www.w3.org/2000/10/swap/log#> .
649
+
650
+ :doc :graph { :alice :knows :bob } .
651
+
652
+ {
653
+ :doc :graph ?g .
654
+ ?g log:includes { :alice :knows ?person } .
655
+ }
656
+ =>
657
+ {
658
+ :doc :mentions ?person .
659
+ } .
660
+ ```
661
+
662
+ `log:semantics`, `log:content`, and related built-ins may dereference sources. Use `--enforce-https` or `{ enforceHttps: true }` in environments where HTTP-to-HTTPS rewriting is required.
663
+
664
+ ---
665
+
666
+ ## Custom built-ins
667
+
668
+ Custom built-ins let applications extend Eyeling without modifying the core engine.
669
+
670
+ ### CLI module
671
+
672
+ Create `hello-builtin.js`:
673
+
674
+ ```js
675
+ module.exports = ({ registerBuiltin, internLiteral, unifyTerm, terms }) => {
676
+ const { Var } = terms;
677
+
678
+ registerBuiltin('http://example.org/custom#hello', ({ goal, subst }) => {
679
+ const value = internLiteral('"world"');
680
+
681
+ if (goal.o instanceof Var) {
682
+ return [{ ...subst, [goal.o.name]: value }];
683
+ }
684
+
685
+ const next = unifyTerm(goal.o, value, subst);
686
+ return next === null ? [] : [next];
687
+ });
688
+ };
689
+ ```
690
+
691
+ Use it:
692
+
693
+ ```bash
694
+ eyeling --builtin ./hello-builtin.js program.n3
695
+ ```
696
+
697
+ Program:
698
+
699
+ ```n3
700
+ @prefix : <http://example.org/> .
701
+ @prefix cb: <http://example.org/custom#> .
702
+
703
+ { :x cb:hello ?value }
704
+ =>
705
+ { :x :value ?value } .
706
+ ```
707
+
708
+ Expected derived output:
709
+
710
+ ```n3
711
+ :x :value "world" .
712
+ ```
713
+
714
+ ### API registration
715
+
716
+ ```js
717
+ const { registerBuiltin, reason } = require('eyeling');
718
+
719
+ registerBuiltin('http://example.org/custom#always', ({ subst }) => [subst]);
720
+
721
+ const out = reason({}, `
722
+ @prefix : <http://example.org/> .
723
+ @prefix cb: <http://example.org/custom#> .
724
+
725
+ { :x cb:always true } => { :x :ok true } .
726
+ `);
727
+ ```
728
+
729
+ ### Module shapes
730
+
731
+ `registerBuiltinModule()` accepts these shapes:
732
+
733
+ ```js
734
+ // Function form
735
+ module.exports = (api) => {
736
+ api.registerBuiltin('http://example.org/custom#p', handler);
737
+ };
738
+ ```
739
+
740
+ ```js
741
+ // Object with register()
742
+ module.exports = {
743
+ register(api) {
744
+ api.registerBuiltin('http://example.org/custom#p', handler);
745
+ },
746
+ };
747
+ ```
748
+
749
+ ```js
750
+ // Builtin map
751
+ module.exports = {
752
+ 'http://example.org/custom#p': handler,
753
+ };
754
+ ```
755
+
756
+ ```js
757
+ // Builtin map under builtins/default
758
+ module.exports = {
759
+ builtins: {
760
+ 'http://example.org/custom#p': handler,
761
+ },
762
+ };
763
+ ```
764
+
765
+ Handlers must return an array of substitution deltas. Return an empty array for failure and `[subst]` for success without new bindings.
766
+
767
+ ---
768
+
769
+ ## Reasoning model
770
+
771
+ Eyeling combines forward saturation with backward proving.
772
+
773
+ At a high level:
774
+
775
+ ```text
776
+ parse sources
777
+
778
+ normalize terms, rules, and lists
779
+
780
+ initialize fact set
781
+
782
+ repeat until no new facts appear:
783
+ for each forward rule:
784
+ prove the rule body with the backward prover
785
+ for each solution:
786
+ instantiate and add the rule head
787
+ activate any newly derived rules
788
+ stop if false is derived
789
+
790
+ render derived output, query-selected output, proof output, or strings
791
+ ```
792
+
793
+ ### Forward chaining
794
+
795
+ Forward rules are the outer control loop. They gradually saturate the fact set by adding ground consequences.
796
+
797
+ ```n3
798
+ { ?x :parent ?y }
799
+ =>
800
+ { ?x :ancestor ?y } .
801
+
802
+ { ?x :parent ?y . ?y :ancestor ?z }
803
+ =>
804
+ { ?x :ancestor ?z } .
805
+ ```
806
+
807
+ ### Backward proving
808
+
809
+ The backward prover solves rule bodies. It can match current facts, use backward rules, and invoke built-ins. This lets forward rules depend on predicates that are computed on demand.
810
+
811
+ ```n3
812
+ { ?x :interestingComparedWith ?y }
813
+ <=
814
+ { ?x math:greaterThan ?y } .
815
+
816
+ { 5 :interestingComparedWith 3 }
817
+ =>
818
+ { :example :works true } .
819
+ ```
820
+
821
+ ### Dynamic rules
822
+
823
+ Eyeling treats top-level `log:implies` and `log:impliedBy` as rule forms and can activate derived implication facts as live rules during reasoning. This supports programs that derive rules as part of their logic.
824
+
825
+ ### Duplicate control and fixpoints
826
+
827
+ Derived facts are indexed and deduplicated. Saturation stops when no rule can add a new fact. This avoids echoing already-known facts and keeps recursive programs such as transitive closure finite when the closure is finite.
828
+
829
+ ### Negative entailment and the inference fuse
830
+
831
+ If a rule derives `false`, Eyeling treats that as a reasoning failure and exits with `INFERENCE_FUSE_EXIT_CODE`, which is `65`.
832
+
833
+ ```n3
834
+ { :policy :violated true } => false .
835
+ ```
836
+
837
+ Use this pattern for integrity constraints, policy failures, and tests that should fail when an unwanted condition is provable.
838
+
839
+ ---
840
+
841
+ ## Architecture
842
+
843
+ Eyeling is organized as a set of small modules under `lib/` plus packaging and browser glue.
844
+
845
+ ### Execution pipeline
846
+
847
+ ```text
848
+ input text / RDF-JS / AST
849
+
850
+
851
+ lib/lexer.js tokenization and RDF compatibility normalization
852
+
853
+
854
+ lib/parser.js N3/TriG-ish parser to internal AST
855
+
856
+
857
+ lib/multisource.js source-level parsing and AST merging
858
+
859
+
860
+ lib/prelude.js term model, triples, rules, prefixes, namespaces
861
+
862
+
863
+ lib/engine.js forward chain, backward prover, rule activation
864
+
865
+ ├── lib/builtins.js built-in predicates and custom registry
866
+ ├── lib/deref.js dereferencing helpers
867
+ ├── lib/skolem.js skolemization helpers
868
+ ├── lib/time.js date/time helpers
869
+ └── lib/trace.js tracing support
870
+
871
+
872
+ lib/printing.js / lib/explain.js
873
+
874
+
875
+ CLI output, API result, proof document, RDF-JS quads, or browser result
876
+ ```
877
+
878
+ ### Key modules
879
+
880
+ | Path | Responsibility |
881
+ |---|---|
882
+ | `index.js` | Public Node package API. Wraps CLI bundle for `reason()` and exports in-process APIs. |
883
+ | `bin/eyeling.cjs` | Executable CLI shim. |
884
+ | `lib/entry.js` | Bundle entry that exposes public APIs and selected playground internals. |
885
+ | `lib/cli.js` | CLI argument handling, source loading, syntax errors, stream message mode. |
886
+ | `lib/engine.js` | Core reasoning engine, proof collection, stream APIs, RDF-JS output hooks. |
887
+ | `lib/builtins.js` | Built-in predicates, custom built-in registry, helper API. |
888
+ | `lib/lexer.js` | Lexer and compatibility normalization. |
889
+ | `lib/parser.js` | Parser for supported N3/RDF syntax. |
890
+ | `lib/prelude.js` | Core term classes, namespaces, triples, rules, prefix environment. |
891
+ | `lib/multisource.js` | Parse several documents independently and merge their ASTs. |
892
+ | `lib/rdfjs.js` | RDF-JS DataFactory and conversion adapters. |
893
+ | `lib/printing.js` | N3/TriG-compatible rendering. |
894
+ | `lib/explain.js` | Proof and explanation rendering. |
895
+ | `lib/deref.js` | Dereferencing support for log built-ins. |
896
+ | `lib/skolem.js` | Deterministic skolem term construction. |
897
+ | `lib/time.js` | Date/time parsing and formatting helpers. |
898
+ | `tools/bundle.js` | Builds `eyeling.js` and the browser bundle. |
899
+
900
+ ### Public surfaces
901
+
902
+ Eyeling deliberately has a small public API:
903
+
904
+ - `reason()` for simple Node use;
905
+ - `reasonStream()` for structured in-process reasoning;
906
+ - `reasonRdfJs()` for async RDF-JS output;
907
+ - `rdfjs` for a built-in data factory;
908
+ - custom built-in registration functions;
909
+ - `INFERENCE_FUSE_EXIT_CODE` for callers that need to distinguish logical failure from ordinary runtime failure.
910
+
911
+ Everything else should be treated as internal unless explicitly documented.
912
+
913
+ ---
914
+
915
+ ## Repository layout
916
+
917
+ ```text
918
+ .
919
+ ├── README.md Project overview, user guide, and maintainer guide
920
+ ├── LICENSE.md MIT license
921
+ ├── package.json Package metadata, scripts, exports, engine range
922
+ ├── index.js Node API entry
923
+ ├── index.d.ts TypeScript declarations
924
+ ├── eyeling.js Bundled Node runtime and CLI target
925
+ ├── eyeling-builtins.ttl Built-in catalog in RDF
926
+ ├── bin/ CLI executable shim
927
+ ├── lib/ Source modules
928
+ ├── dist/browser/ Browser bundle and ESM wrapper
929
+ ├── examples/ N3 examples, RDF message inputs, and generated decks
930
+ ├── spec/ RDF 1.2 parser test adapter
931
+ ├── test/ API, built-in, example, package, playground, and stream tests
932
+ ├── tools/ Build tooling
933
+ ├── playground.html Browser playground
934
+ └── demo.html Simple browser demo
935
+ ```
936
+
937
+ The package publishes the source modules, tests, examples, bundled runtime, browser bundle, declarations, README, license, and built-in catalog.
938
+
939
+ ---
940
+
941
+ ## Examples guide
942
+
943
+ The repository contains more than two hundred N3 examples under `examples/`, plus RDF Message input files under `examples/input/` and presentation-oriented Markdown decks under `examples/deck/`.
944
+
945
+ ### Good first examples
946
+
947
+ | Example | What it demonstrates |
948
+ |---|---|
949
+ | `examples/socrates.n3` | Basic class inference. |
950
+ | `examples/backward.n3` | Backward rule proving with a math built-in. |
951
+ | `examples/age.n3` | Literal propagation. |
952
+ | `examples/family-cousins.n3` | Multi-hop relational inference. |
953
+ | `examples/dijkstra.n3` | Graph/path reasoning. |
954
+ | `examples/list-map.n3` | List processing. |
955
+ | `examples/string-builtins-tests.n3` | String built-ins. |
956
+ | `examples/math-builtins-tests.n3` | Numeric built-ins. |
957
+ | `examples/rdf-messages.n3` | RDF Message Log replay. |
958
+
959
+ ### Running all examples through tests
960
+
961
+ ```bash
962
+ npm run test:examples
963
+ ```
964
+
965
+ Proof-only example checks:
966
+
967
+ ```bash
968
+ npm run test:examples:proof
969
+ ```
970
+
971
+ ### Output-generating examples
972
+
973
+ Many advanced examples use `log:outputString` to emit Markdown reports. This keeps the logical derivation and presentation in one N3 program. Run them from the CLI and redirect stdout when needed:
974
+
975
+ ```bash
976
+ eyeling examples/rdf-message-flow.n3 examples/input/rdf-message-flow.trig > report.md
977
+ ```
978
+
979
+ ---
980
+
981
+ ## Testing and quality checks
982
+
983
+ Package scripts are defined in `package.json`.
984
+
985
+ ### Core scripts
986
+
987
+ | Script | Purpose |
988
+ |---|---|
989
+ | `npm run build` | Rebuild `eyeling.js` and browser artifacts. |
990
+ | `npm run test:packlist` | Verify the package file list. |
991
+ | `npm run test:api` | Run API and stream-message API tests. |
992
+ | `npm run test:builtins` | Validate custom built-in contracts. |
993
+ | `npm run test:examples` | Run example corpus tests. |
994
+ | `npm run test:examples:proof` | Run proof-output checks for examples. |
995
+ | `npm run test:manifest` | Validate example/test manifest expectations. |
996
+ | `npm run test:playground` | Check playground serving headers. |
997
+ | `npm run test:package` | Verify package-level behavior. |
998
+ | `npm run rdf12` | Run RDF 1.2 Turtle, N-Triples, N-Quads, and TriG syntax suites. |
999
+ | `npm test` | Build and run the full suite. |
1000
+
1001
+ ### Recommended local check before committing
1002
+
1003
+ Use the full test suite as the authoritative project check:
1004
+
1005
+ ```bash
1006
+ npm test
1007
+ ```
1008
+
1009
+ For quick API-level feedback during development:
1010
+
1011
+ ```bash
1012
+ npm run build
1013
+ npm run test:api
1014
+ npm run test:builtins
1015
+ ```
1016
+
1017
+ ### What the tests cover
1018
+
1019
+ The tests exercise:
1020
+
1021
+ - parsing edge cases and syntax errors;
1022
+ - forward and backward chaining;
1023
+ - recursion and transitive closure;
1024
+ - duplicate suppression;
1025
+ - negative entailment and fuse behavior;
1026
+ - proof output;
1027
+ - lists and RDF collection materialization;
1028
+ - `log:outputString` rendering;
1029
+ - AST output;
1030
+ - multi-source parsing;
1031
+ - RDF-JS input and output;
1032
+ - custom built-ins;
1033
+ - RDF 1.2 compatibility mode;
1034
+ - RDF Message Log parsing and streaming;
1035
+ - package exports and browser playground behavior.
1036
+
1037
+ ---
1038
+
1039
+ ## Development workflow
1040
+
1041
+ ### Prerequisites
1042
+
1043
+ - Node.js 18 or newer.
1044
+ - npm.
1045
+
1046
+ ### Install dependencies
1047
+
1048
+ ```bash
1049
+ npm install
1050
+ ```
1051
+
1052
+ ### Build bundles
1053
+
1054
+ ```bash
1055
+ npm run build
1056
+ ```
1057
+
1058
+ This regenerates:
1059
+
1060
+ - `eyeling.js`
1061
+ - `dist/browser/eyeling.browser.js`
1062
+ - `dist/browser/index.mjs`
1063
+
1064
+ ### Edit source
1065
+
1066
+ Most logic lives in `lib/`. Prefer small, focused changes:
1067
+
1068
+ 1. Update or add tests first when fixing behavior.
1069
+ 2. Modify the relevant source module.
1070
+ 3. Rebuild bundles.
1071
+ 4. Run the targeted test script.
1072
+ 5. Run `npm test` before committing or publishing.
1073
+
1074
+ ### Add a built-in
1075
+
1076
+ 1. Implement behavior in `lib/builtins.js` or as an external custom built-in.
1077
+ 2. Add contract tests in `test/builtins.test.js` or behavior tests in `test/api.test.js`.
1078
+ 3. Document the built-in in `eyeling-builtins.ttl`.
1079
+ 4. Add at least one runnable example if the built-in is user-facing.
1080
+
1081
+ ### Add a parser feature
1082
+
1083
+ 1. Add focused parser tests for accepted and rejected syntax.
1084
+ 2. Update `lib/lexer.js` and/or `lib/parser.js`.
1085
+ 3. Ensure output rendering in `lib/printing.js` remains valid.
1086
+ 4. Add RDF compatibility tests if the feature is RDF/TriG-specific.
1087
+
1088
+ ### Add an example
1089
+
1090
+ A good example should include:
1091
+
1092
+ - clear prefixes;
1093
+ - a short comment block explaining the scenario;
1094
+ - facts separated from rules when practical;
1095
+ - deterministic output;
1096
+ - `log:outputString` only when human-readable report output is intended;
1097
+ - a test expectation when the example is part of the checked corpus.
1098
+
1099
+ ---
1100
+
1101
+ ## Publishing and release notes
1102
+
1103
+ The package metadata publishes Eyeling to npm with:
1104
+
1105
+ - CommonJS root export;
1106
+ - browser export;
1107
+ - TypeScript declarations;
1108
+ - CLI binary;
1109
+ - examples, tests, bundles, and built-in catalog.
1110
+
1111
+ The repository includes GitHub workflows for pages, npm publishing, RDF 1.2 compliance, and releases.
1112
+
1113
+ Before versioning or publishing:
1114
+
1115
+ ```bash
1116
+ npm test
1117
+ npm version patch # or minor / major
1118
+ ```
1119
+
1120
+ The `preversion` script runs the full test suite. The `postversion` script pushes the branch and tags.
1121
+
1122
+ ---
1123
+
1124
+ ## Troubleshooting
1125
+
1126
+ ### The CLI prints help instead of running
1127
+
1128
+ Eyeling prints help when no positional input is provided and stdin is interactive. Provide a file, URL, `-`, or pipe data into stdin.
1129
+
1130
+ ```bash
1131
+ eyeling examples/socrates.n3
1132
+ cat examples/socrates.n3 | eyeling
1133
+ eyeling - < examples/socrates.n3
1134
+ ```
1135
+
1136
+ ### RDF 1.2 syntax fails to parse
1137
+
1138
+ Enable RDF compatibility mode:
1139
+
1140
+ ```bash
1141
+ eyeling --rdf input.trig
1142
+ ```
1143
+
1144
+ or:
1145
+
1146
+ ```js
1147
+ reasonStream(input, { rdf: true });
1148
+ ```
1149
+
1150
+ ### `--stream-messages` fails immediately
1151
+
1152
+ `--stream-messages` requires RDF mode and cannot be combined with `--ast`, `--stream`, or proof output.
1153
+
1154
+ Use:
1155
+
1156
+ ```bash
1157
+ eyeling --rdf --stream-messages rules.n3 messages.trig
1158
+ ```
1159
+
1160
+ ### A rule did not fire
1161
+
1162
+ Check the following:
1163
+
1164
+ - Are prefixes identical between facts and rules?
1165
+ - Did the rule body require a fact that is only available after another rule fires?
1166
+ - Is a built-in being used in the correct direction?
1167
+ - Does the rule depend on RDF mode syntax without `--rdf`?
1168
+ - Are blank nodes scoped as intended across multiple source files?
1169
+ - Is the desired output an input fact rather than a newly derived fact?
1170
+
1171
+ For debugging, try `--proof` or create a smaller reproduction with only the relevant facts and rule.
1172
+
1173
+ ### Output contains no input facts
1174
+
1175
+ Default CLI output prints newly derived facts. Use `reasonStream()` with `includeInputFactsInClosure: true` when you need the complete closure including input facts.
1176
+
1177
+ ### RDF-JS conversion fails
1178
+
1179
+ Some N3 terms cannot be represented as ordinary RDF-JS quads. Use:
1180
+
1181
+ ```js
1182
+ reasonStream(input, { rdfjs: true, skipUnsupportedRdfJs: true });
1183
+ ```
1184
+
1185
+ or keep the N3 rendering in `closureN3`.
1186
+
1187
+ ### A program exits with code 65
1188
+
1189
+ A rule derived `false`. This is usually an integrity constraint or policy failure, not a parser error.
1190
+
1191
+ ### Remote dereferencing behaves unexpectedly
1192
+
1193
+ Use `--enforce-https` or `{ enforceHttps: true }` when policy requires HTTPS. Also ensure the runtime has network access and that the remote source returns a supported RDF/N3-compatible content type.
1194
+
1195
+ ---
1196
+
1197
+ ## Security and operational notes
1198
+
1199
+ ### Custom built-ins execute JavaScript
1200
+
1201
+ Custom built-ins are code. Only load built-in modules you trust. In server environments, do not allow arbitrary users to provide `--builtin` paths or dynamically registered handlers.
1202
+
1203
+ ### Dereferencing can access remote content
1204
+
1205
+ `log:semantics`, `log:content`, and related built-ins may dereference IRIs. Treat this like network I/O:
1206
+
1207
+ - use HTTPS where possible;
1208
+ - avoid dereferencing untrusted URLs in privileged environments;
1209
+ - apply external network restrictions when running untrusted programs;
1210
+ - consider `--super-restricted` for highly constrained execution.
1211
+
1212
+ ### Reasoning can be computationally expensive
1213
+
1214
+ Recursive rules, generators, large joins, and high-cardinality facts can produce large closures. Eyeling includes duplicate suppression and safety caps for some operations, but application-level limits are still important for untrusted workloads.
1215
+
1216
+ ### Proof output may reveal source details
1217
+
1218
+ Proof output can include source file labels and line references. Avoid exposing proof documents directly when source paths or input details are sensitive.
1219
+
1220
+ ---
1221
+
1222
+ ## Glossary
1223
+
1224
+ | Term | Meaning |
1225
+ |---|---|
1226
+ | AST | Abstract syntax tree produced by parsing N3/RDF input. |
1227
+ | Backward chaining | Goal-directed proving: to prove a goal, prove supporting facts/rules/built-ins. |
1228
+ | Built-in | Predicate implemented by JavaScript code rather than by input facts alone. |
1229
+ | Closure | The set of facts available after reasoning reaches a fixpoint. |
1230
+ | Derived fact | A fact added by a rule, not directly present as an input fact. |
1231
+ | Fact | A triple asserted in the input or derived during reasoning. |
1232
+ | Forward chaining | Saturation strategy that repeatedly applies rules to derive new facts. |
1233
+ | Formula | A quoted graph-like N3 term that can be inspected by formula built-ins. |
1234
+ | IRI | Internationalized Resource Identifier used to identify resources and predicates. |
1235
+ | N3 | Notation3, an RDF-compatible notation with rules and formulas. |
1236
+ | Prefix environment | Mapping from short prefixes such as `:` or `math:` to full IRI bases. |
1237
+ | RDF-JS | JavaScript interface conventions for RDF terms, quads, and data factories. |
1238
+ | RDF Message Log | Ordered record of RDF messages separated by message delimiters. |
1239
+ | Skolemization | Replacing existential blank nodes with generated identifiers. |
1240
+ | Substitution | Mapping from variables to terms during proof search. |
1241
+ | Triple | Subject-predicate-object statement. |