@dxos/echo-memory 0.0.0-stage → 0.0.0

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.
Files changed (147) hide show
  1. package/LICENSE +105 -0
  2. package/dist/lib/Fact.mjs +1 -0
  3. package/dist/lib/FactFeed.mjs +1 -0
  4. package/dist/lib/Graph.mjs +1 -0
  5. package/dist/lib/Hash.mjs +1 -0
  6. package/dist/lib/Mapping.mjs +1 -0
  7. package/dist/lib/MemoryError.mjs +1 -0
  8. package/dist/lib/MemoryQuery.mjs +1 -0
  9. package/dist/lib/MemoryService.mjs +1 -0
  10. package/dist/lib/Ontology.mjs +1 -0
  11. package/dist/lib/Pipeline.mjs +1 -0
  12. package/dist/lib/Predicate.mjs +1 -0
  13. package/dist/lib/Rdf.mjs +1 -0
  14. package/dist/lib/RdfStore.mjs +1 -0
  15. package/dist/lib/Sparql.mjs +1 -0
  16. package/dist/lib/Subscription.mjs +1 -0
  17. package/dist/lib/Trig.mjs +1 -0
  18. package/dist/lib/Vocab.mjs +1 -0
  19. package/dist/lib/Vocabularies.mjs +1 -0
  20. package/dist/lib/chunk-Fact.mjs +245 -0
  21. package/dist/lib/chunk-Fact.mjs.map +1 -0
  22. package/dist/lib/chunk-FactFeed.mjs +29 -0
  23. package/dist/lib/chunk-FactFeed.mjs.map +1 -0
  24. package/dist/lib/chunk-Graph.mjs +147 -0
  25. package/dist/lib/chunk-Graph.mjs.map +1 -0
  26. package/dist/lib/chunk-Hash.mjs +16 -0
  27. package/dist/lib/chunk-Hash.mjs.map +1 -0
  28. package/dist/lib/chunk-Mapping.mjs +226 -0
  29. package/dist/lib/chunk-Mapping.mjs.map +1 -0
  30. package/dist/lib/chunk-MemoryError.mjs +10 -0
  31. package/dist/lib/chunk-MemoryError.mjs.map +1 -0
  32. package/dist/lib/chunk-MemoryQuery.mjs +99 -0
  33. package/dist/lib/chunk-MemoryQuery.mjs.map +1 -0
  34. package/dist/lib/chunk-MemoryService.mjs +31 -0
  35. package/dist/lib/chunk-MemoryService.mjs.map +1 -0
  36. package/dist/lib/chunk-Ontology.mjs +529 -0
  37. package/dist/lib/chunk-Ontology.mjs.map +1 -0
  38. package/dist/lib/chunk-Pipeline.mjs +84 -0
  39. package/dist/lib/chunk-Pipeline.mjs.map +1 -0
  40. package/dist/lib/chunk-Predicate.mjs +66 -0
  41. package/dist/lib/chunk-Predicate.mjs.map +1 -0
  42. package/dist/lib/chunk-Rdf.mjs +120 -0
  43. package/dist/lib/chunk-Rdf.mjs.map +1 -0
  44. package/dist/lib/chunk-RdfStore.mjs +60 -0
  45. package/dist/lib/chunk-RdfStore.mjs.map +1 -0
  46. package/dist/lib/chunk-Sparql.mjs +153 -0
  47. package/dist/lib/chunk-Sparql.mjs.map +1 -0
  48. package/dist/lib/chunk-Subscription.mjs +44 -0
  49. package/dist/lib/chunk-Subscription.mjs.map +1 -0
  50. package/dist/lib/chunk-Trig.mjs +106 -0
  51. package/dist/lib/chunk-Trig.mjs.map +1 -0
  52. package/dist/lib/chunk-Vocab.mjs +164 -0
  53. package/dist/lib/chunk-Vocab.mjs.map +1 -0
  54. package/dist/lib/chunk-Vocabularies.mjs +343 -0
  55. package/dist/lib/chunk-Vocabularies.mjs.map +1 -0
  56. package/dist/lib/chunk-rolldown-runtime.mjs +13 -0
  57. package/dist/lib/index.mjs +19 -0
  58. package/dist/types/src/Fact.d.ts +339 -0
  59. package/dist/types/src/Fact.d.ts.map +1 -0
  60. package/dist/types/src/Fact.test.d.ts +2 -0
  61. package/dist/types/src/Fact.test.d.ts.map +1 -0
  62. package/dist/types/src/FactFeed.d.ts +11 -0
  63. package/dist/types/src/FactFeed.d.ts.map +1 -0
  64. package/dist/types/src/FactFeed.test.d.ts +2 -0
  65. package/dist/types/src/FactFeed.test.d.ts.map +1 -0
  66. package/dist/types/src/Graph.d.ts +31 -0
  67. package/dist/types/src/Graph.d.ts.map +1 -0
  68. package/dist/types/src/Graph.test.d.ts +2 -0
  69. package/dist/types/src/Graph.test.d.ts.map +1 -0
  70. package/dist/types/src/Hash.d.ts +3 -0
  71. package/dist/types/src/Hash.d.ts.map +1 -0
  72. package/dist/types/src/Mapping.d.ts +18 -0
  73. package/dist/types/src/Mapping.d.ts.map +1 -0
  74. package/dist/types/src/Mapping.test.d.ts +2 -0
  75. package/dist/types/src/Mapping.test.d.ts.map +1 -0
  76. package/dist/types/src/MemoryError.d.ts +33 -0
  77. package/dist/types/src/MemoryError.d.ts.map +1 -0
  78. package/dist/types/src/MemoryQuery.d.ts +136 -0
  79. package/dist/types/src/MemoryQuery.d.ts.map +1 -0
  80. package/dist/types/src/MemoryQuery.test.d.ts +2 -0
  81. package/dist/types/src/MemoryQuery.test.d.ts.map +1 -0
  82. package/dist/types/src/MemoryService.d.ts +72 -0
  83. package/dist/types/src/MemoryService.d.ts.map +1 -0
  84. package/dist/types/src/Ontology.d.ts +115 -0
  85. package/dist/types/src/Ontology.d.ts.map +1 -0
  86. package/dist/types/src/Ontology.test.d.ts +2 -0
  87. package/dist/types/src/Ontology.test.d.ts.map +1 -0
  88. package/dist/types/src/Pipeline.d.ts +103 -0
  89. package/dist/types/src/Pipeline.d.ts.map +1 -0
  90. package/dist/types/src/Predicate.d.ts +17 -0
  91. package/dist/types/src/Predicate.d.ts.map +1 -0
  92. package/dist/types/src/Predicate.test.d.ts +2 -0
  93. package/dist/types/src/Predicate.test.d.ts.map +1 -0
  94. package/dist/types/src/Rdf.d.ts +33 -0
  95. package/dist/types/src/Rdf.d.ts.map +1 -0
  96. package/dist/types/src/Rdf.test.d.ts +2 -0
  97. package/dist/types/src/Rdf.test.d.ts.map +1 -0
  98. package/dist/types/src/RdfStore.d.ts +471 -0
  99. package/dist/types/src/RdfStore.d.ts.map +1 -0
  100. package/dist/types/src/Sparql.d.ts +58 -0
  101. package/dist/types/src/Sparql.d.ts.map +1 -0
  102. package/dist/types/src/Sparql.test.d.ts +2 -0
  103. package/dist/types/src/Sparql.test.d.ts.map +1 -0
  104. package/dist/types/src/Subscription.d.ts +100 -0
  105. package/dist/types/src/Subscription.d.ts.map +1 -0
  106. package/dist/types/src/Trig.d.ts +8 -0
  107. package/dist/types/src/Trig.d.ts.map +1 -0
  108. package/dist/types/src/Trig.test.d.ts +2 -0
  109. package/dist/types/src/Trig.test.d.ts.map +1 -0
  110. package/dist/types/src/Vocab.d.ts +90 -0
  111. package/dist/types/src/Vocab.d.ts.map +1 -0
  112. package/dist/types/src/Vocabularies.d.ts +45 -0
  113. package/dist/types/src/Vocabularies.d.ts.map +1 -0
  114. package/dist/types/src/index.d.ts +19 -0
  115. package/dist/types/src/index.d.ts.map +1 -0
  116. package/dist/types/tsconfig.tsbuildinfo +1 -0
  117. package/package.json +133 -3
  118. package/src/Fact.test.ts +74 -0
  119. package/src/Fact.ts +269 -0
  120. package/src/FactFeed.test.ts +40 -0
  121. package/src/FactFeed.ts +38 -0
  122. package/src/Graph.test.ts +106 -0
  123. package/src/Graph.ts +158 -0
  124. package/src/Hash.ts +15 -0
  125. package/src/Mapping.test.ts +197 -0
  126. package/src/Mapping.ts +320 -0
  127. package/src/MemoryError.ts +10 -0
  128. package/src/MemoryQuery.test.ts +67 -0
  129. package/src/MemoryQuery.ts +114 -0
  130. package/src/MemoryService.ts +89 -0
  131. package/src/Ontology.test.ts +94 -0
  132. package/src/Ontology.ts +571 -0
  133. package/src/Pipeline.ts +97 -0
  134. package/src/Predicate.test.ts +47 -0
  135. package/src/Predicate.ts +89 -0
  136. package/src/Rdf.test.ts +104 -0
  137. package/src/Rdf.ts +158 -0
  138. package/src/RdfStore.ts +111 -0
  139. package/src/Sparql.test.ts +72 -0
  140. package/src/Sparql.ts +237 -0
  141. package/src/Subscription.ts +47 -0
  142. package/src/Trig.test.ts +199 -0
  143. package/src/Trig.ts +170 -0
  144. package/src/Vocab.ts +134 -0
  145. package/src/Vocabularies.ts +204 -0
  146. package/src/index.ts +22 -0
  147. package/README.md +0 -3
