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.
package/README.md CHANGED
@@ -7,7 +7,7 @@ eyemind is a **JavaScript rule language** with forward and backward reasoning an
7
7
 
8
8
  [Playground](https://eyereasoner.github.io/eyemind/playground/) · [Specification](https://eyereasoner.github.io/eyemind/SPEC) · [Conformance](https://eyereasoner.github.io/eyemind/conformance/) · [Examples](https://eyereasoner.github.io/eyemind/examples/)
9
9
 
10
- The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 115 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1353 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
10
+ The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 118 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1353 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
11
11
 
12
12
  ## Contents
13
13
 
@@ -20,6 +20,7 @@ The playground runs programs in your browser; the specification defines the lang
20
20
  - [Inspecting rules](#inspecting-rules)
21
21
  - [RDF 1.2](#rdf-12)
22
22
  - [Notation3](#notation3)
23
+ - [RDF Messages](#rdf-messages)
23
24
  - [SPARQL 1.2 RL](#sparql-12-rl)
24
25
  - [How eyemind reasons](#how-eyemind-reasons)
25
26
  - [Proofs, and what checking one means](#proofs-and-what-checking-one-means)
@@ -142,7 +143,7 @@ for (let level = 1; level <= 10; level++) {
142
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).
143
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.
144
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']))`.
145
- - **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.
146
147
 
147
148
  ### Deriving rules
148
149
 
@@ -191,7 +192,7 @@ eyemind --to trig rules.js data.trig # the conclusions as TriG
191
192
  | Triple term | `triple(S, P, O)`, which may nest |
192
193
  | Default graph, named graph | `'default_graph'`, `iri(Name)` |
193
194
 
194
- 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.
195
196
 
196
197
  ### Notation3
197
198
 
@@ -236,6 +237,68 @@ Examples run directly from their N3 source in the playground and on the command
236
237
  Each deck shows the N3 result and what its saved proof establishes, including
237
238
  any remaining obligations.
238
239
 
240
+ ### RDF Messages
241
+
242
+ eyemind reads the [RDF Messages living draft](https://w3c-cg.github.io/rsp/spec/messages)
243
+ in Turtle, TriG, N-Triples and N-Quads. A version such as
244
+ `VERSION "1.2-messages"` enables `MESSAGE` boundaries; Turtle and TriG also
245
+ accept `@version "1.2-messages" .` and `@message .`. Empty messages are
246
+ preserved, a final delimiter adds no extra message, and blank nodes belong
247
+ to their message. Prefix and base changes apply to subsequent data.
248
+
249
+ Whole-log replay gives N3 or JavaScript rules an ordered view of the messages:
250
+
251
+ ```sh
252
+ eyemind examples/message-boundaries.n3 examples/data/message-boundaries.trig
253
+ eyemind --proof 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
+ ```
256
+
257
+ The replay vocabulary is `eymsg:`, with namespace
258
+ `https://eyereasoner.github.io/eyeling/vocab/message#`. A stream has
259
+ `messageCount`, `orderedEnvelopes`, `firstEnvelope`, `lastEnvelope` and
260
+ `envelope` links. Each envelope has a one-based `offset`, a `payloadKind`
261
+ of `empty` or `nonEmpty`, and, when nonempty, a `payloadGraph` link.
262
+ `nextEnvelope` preserves order. Stream and envelope IRIs are deterministic
263
+ from the input's scope; they are application replay identifiers, not syntax
264
+ from the draft.
265
+
266
+ `?payload log:nameOf ?data` exposes a quoted payload formula, inspected with
267
+ `?data log:includes { ... }`. A named graph inside a message is another
268
+ `log:nameOf` formula inside that payload. Message triples stay inside their
269
+ contexts; rules can deliberately join envelopes when replaying a whole log.
270
+ JavaScript rules see the replay facts as `rdf(S, P, O, 'default_graph')`
271
+ with `graph(...)` terms for payload formulas.
272
+
273
+ For independent processing, run the rules once per message:
274
+
275
+ ```sh
276
+ eyemind --stream-messages examples/message-alerts.n3 examples/data/message-alerts.nt
277
+ ```
278
+
279
+ The Node command incrementally reads files, standard input (`-`) or HTTP(S)
280
+ message logs and writes each result when its message closes. It reads static
281
+ inputs once and discards each run's derived facts before the next message.
282
+ Memory retains the current message, active prefix/base context and static
283
+ inputs. An inference fuse stops the stream with exit code 65. Output uses
284
+ the ordinary N3, RDF or term format selected for the run.
285
+
286
+ The playground's **Independent RDF Messages** mode processes its loaded
287
+ text with the same boundaries. Whole-log replay supports proofs;
288
+ `--stream-messages` rejects proof, proof-checking, compiled-program and
289
+ unused-clause modes. The [message-boundaries](https://eyereasoner.github.io/eyemind/examples/deck/message-boundaries),
290
+ [message-alerts](https://eyereasoner.github.io/eyemind/examples/deck/message-alerts)
291
+ and [message-provenance](https://eyereasoner.github.io/eyemind/examples/deck/message-provenance)
292
+ decks show the outputs and remaining proof obligations.
293
+
294
+ Library hosts can import `RdfMessageReader` and `parseRdfMessages` from
295
+ `eyemind`. The former accepts text chunks through `write(text)` and
296
+ `finish()`, calling `onMessage({ index, quads, prefixes, base })` for each
297
+ dataset; returning `false` stops it. The latter reads a complete string and
298
+ returns `messages` plus its replay representation. Both take `format`,
299
+ `base` and `scope` options. `parseRdf` reads ordinary RDF documents; use
300
+ `parseRdfMessages` to retain message boundaries.
301
+
239
302
  ### SPARQL 1.2 RL
240
303
 
241
304
  A file ending in `.srl` is a [SPARQL 1.2 RL](https://www.w3.org/TR/sparql12-rl/) rule set: eyemind parses and analyzes it, then compiles it into a program, with the SPARQL functions and aggregates it uses written as eyemind rules, and RDF data files given with it are its base graph. The result is the inference graph, as Turtle:
@@ -268,7 +331,32 @@ The two work together: a forward rule's premise can call a backward definition,
268
331
 
269
332
  ## Proofs, and what checking one means
270
333
 
271
- 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:
272
360
 
273
361
  | | Condition | What it establishes |
274
362
  | --- | --- | --- |
@@ -369,6 +457,7 @@ eyemind [OPTION ...] [FILE ...]
369
457
  | `--goal GOAL` | Ask `GOAL` after forward reasoning; may be repeated. |
370
458
  | `--strict-proof` | With a checking mode, reject proofs with any obligation. |
371
459
  | `--unused` | List the clauses that make no difference to the conclusions. |
460
+ | `--stream-messages` | Read an RDF Message Log and run the rules independently per message; Node reads files, stdin and HTTP(S) incrementally. |
372
461
  | `--stats` | Print reasoning statistics as JSON to standard error. |
373
462
  | `--max-depth N`, `--max-iterations N`, `--max-inferences N` | Bound backward depth (1000000), forward rounds per stratum (1000) and goals started (1000000); a compiled N3 or SRL program has 1000000, 100000 and 1000000000. |
374
463
  | `--to FORMAT` | Write the conclusions as `turtle`, `trig`, `n-triples`, `n-quads`, `n3` or `eyemind`; by default N3 for N3, Turtle for SRL, eyemind otherwise. |
@@ -410,6 +499,13 @@ console.log(checkProof(socrates, result.proof, { goals }).valid);
410
499
 
411
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.
412
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
+
413
509
  ## What is deliberately absent
414
510
 
415
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.
@@ -418,23 +514,47 @@ Cut, conditional commitment, mutable databases, attributed variables, constraint
418
514
 
419
515
  ```sh
420
516
  npm test # unit, examples, conformance, command line, playground
421
- npm test -- unit examples # only these sections
517
+ npm test -- unit examples # these sections, plus W3C EARL
422
518
  npm test -- -k skolem # only tests whose line contains "skolem"
423
519
  EYEMIND_PROPERTY_SCALE=20 npm test -- -k properties # deeper generated tests
424
520
  node tools/update-examples.js # regenerate example artifacts after an intended change
425
521
  node tools/report.js # the table npm test ends with, into REPORT.md
426
522
  node tools/notation3tests.js # the saved Notation3 suite, without network access
427
- node tools/sync-notation3tests.js # refresh its tests and document fixtures from upstream
523
+ npm run sync # refresh all three upstream test suites
428
524
  node conformance/run.js --command "my-eyemind" # run the conformance suite against another implementation
429
525
  ```
430
526
 
431
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.
432
528
 
433
- 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.
434
554
 
435
555
  ### Releases
436
556
 
437
- `./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**.
438
558
 
439
559
  ## The name
440
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.6
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,66 @@ 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
+
2204
+ eyemind also reads RDF Message Logs in these four RDF syntaxes, announced by
2205
+ a `*-messages` version. Replay supplies ordered envelopes and quoted payloads
2206
+ to N3 or JavaScript rules; `--stream-messages` evaluates each message
2207
+ independently and supports incremental Node input. Replay can produce and
2208
+ check ordinary eyemind proofs. The streaming mode rejects proof generation,
2209
+ proof checking, `--program` and `--unused`. These mappings and this option
2210
+ are also outside conformance; the README describes their supported behavior.
2211
+
2152
2212
  | Exit code | Meaning |
2153
2213
  | --- | --- |
2154
2214
  | 0 | Success, including a check that found the proof valid. |
package/bin/eyemind.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import { readFileSync, writeSync } from 'node:fs';
4
4
  import { main } from '../src/cli.js';
5
5
  import { nodeIO } from '../src/node.js';
6
+ import { streamMessages } from '../src/node-messages.js';
6
7
 
7
8
  function write(fd, text) {
8
9
  // Written synchronously, so a large proof is complete before the exit.
@@ -19,8 +20,9 @@ function write(fd, text) {
19
20
  }
20
21
  }
21
22
 
22
- const code = main(process.argv.slice(2), {
23
+ const code = await main(process.argv.slice(2), {
23
24
  ...nodeIO,
25
+ streamMessages,
24
26
  stdout: (text) => write(1, text),
25
27
  stderr: (text) => write(2, text),
26
28
  stdin: () => readFileSync(0, 'utf8'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.6",
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,7 @@
1
1
  // The eyemind command line.
2
2
  import { run, unusedClauses } from './engine.js';
3
- import { OUTPUT_FORMATS, defaultFormat, loadInputs, writeConclusions } from './formats.js';
3
+ import { OUTPUT_FORMATS, defaultFormat, loadInputs, rdfMessageFormat, scopeOf, writeConclusions, writeProof } from './formats.js';
4
+ import { isRdfMessageLog, replayMessages, RdfMessageReader } from './messages.js';
4
5
  import { checkProof, checkReport, publicReport } from './proof.js';
5
6
  import { EyemindError } from './terms.js';
6
7
  import { VERSION } from './version.js';
@@ -9,7 +10,7 @@ export const HELP = `Usage: eyemind [OPTION ...] [FILE ...]
9
10
  Programs are JavaScript; forward rules run to a fixpoint. Other files are read
10
11
  by their extension: .ttl, .trig, .nt and .nq as RDF 1.2 data, .n3 as Notation3
11
12
  and .srl as a SPARQL 1.2 RL rule set, both compiled to an eyemind program.
12
- -p, --proof Print the claims with clause(...) and step(...) records
13
+ -p, --proof Print a proof in the input's format (JavaScript, N3, SRL)
13
14
  -c, --prove-and-check Generate a proof and check it against the input program
14
15
  --check-proof FILE Print checked answers and a proof check report (- for stdin)
15
16
  --json Print the check report as JSON instead
@@ -27,6 +28,7 @@ and .srl as a SPARQL 1.2 RL rule set, both compiled to an eyemind program.
27
28
  --all With RDF output, write the given data too
28
29
  --program Print the program the inputs compile to
29
30
  --base IRI Resolve relative IRIs of the inputs against IRI
31
+ --stream-messages Run the rules independently for each RDF Message
30
32
  -v, --version Print the version
31
33
  -h, --help Print this help
32
34
  Source defaults to stdin; multiple files form one program.
@@ -62,6 +64,8 @@ export function main(argv, io) {
62
64
  let all = false;
63
65
  let printProgram = false;
64
66
  let base = null;
67
+ let streamMessages = false;
68
+ const filePositions = new Set();
65
69
  for (let i = 0; i < argv.length; i++) {
66
70
  const arg = argv[i];
67
71
  if (arg === '--help' || arg === '-h') {
@@ -88,6 +92,8 @@ export function main(argv, io) {
88
92
  all = true;
89
93
  } else if (arg === '--program') {
90
94
  printProgram = true;
95
+ } else if (arg === '--stream-messages') {
96
+ streamMessages = true;
91
97
  } else if (arg === '--check-proof' || arg === '--goal' || arg === '--to' || arg === '--base' || Object.hasOwn(LIMITS, arg)) {
92
98
  i++;
93
99
  if (i >= argv.length) throw new UsageError(`${arg} needs a value`);
@@ -116,6 +122,7 @@ export function main(argv, io) {
116
122
  throw new UsageError(`unknown option ${arg}`);
117
123
  } else {
118
124
  files.push(arg);
125
+ filePositions.add(i);
119
126
  }
120
127
  }
121
128
  if (asJson && proofFile === null && !proveAndCheck) throw new UsageError('--json requires --check-proof or --prove-and-check');
@@ -132,7 +139,46 @@ export function main(argv, io) {
132
139
  }
133
140
  if (!files.length) files.push('-');
134
141
  if (files.filter((file) => file === '-').length > 1) throw new UsageError('stdin can only be read once');
135
- const loaded = loadInputs(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io, { base });
142
+ if (streamMessages) {
143
+ if (proofFile !== null || options.proof || proveAndCheck || printProgram || unused) {
144
+ throw new UsageError('--stream-messages cannot be combined with --proof, --check-proof, --prove-and-check, --program or --unused; replay the whole log to prove its conclusions');
145
+ }
146
+ const args = argv.filter((arg, i) => arg !== '--stream-messages' && !filePositions.has(i));
147
+ let messageNumber = 0;
148
+ const request = {
149
+ files, base,
150
+ scope: (name, index = files.indexOf(name)) => scopeOf(files.map((f) => ['', f]), name, index),
151
+ run: (inputs, name, replay) => main([...args, ...inputs.map(([path]) => path), name], {
152
+ ...io,
153
+ // Each result is serialized separately; keep its blank labels
154
+ // distinct without retaining nodes from previous messages.
155
+ blankNodePrefix: `m${++messageNumber}_`,
156
+ messageInputs: new Map([[name === '-' ? '<stdin>' : name, replay]]),
157
+ readFile: (path) => path === name ? '' : inputs.find(([p]) => p === path)?.[1] ?? io.readFile(path),
158
+ stdin: () => name === '-' ? '' : io.stdin(),
159
+ }),
160
+ };
161
+ if (io.streamMessages) return io.streamMessages(request, io);
162
+ // Hosts such as the playground already hold their inputs as text.
163
+ // Node supplies the incremental file/HTTP implementation instead.
164
+ const sources = files.map((name, index) => ({ name, index, text: readSource(name, io) }));
165
+ const logs = sources.filter(({ text }) => isRdfMessageLog(text));
166
+ if (!logs.length) throw new UsageError('--stream-messages needs an RDF Message Log with VERSION "*-messages"');
167
+ const inputs = sources.filter((source) => !logs.includes(source)).map(({ name, text }) => [name, text]);
168
+ for (const { name, text, index } of logs) {
169
+ let code = 0;
170
+ const scope = request.scope(name, index);
171
+ const reader = new RdfMessageReader({ format: rdfMessageFormat(name), base: base ?? io.fileIri?.(name), scope, onMessage: (message) => {
172
+ code = request.run(inputs, name, replayMessages([message], { scope }));
173
+ return code === 0;
174
+ } });
175
+ reader.write(text);
176
+ reader.finish();
177
+ if (code) return code;
178
+ }
179
+ return 0;
180
+ }
181
+ const loaded = loadInputs(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io, { base, messageInputs: io.messageInputs });
136
182
  const program = loaded.program;
137
183
  if (printProgram) {
138
184
  stdout(loaded.text);
@@ -161,7 +207,9 @@ export function main(argv, io) {
161
207
  return report.valid ? result.haltCode || 0 : 2;
162
208
  }
163
209
  // Answers to goals are eyemind terms unless an output format is asked.
164
- const written = options.proof ? null : writeConclusions(loaded, result, { format: format ?? (goals.length ? 'eyemind' : defaultFormat(loaded.kind)), all });
210
+ const written = options.proof ? writeProof(loaded, result, { goals }) : writeConclusions(loaded, result, {
211
+ format: format ?? (goals.length ? 'eyemind' : defaultFormat(loaded.kind)), all, blankNodePrefix: io.blankNodePrefix,
212
+ });
165
213
  stdout(written ?? result.stdout);
166
214
  if (stats) stderr(`${JSON.stringify(result.stats)}\n`);
167
215
  return result.haltCode || 0;
package/src/formats.js CHANGED
@@ -21,6 +21,9 @@ import { DEFAULT_GRAPH, parseRdf, rdfDocument, rdfFormat, writeRdf } from './rdf
21
21
  import { answersToN3, compileSources } from './n3.js';
22
22
  import { compileSrl, srlQuads } from './srl.js';
23
23
  import { write } from './writer.js';
24
+ import { isRdfMessageLog, parseRdfMessages } from './messages.js';
25
+ import { writeNativeProof } from './native-proof.js';
26
+ import { checkProof } from './proof.js';
24
27
 
25
28
  export const OUTPUT_FORMATS = ['eyemind', 'turtle', 'trig', 'n-triples', 'n-quads', 'n3'];
26
29
 
@@ -32,6 +35,11 @@ export function inputKind(name) {
32
35
  return 'js';
33
36
  }
34
37
 
38
+ export function rdfMessageFormat(name) {
39
+ const path = /^https?:/.test(name) ? new URL(name).pathname : name;
40
+ return rdfFormat(path) ?? 'trig';
41
+ }
42
+
35
43
  // Load inputs, given as [text, name] pairs, as one program. io may supply
36
44
  // readFile, for the documents N3 and IMPORTS name, and fileIri(name), the
37
45
  // base IRI of a file. Returns { kind, program, text, prefixes, compiled }:
@@ -47,17 +55,26 @@ export function loadInputs(inputs, io = null, options = {}) {
47
55
  }
48
56
  }
49
57
 
50
- function load(inputs, io, { base = null }) {
51
- const kinds = inputs.map(([, name]) => inputKind(name));
58
+ function load(inputs, io, { base = null, messageInputs = null }) {
59
+ const kinds = inputs.map(([text, name]) => messageInputs?.has(name) ||
60
+ (inputKind(name) === 'n3' && isRdfMessageLog(text)) ? 'rdf' : inputKind(name));
52
61
  const baseOf = (name) => base ?? io?.fileIri?.(name) ?? null;
53
- const rdf = (text, name, k) => parseRdf(text, { format: rdfFormat(name), base: baseOf(name), scope: scopeOf(inputs, name, k) });
62
+ const rdf = (text, name, k) => messageInputs?.get(name) ??
63
+ (isRdfMessageLog(text) ? parseRdfMessages : parseRdf)(text, {
64
+ format: rdfFormat(name) ?? 'trig', base: baseOf(name), scope: scopeOf(inputs, name, k),
65
+ });
54
66
  if (kinds.includes('srl')) {
55
67
  const others = kinds.filter((k) => k !== 'srl' && k !== 'rdf');
56
68
  if (kinds.filter((k) => k === 'srl').length > 1 || others.length) {
57
69
  throw new EyemindError('a SPARQL 1.2 RL run takes one .srl rule set, and RDF data for its base graph');
58
70
  }
59
71
  const [text, name] = inputs[kinds.indexOf('srl')];
60
- const data = inputs.flatMap(([t, n], k) => (kinds[k] === 'rdf' ? rdf(t, n, k).quads : []));
72
+ const data = inputs.flatMap(([t, n], k) => {
73
+ if (kinds[k] !== 'rdf') return [];
74
+ const parsed = rdf(t, n, k);
75
+ if (parsed.triples) throw new EyemindError('RDF Message Log replay needs N3 or JavaScript rules; a SPARQL rule set takes an RDF base graph');
76
+ return parsed.quads;
77
+ });
61
78
  const compiled = compileSrl(text, { base: baseOf(name), filename: name, resolve: importResolver(io), data });
62
79
  for (const warning of compiled.warnings) io?.stderr?.(`eyemind: warning: ${warning}\n`);
63
80
  return { kind: 'srl', program: loadSources([[compiled.program, name]], io), text: compiled.program, prefixes: compiled.prefixes, compiled };
@@ -82,7 +99,7 @@ function load(inputs, io, { base = null }) {
82
99
  }
83
100
 
84
101
  // A blank-node scope per data file: its name, numbered when names repeat.
85
- function scopeOf(inputs, name, k) {
102
+ export function scopeOf(inputs, name, k) {
86
103
  const base = String(name).replace(/^.*[\\/]/, '');
87
104
  const same = inputs.filter(([, n]) => String(n).replace(/^.*[\\/]/, '') === base);
88
105
  return same.length > 1 ? `${base}#${inputs.slice(0, k).filter(([, n]) => String(n).replace(/^.*[\\/]/, '') === base).length + 1}` : base;
@@ -105,19 +122,29 @@ function importResolver(io) {
105
122
  // eyemind's own text for a program.
106
123
  export const defaultFormat = (kind) => ({ n3: 'n3', srl: 'turtle' })[kind] ?? 'eyemind';
107
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
+
108
135
  // The conclusions of a run in an output format; null for eyemind's own text.
109
136
  // all also writes the given data. Throws when a conclusion is no triple.
110
- export function writeConclusions(loaded, result, { format, all = false } = {}) {
137
+ export function writeConclusions(loaded, result, { format, all = false, blankNodePrefix = '' } = {}) {
111
138
  if (format === 'eyemind') return null;
112
139
  const answers = result.answers;
113
140
  if (format === 'n3') {
114
141
  if (loaded.kind !== 'n3') throw new EyemindError('--to n3 writes the conclusions of an N3 run');
115
- return answersToN3(loaded.compiled.doc, answers, { mode: all ? 'all' : 'new' }).n3;
142
+ return answersToN3(loaded.compiled.doc, answers, { mode: all ? 'all' : 'new', blankNodePrefix }).n3;
116
143
  }
117
144
  let quads;
118
145
  if (loaded.kind === 'srl') quads = srlQuads(loaded.text, answers, { all });
119
146
  else quads = conclusionQuads(answers, all ? loaded.text : null);
120
- return writeRdf(quads, { format, prefixes: loaded.kind === 'n3' ? Object.fromEntries(loaded.prefixes) : loaded.prefixes });
147
+ return writeRdf(quads, { format, prefixes: loaded.kind === 'n3' ? Object.fromEntries(loaded.prefixes) : loaded.prefixes, blankNodePrefix });
121
148
  }
122
149
 
123
150
  // Conclusions that are triples, rdf/3 or result/3, or quads, rdf/4 or
package/src/index.js CHANGED
@@ -10,6 +10,8 @@ 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';
17
+ export { RdfMessageReader, parseRdfMessages } from './messages.js';