@@ -0,0 +1,10 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import { BaseError } from '@dxos/errors';
8
+
9
+ /** The memory refused, could not be reached, or the input does not compile; the message says which. */
10
+ export class MemoryError extends BaseError.extend('MemoryError', 'Memory operation failed.') {}
@@ -0,0 +1,67 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Schema from 'effect/Schema';
6
+ import { describe, expectTypeOf, test } from 'vitest';
7
+
8
+ import * as Fact from './Fact.ts';
9
+ import * as MemoryQuery from './MemoryQuery.ts';
10
+ import * as Subscription from './Subscription.ts';
11
+
12
+ describe('MemoryQuery', () => {
13
+ test('each constructor fixes its answer type', () => {
14
+ expectTypeOf<MemoryQuery.ResultOf<MemoryQuery.Facts>>().toEqualTypeOf<readonly Fact.Fact[]>();
15
+ expectTypeOf<MemoryQuery.ResultOf<ReturnType<typeof MemoryQuery.sparql>>>().toEqualTypeOf<
16
+ readonly MemoryQuery.SparqlRow[]
17
+ >();
18
+ expectTypeOf<MemoryQuery.ResultOf<ReturnType<typeof MemoryQuery.cursor>>>().toEqualTypeOf<string | undefined>();
19
+ });
20
+
21
+ test('a query is plain JSON and decodes back by its tag', ({ expect }) => {
22
+ const queries: MemoryQuery.Any[] = [
23
+ MemoryQuery.facts({ entity: Fact.EntityKey.make('alice'), minConfidence: 0.5 }),
24
+ MemoryQuery.graphs('SELECT ?g WHERE { GRAPH ?g { ?s ?p ?o } }'),
25
+ MemoryQuery.sparql('SELECT ?s WHERE { ?s ?p ?o }'),
26
+ MemoryQuery.predicates(),
27
+ MemoryQuery.cursor(Fact.SourceUri.make('dxn:queue:space:chat')),
28
+ ];
29
+ for (const query of queries) {
30
+ const json = JSON.parse(JSON.stringify(Schema.encodeSync(MemoryQuery.Any)(query)));
31
+ expect(Schema.decodeUnknownSync(MemoryQuery.Any)(json)).toEqual(query);
32
+ }
33
+ });
34
+
35
+ test('an answer decodes with the schema its tag names', ({ expect }) => {
36
+ const rows = [{ s: { termType: 'NamedNode', value: 'https://example.com/alice' } }];
37
+ const schema = MemoryQuery.resultOf(MemoryQuery.sparql('SELECT ?s WHERE { ?s ?p ?o }'));
38
+ expect(Schema.decodeUnknownSync(schema)(JSON.parse(JSON.stringify(rows)))).toEqual(rows);
39
+ expect(Schema.decodeUnknownSync(MemoryQuery.resultSchema('cursor'))(undefined)).toBeUndefined();
40
+ });
41
+ });
42
+
43
+ describe('Subscription', () => {
44
+ test('subscriptions and events are plain JSON', ({ expect }) => {
45
+ const subscription = Schema.decodeUnknownSync(Subscription.Subscription)({
46
+ id: 'alice.1',
47
+ owner: 'alice',
48
+ rules: 'wake(match) :- fact(F).',
49
+ createdAt: '2026-11-16T00:00:00.000Z',
50
+ payload: { notify: { recipient: { '/': 'echo://space/obj' }, message: 'hi' } },
51
+ });
52
+ const event = Schema.decodeUnknownSync(Subscription.MemoryEvent)({
53
+ id: 'event-1',
54
+ subscription: 'alice.1',
55
+ label: 'match',
56
+ facts: [],
57
+ at: '2026-11-16T00:00:00.000Z',
58
+ });
59
+ for (const [schema, value] of [
60
+ [Subscription.Subscription, subscription],
61
+ [Subscription.MemoryEvent, event],
62
+ ] as const) {
63
+ const json = JSON.parse(JSON.stringify(Schema.encodeUnknownSync(schema)(value)));
64
+ expect(Schema.decodeUnknownSync(schema)(json)).toEqual(value);
65
+ }
66
+ });
67
+ });
@@ -0,0 +1,114 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as Schema from 'effect/Schema';
8
+
9
+ import * as Fact from './Fact.ts';
10
+
11
+ /** What a {@link Facts} query selects; every field set must hold. */
12
+ export const FactQuery = Schema.Struct({
13
+ /** Entity in the subject position. */
14
+ subjectEntity: Schema.optional(Fact.EntityKey),
15
+ /** Entity in the subject or object position. */
16
+ entity: Schema.optional(Fact.EntityKey),
17
+ /** Predicate IRI, or a surface form resolved through the memory's ontology. */
18
+ predicate: Schema.optional(Schema.String),
19
+ /** The item the facts were read from. */
20
+ source: Schema.optional(Fact.SourceUri),
21
+ /** Inclusive lower bound on factuality confidence. */
22
+ minConfidence: Schema.optional(Schema.Number),
23
+ });
24
+ export interface FactQuery extends Schema.Schema.Type<typeof FactQuery> {}
25
+
26
+ /** One RDF term a SPARQL solution binds; plain data, so rows cross a wire as JSON. */
27
+ export const SparqlTerm = Schema.Union([
28
+ Schema.Struct({ termType: Schema.Literal('NamedNode'), value: Schema.String }),
29
+ Schema.Struct({ termType: Schema.Literal('BlankNode'), value: Schema.String }),
30
+ Schema.Struct({
31
+ termType: Schema.Literal('Literal'),
32
+ value: Schema.String,
33
+ datatype: Schema.optional(Schema.String),
34
+ language: Schema.optional(Schema.String),
35
+ }),
36
+ ]);
37
+ export type SparqlTerm = Schema.Schema.Type<typeof SparqlTerm>;
38
+
39
+ /** One SPARQL solution: each bound variable (named without `?`) to its term; an unbound variable is absent. */
40
+ export const SparqlRow = Schema.Record(Schema.String, SparqlTerm);
41
+ export type SparqlRow = Schema.Schema.Type<typeof SparqlRow>;
42
+
43
+ //
44
+ // Query kinds. Each is a tagged struct, so a query is plain JSON; `results` names the schema of each kind's answer.
45
+ //
46
+
47
+ /** Facts whose statement matches a pattern. Answered without SPARQL on every implementation. */
48
+ export const Facts = Schema.TaggedStruct('facts', { pattern: FactQuery });
49
+ export interface Facts extends Schema.Schema.Type<typeof Facts> {}
50
+
51
+ /** Every fact in the named graphs a SPARQL `SELECT ?g` binds. */
52
+ export const Graphs = Schema.TaggedStruct('graphs', { sparql: Schema.String });
53
+ export interface Graphs extends Schema.Schema.Type<typeof Graphs> {}
54
+
55
+ /** Any SPARQL `SELECT`, its solutions returned as written. */
56
+ export const Sparql = Schema.TaggedStruct('sparql', { sparql: Schema.String });
57
+ export interface Sparql extends Schema.Schema.Type<typeof Sparql> {}
58
+
59
+ /** The predicates the memory knows. */
60
+ export const Predicates = Schema.TaggedStruct('predicates', {});
61
+ export interface Predicates extends Schema.Schema.Type<typeof Predicates> {}
62
+
63
+ /** How far a source has been read: the `through` of its read cursor. */
64
+ export const Cursor = Schema.TaggedStruct('cursor', { source: Fact.SourceUri });
65
+ export interface Cursor extends Schema.Schema.Type<typeof Cursor> {}
66
+
67
+ /** Any query kind. */
68
+ export const Any = Schema.Union([Facts, Graphs, Sparql, Predicates, Cursor]);
69
+ export type Any = Schema.Schema.Type<typeof Any>;
70
+
71
+ export type Tag = Any['_tag'];
72
+
73
+ /** What each kind answers. */
74
+ export interface Results {
75
+ readonly facts: readonly Fact.Fact[];
76
+ readonly graphs: readonly Fact.Fact[];
77
+ readonly sparql: readonly SparqlRow[];
78
+ readonly predicates: readonly Fact.PredicateEntry[];
79
+ readonly cursor: string | undefined;
80
+ }
81
+
82
+ /** The schema of each kind's answer, so a remote client decodes an answer by the query's `_tag`. */
83
+ export const results: { readonly [K in Tag]: Schema.Codec<Results[K], unknown> } = {
84
+ facts: Schema.Array(Fact.Fact),
85
+ graphs: Schema.Array(Fact.Fact),
86
+ sparql: Schema.Array(SparqlRow),
87
+ predicates: Schema.Array(Fact.PredicateEntry),
88
+ cursor: Schema.UndefinedOr(Schema.String),
89
+ };
90
+
91
+ /** The schema of a kind's answer. */
92
+ export const resultSchema = <K extends Tag>(tag: K): Schema.Codec<Results[K], unknown> => results[tag];
93
+
94
+ /** The schema of a query's answer. */
95
+ export const resultOf = <Q extends Any>(query: Q): Schema.Codec<Results[Q['_tag']], unknown> =>
96
+ resultSchema<Q['_tag']>(query._tag);
97
+
98
+ /** What a query answers. */
99
+ export type ResultOf<Q extends Any> = Results[Q['_tag']];
100
+
101
+ /** Facts whose statement matches the pattern; answers `Fact[]`. */
102
+ export const facts = (pattern: FactQuery = {}): Facts => Facts.make({ pattern });
103
+
104
+ /** Every fact in the graphs a `SELECT ?g` binds; answers `Fact[]`. */
105
+ export const graphs = (sparql: string): Graphs => Graphs.make({ sparql });
106
+
107
+ /** A SPARQL `SELECT`'s solutions; answers `SparqlRow[]`. */
108
+ export const sparql = (sparql: string): Sparql => Sparql.make({ sparql });
109
+
110
+ /** The known predicates; answers `PredicateEntry[]`. */
111
+ export const predicates = (): Predicates => Predicates.make({});
112
+
113
+ /** A source's read cursor; answers `string | undefined`. */
114
+ export const cursor = (source: Fact.SourceUri): Cursor => Cursor.make({ source });
@@ -0,0 +1,89 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as Context from 'effect/Context';
8
+ import type * as Effect from 'effect/Effect';
9
+ import * as Schema from 'effect/Schema';
10
+
11
+ import * as Fact from './Fact.ts';
12
+ import type * as MemoryError from './MemoryError.ts';
13
+ import type * as MemoryQuery from './MemoryQuery.ts';
14
+ import type * as Subscription from './Subscription.ts';
15
+
16
+ /** How far a source has been read into facts. */
17
+ export const ReadCursor = Schema.Struct({
18
+ /** The source read (a chat, a feed, a mailbox). */
19
+ source: Fact.SourceUri,
20
+ /** URI or hash of the last item read; the next read starts after it. */
21
+ through: Schema.String,
22
+ });
23
+ export interface ReadCursor extends Schema.Schema.Type<typeof ReadCursor> {}
24
+
25
+ export const PutOptions = Schema.Struct({
26
+ /** Speakers whose facts are stored but wake nothing on their own. */
27
+ quiet: Schema.optional(Schema.Array(Fact.EntityKey)),
28
+ /** Moved in the same write as the facts. */
29
+ read: Schema.optional(ReadCursor),
30
+ });
31
+ export interface PutOptions extends Schema.Schema.Type<typeof PutOptions> {}
32
+
33
+ /**
34
+ * The memory of one space, in two halves over one store.
35
+ *
36
+ * - Knowledge base: {@link Service.put} stores facts and {@link Service.query} reads them back.
37
+ * - Event base: a subscription carries goal rules; whenever put facts or the clock wake them, an event is queued
38
+ * in that subscription's own outbox, which its consumer drains with {@link Service.take} and {@link Service.ack}.
39
+ *
40
+ * Time-driven rules are evaluated by the implementation on its own; the interface has no op for the clock.
41
+ */
42
+ export interface Service {
43
+ /**
44
+ * Stores facts (a repeated put is idempotent), moves `options.read` in the same write, and returns how many
45
+ * events the write queued. A put with no facts only moves the cursor.
46
+ */
47
+ readonly put: (facts: readonly Fact.Fact[], options?: PutOptions) => Effect.Effect<number, MemoryError.MemoryError>;
48
+
49
+ /** The only read of the knowledge base; the query's kind fixes what it answers. */
50
+ readonly query: <Q extends MemoryQuery.Any>(
51
+ query: Q,
52
+ ) => Effect.Effect<MemoryQuery.ResultOf<Q>, MemoryError.MemoryError>;
53
+
54
+ /**
55
+ * Forgets the facts, read cursors and queued events, and restores the seed vocabulary; subscriptions stay, with
56
+ * their rule state started over.
57
+ */
58
+ readonly reset: () => Effect.Effect<void, MemoryError.MemoryError>;
59
+
60
+ /**
61
+ * Adds a subscription, or replaces the one with its id. False, adding nothing, when the space holds
62
+ * `MAX_SUBSCRIPTIONS` others; fails when its rules do not compile.
63
+ */
64
+ readonly subscribe: (subscription: Subscription.Subscription) => Effect.Effect<boolean, MemoryError.MemoryError>;
65
+
66
+ /** Subscriptions oldest first: all, or those the owner holds. */
67
+ readonly subscriptions: (
68
+ owner?: Fact.EntityKey,
69
+ ) => Effect.Effect<Subscription.Subscription[], MemoryError.MemoryError>;
70
+
71
+ /** Removes a subscription and its outbox; false when it was already gone. */
72
+ readonly unsubscribe: (id: Subscription.SubscriptionId) => Effect.Effect<boolean, MemoryError.MemoryError>;
73
+
74
+ /** The subscription's unacknowledged events, oldest first; empty for an unknown subscription. */
75
+ readonly take: (
76
+ id: Subscription.SubscriptionId,
77
+ ) => Effect.Effect<Subscription.MemoryEvent[], MemoryError.MemoryError>;
78
+
79
+ /** Removes the events from the outbox; unknown ids are ignored. */
80
+ readonly ack: (
81
+ id: Subscription.SubscriptionId,
82
+ events: readonly Subscription.MemoryEventId[],
83
+ ) => Effect.Effect<void, MemoryError.MemoryError>;
84
+ }
85
+
86
+ export class MemoryService extends Context.Service<MemoryService, Service>()('@dxos/echo-memory/MemoryService') {}
87
+
88
+ /** Re-exported so callers importing this module as a namespace avoid `MemoryService.MemoryService.key`. */
89
+ export const key = MemoryService.key;
@@ -0,0 +1,94 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import * as Ontology from './Ontology.ts';
8
+ import * as Vocab from './Vocab.ts';
9
+
10
+ describe('Ontology', () => {
11
+ test('resolves a synonym and an inflection to the defined predicate', ({ expect }) => {
12
+ expect(Ontology.DEFAULT.resolve('is on the team as').iri).toBe('https://schema.org/jobTitle');
13
+ expect(Ontology.DEFAULT.resolve('Working-On').name).toBe('works_on');
14
+ expect(Ontology.DEFAULT.resolve('worksOn').name).toBe('works_on');
15
+ });
16
+
17
+ test('seeds predicates from established vocabularies under their own IRIs', ({ expect }) => {
18
+ expect(Ontology.DEFAULT.resolve('is a').iri).toBe(Vocab.RDF_TYPE);
19
+ expect(Ontology.DEFAULT.resolve('employed by').iri).toBe('https://schema.org/worksFor');
20
+ expect(Ontology.DEFAULT.resolve('knows').iri).toBe('http://xmlns.com/foaf/0.1/knows');
21
+ expect(Ontology.DEFAULT.resolve('created by').iri).toBe('http://purl.org/dc/terms/creator');
22
+ expect(Ontology.DEFAULT.resolve('claim').iri).toBe(`${Vocab.DX}claim`);
23
+ });
24
+
25
+ test('a predicate stored under its former dx: IRI reads and matches as the seed', ({ expect }) => {
26
+ expect(Ontology.DEFAULT.get(`${Vocab.DX}hasRole`)?.label).toBe('has role');
27
+ expect(Ontology.DEFAULT.equivalents('https://schema.org/jobTitle')).toEqual(
28
+ new Set(['https://schema.org/jobTitle', `${Vocab.DX}hasRole`]),
29
+ );
30
+ });
31
+
32
+ test('seeds `uses`, matching what extractors minted for it before', ({ expect }) => {
33
+ expect(Ontology.DEFAULT.resolve('is using').iri).toBe(`${Vocab.DX}uses`);
34
+ expect(Ontology.DEFAULT.resolve('built with').iri).toBe(`${Vocab.DX}uses`);
35
+ expect(Ontology.DEFAULT.get(`${Vocab.LOCAL_BRAIN}uses`)?.name).toBe('uses');
36
+ });
37
+
38
+ test('mints an unknown predicate in its namespace, labelled with its surface form', ({ expect }) => {
39
+ const first = Ontology.DEFAULT.resolve('travels to');
40
+ expect(first).toEqual({
41
+ iri: `${Vocab.LOCAL_BRAIN}travelsTo`,
42
+ name: 'travels_to',
43
+ label: 'travels to',
44
+ definedBy: Vocab.LOCAL_BRAIN,
45
+ });
46
+ // Minted as said, matched by stem: once known, an inflected variant resolves to the same predicate.
47
+ expect(Ontology.DEFAULT.extend([first]).resolve('traveling to').iri).toBe(first.iri);
48
+ expect(Ontology.DEFAULT.get(first.iri)).toBeUndefined();
49
+
50
+ const brain = Ontology.DEFAULT.withNamespace(Vocab.brainNamespace('agent-1'));
51
+ expect(brain.resolve('travels to').iri).toBe('https://dxos.org/semantic/brain/agent-1/travelsTo');
52
+ });
53
+
54
+ test('extends with a new predicate, and rejects a synonym claimed twice', ({ expect }) => {
55
+ const ontology = Ontology.DEFAULT.extend([Ontology.entry('mentors', { synonyms: ['coaches'] })]);
56
+ expect(ontology.resolve('Coaches').iri).toBe('https://dxos.org/ontology/mentors');
57
+ expect(() => ontology.extend([Ontology.entry('trains', { synonyms: ['coaches'] })])).toThrow(/coaches/);
58
+ });
59
+
60
+ test('includes learned predicates, skipping those it already names', ({ expect }) => {
61
+ const learned = Ontology.DEFAULT.include([
62
+ Ontology.DEFAULT.resolve('travels to'),
63
+ { iri: `${Vocab.LOCAL_BRAIN}employedBy`, name: 'employ_by', label: 'employed by' },
64
+ ]);
65
+ expect(learned.get(`${Vocab.LOCAL_BRAIN}travelsTo`)?.label).toBe('travels to');
66
+ expect(learned.get(`${Vocab.LOCAL_BRAIN}employedBy`)).toBeUndefined();
67
+ });
68
+
69
+ test('merges one predicate into another, keeping the merged one readable', ({ expect }) => {
70
+ const minted = { ...Ontology.DEFAULT.resolve('gets paid by'), description: 'Employer.' };
71
+ const merged = Ontology.DEFAULT.extend([{ ...minted, synonyms: ['on the payroll of'] }]).merge(
72
+ minted.iri,
73
+ 'https://schema.org/worksFor',
74
+ );
75
+ expect(merged.resolve('on the payroll of').iri).toBe('https://schema.org/worksFor');
76
+ expect(merged.get(minted.iri)?.replacedBy).toBe('https://schema.org/worksFor');
77
+ expect(merged.equivalents('https://schema.org/worksFor').has(minted.iri)).toBe(true);
78
+ // Either way round: a query by the merged-away IRI matches the survivor.
79
+ expect(merged.equivalents(minted.iri).has('https://schema.org/worksFor')).toBe(true);
80
+ expect(merged.canonical(minted.iri)?.iri).toBe('https://schema.org/worksFor');
81
+ });
82
+
83
+ test('round-trips an entry through the ontology graph', ({ expect }) => {
84
+ const entry = Ontology.DEFAULT.get('https://schema.org/memberOf');
85
+ expect(entry).toBeDefined();
86
+ if (entry) {
87
+ expect(Ontology.fromQuads(Ontology.toQuads(entry))).toEqual([entry]);
88
+ }
89
+ });
90
+
91
+ test('reads an IRI it does not define by its local name', ({ expect }) => {
92
+ expect(Ontology.labelFromIri('https://dxos.org/ontology/travelTo')).toBe('travel to');
93
+ });
94
+ });