@dxos/brain 0.0.1 → 0.12.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 (68) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +32 -1
  3. package/dist/lib/Builtins.mjs +178 -0
  4. package/dist/lib/Builtins.mjs.map +1 -0
  5. package/dist/lib/CompilePrompt.mjs +305 -0
  6. package/dist/lib/CompilePrompt.mjs.map +1 -0
  7. package/dist/lib/Compiler.mjs +212 -0
  8. package/dist/lib/Compiler.mjs.map +1 -0
  9. package/dist/lib/Encoding.mjs +116 -0
  10. package/dist/lib/Encoding.mjs.map +1 -0
  11. package/dist/lib/GoalRules.mjs +161 -0
  12. package/dist/lib/GoalRules.mjs.map +1 -0
  13. package/dist/lib/Vocabulary.mjs +92 -0
  14. package/dist/lib/Vocabulary.mjs.map +1 -0
  15. package/dist/lib/chunk-rolldown-runtime.mjs +13 -0
  16. package/dist/lib/index.mjs +7 -0
  17. package/dist/lib/testing.mjs +831 -0
  18. package/dist/lib/testing.mjs.map +1 -0
  19. package/dist/types/src/Builtins.d.ts +57 -0
  20. package/dist/types/src/Builtins.d.ts.map +1 -0
  21. package/dist/types/src/Builtins.test.d.ts +2 -0
  22. package/dist/types/src/Builtins.test.d.ts.map +1 -0
  23. package/dist/types/src/CompilePrompt.d.ts +107 -0
  24. package/dist/types/src/CompilePrompt.d.ts.map +1 -0
  25. package/dist/types/src/CompilePrompt.test.d.ts +2 -0
  26. package/dist/types/src/CompilePrompt.test.d.ts.map +1 -0
  27. package/dist/types/src/Compiler.d.ts +76 -0
  28. package/dist/types/src/Compiler.d.ts.map +1 -0
  29. package/dist/types/src/Compiler.test.d.ts +2 -0
  30. package/dist/types/src/Compiler.test.d.ts.map +1 -0
  31. package/dist/types/src/Encoding.d.ts +42 -0
  32. package/dist/types/src/Encoding.d.ts.map +1 -0
  33. package/dist/types/src/GoalRules.d.ts +66 -0
  34. package/dist/types/src/GoalRules.d.ts.map +1 -0
  35. package/dist/types/src/GoalRules.test.d.ts +2 -0
  36. package/dist/types/src/GoalRules.test.d.ts.map +1 -0
  37. package/dist/types/src/Vocabulary.d.ts +31 -0
  38. package/dist/types/src/Vocabulary.d.ts.map +1 -0
  39. package/dist/types/src/Vocabulary.test.d.ts +2 -0
  40. package/dist/types/src/Vocabulary.test.d.ts.map +1 -0
  41. package/dist/types/src/index.d.ts +7 -0
  42. package/dist/types/src/index.d.ts.map +1 -0
  43. package/dist/types/src/testing/index.d.ts +4 -0
  44. package/dist/types/src/testing/index.d.ts.map +1 -0
  45. package/dist/types/src/testing/reference.d.ts +9 -0
  46. package/dist/types/src/testing/reference.d.ts.map +1 -0
  47. package/dist/types/src/testing/scenarios.d.ts +73 -0
  48. package/dist/types/src/testing/scenarios.d.ts.map +1 -0
  49. package/dist/types/src/testing/simulate.d.ts +31 -0
  50. package/dist/types/src/testing/simulate.d.ts.map +1 -0
  51. package/dist/types/tsconfig.tsbuildinfo +1 -0
  52. package/package.json +74 -5
  53. package/src/Builtins.test.ts +45 -0
  54. package/src/Builtins.ts +274 -0
  55. package/src/CompilePrompt.test.ts +117 -0
  56. package/src/CompilePrompt.ts +376 -0
  57. package/src/Compiler.test.ts +85 -0
  58. package/src/Compiler.ts +234 -0
  59. package/src/Encoding.ts +99 -0
  60. package/src/GoalRules.test.ts +96 -0
  61. package/src/GoalRules.ts +181 -0
  62. package/src/Vocabulary.test.ts +48 -0
  63. package/src/Vocabulary.ts +88 -0
  64. package/src/index.ts +10 -0
  65. package/src/testing/index.ts +7 -0
  66. package/src/testing/reference.ts +91 -0
  67. package/src/testing/scenarios.ts +604 -0
  68. package/src/testing/simulate.ts +127 -0
@@ -0,0 +1,234 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as Ast from '@dxos/datalog/Ast';
8
+ import type * as Builtin from '@dxos/datalog/Builtin';
9
+ import * as Checker from '@dxos/datalog/Checker';
10
+ import * as Parser from '@dxos/datalog/Parser';
11
+ import { BaseError } from '@dxos/errors';
12
+
13
+ import * as Builtins from './Builtins.ts';
14
+ import * as Encoding from './Encoding.ts';
15
+ import * as Vocabulary from './Vocabulary.ts';
16
+
17
+ /** Heads a goal program may define: `achieved(goal)`, `holds(goal)`, `wake(Label)`, `blocks(Action)`. */
18
+ export const GOAL_HEADS = ['achieved', 'holds', 'wake', 'blocks'] as const;
19
+
20
+ /** Relations goal rules may read; goal heads a program leaves undefined are empty. */
21
+ export const RELATIONS: Readonly<Record<string, number>> = {
22
+ ...Encoding.RELATIONS,
23
+ ...Object.fromEntries(GOAL_HEADS.map((head) => [head, 1])),
24
+ };
25
+
26
+ export type DiagnosticCode = Checker.DiagnosticCode | 'parse' | 'vocabulary' | 'goal';
27
+
28
+ export type Diagnostic = {
29
+ readonly code: DiagnosticCode;
30
+ readonly message: string;
31
+ readonly position?: Ast.Position;
32
+ };
33
+
34
+ /** A checked goal program ready for evaluation. */
35
+ export type Compilation = {
36
+ readonly source: string;
37
+ readonly program: Ast.Program;
38
+ /** Per-rule wake relations (one tuple per binding) and the label each one wakes. */
39
+ readonly wakes: ReadonlyMap<string, string>;
40
+ };
41
+
42
+ export type Options = {
43
+ readonly vocabulary?: Vocabulary.Vocabulary;
44
+ /** Defaults to the goal built-ins over an empty context (signatures are all checking needs). */
45
+ readonly builtins?: Builtin.Registry;
46
+ };
47
+
48
+ /** Thrown by `compileOrThrow` and `GoalRules` when compilation reports diagnostics. */
49
+ export class CompileError extends BaseError.extend('CompileError', 'Goal rules do not compile') {
50
+ // A typed field rather than `context`, which would repeat every diagnostic in the message as JSON.
51
+ readonly diagnostics: ReadonlyArray<Diagnostic>;
52
+
53
+ constructor(diagnostics: ReadonlyArray<Diagnostic>) {
54
+ super({ message: `Goal rules do not compile:\n${diagnostics.map(formatDiagnostic).join('\n')}` });
55
+ this.diagnostics = diagnostics;
56
+ }
57
+ }
58
+
59
+ /** Formats a diagnostic as `line:column code: message`. */
60
+ export const formatDiagnostic = ({ code, message, position }: Diagnostic): string =>
61
+ `${position ? `${position.line}:${position.column} ` : ''}${code}: ${message}`;
62
+
63
+ /** The vocabulary used when none is given. */
64
+ export const defaultVocabulary = (): Vocabulary.Vocabulary =>
65
+ Vocabulary.make(Vocabulary.DEFAULT_ENTRIES, [...Object.keys(Encoding.RELATIONS), ...GOAL_HEADS]);
66
+
67
+ /**
68
+ * Compiles goal rules: parses, expands predicate shorthand for canonical vocabulary predicates
69
+ * (`helps_with(S, O)` → `fact(_, S, helps_with, O)`, `helps_with(F, S, O)` exposes the id),
70
+ * checks goal heads, then runs the engine's static checks against the fact relations.
71
+ */
72
+ export const compile = (
73
+ source: string,
74
+ options: Options = {},
75
+ ): { compilation?: Compilation; diagnostics: Diagnostic[] } => {
76
+ const vocabulary = options.vocabulary ?? defaultVocabulary();
77
+ const builtins = options.builtins ?? Builtins.make(Builtins.emptyContext());
78
+
79
+ let parsed: Ast.Program;
80
+ try {
81
+ parsed = Parser.parse(source);
82
+ } catch (error) {
83
+ if (error instanceof Parser.ParseError) {
84
+ return { diagnostics: [{ code: 'parse', message: error.reason, position: error.position }] };
85
+ }
86
+ throw error;
87
+ }
88
+
89
+ const diagnostics: Diagnostic[] = [];
90
+ const defined = new Set(parsed.rules.map((rule) => rule.head.predicate));
91
+ let anonymous = 0;
92
+
93
+ const rewriteAtom = (literal: Ast.AtomLiteral, fallback: Ast.Position | undefined): Ast.AtomLiteral => {
94
+ const { predicate, terms } = literal.atom;
95
+ const position = literal.position ?? fallback;
96
+ if (predicate === 'fact') {
97
+ const stored = terms[2];
98
+ if (stored?.type === 'constant') {
99
+ const canonical = vocabulary.canonical(String(stored.value));
100
+ if (canonical !== undefined && canonical !== stored.value) {
101
+ diagnostics.push({
102
+ code: 'vocabulary',
103
+ message: `predicate "${stored.value}" is stored as ${canonical}; use ${canonical}`,
104
+ position,
105
+ });
106
+ }
107
+ }
108
+ return literal;
109
+ }
110
+ if (predicate in Encoding.RELATIONS || builtins.has(predicate) || defined.has(predicate)) {
111
+ return literal;
112
+ }
113
+ if (vocabulary.isCanonical(predicate)) {
114
+ if (terms.length !== 2 && terms.length !== 3) {
115
+ diagnostics.push({
116
+ code: 'vocabulary',
117
+ message: `shorthand ${predicate} takes (Subject, Object) or (Fact, Subject, Object), not ${terms.length} arguments`,
118
+ position,
119
+ });
120
+ return literal;
121
+ }
122
+ const id: Ast.Term =
123
+ terms.length === 3 ? terms[0] : { type: 'variable', name: `_shorthand${anonymous++}`, anonymous: true };
124
+ const [subject, object] = terms.length === 3 ? [terms[1], terms[2]] : [terms[0], terms[1]];
125
+ return { ...literal, atom: Ast.atom('fact', [id, subject, Ast.constant(predicate), object]) };
126
+ }
127
+ const canonical = vocabulary.canonical(predicate);
128
+ if (canonical !== undefined) {
129
+ diagnostics.push({
130
+ code: 'vocabulary',
131
+ message: `${predicate} is a synonym; shorthand must use the canonical predicate ${canonical}`,
132
+ position,
133
+ });
134
+ }
135
+ return literal;
136
+ };
137
+
138
+ const rewriteLiteral = (literal: Ast.Literal, fallback: Ast.Position | undefined): Ast.Literal => {
139
+ switch (literal.type) {
140
+ case 'atom':
141
+ return rewriteAtom(literal, fallback);
142
+ case 'comparison':
143
+ return literal;
144
+ case 'aggregate':
145
+ return { ...literal, body: literal.body.map((inner) => rewriteLiteral(inner, literal.position ?? fallback)) };
146
+ }
147
+ };
148
+
149
+ const rules: Ast.Rule[] = [];
150
+ const wakes = new Map<string, string>();
151
+ parsed.rules.forEach((parsedRule, index) => {
152
+ const rule = {
153
+ ...parsedRule,
154
+ body: parsedRule.body.map((literal) => rewriteLiteral(literal, parsedRule.position)),
155
+ };
156
+ const { predicate, terms } = rule.head;
157
+ if (predicate in Encoding.RELATIONS) {
158
+ diagnostics.push({
159
+ code: 'goal',
160
+ message: `rules cannot define the base relation ${predicate}`,
161
+ position: rule.position,
162
+ });
163
+ }
164
+ if (isGoalHead(predicate)) {
165
+ const [argument] = terms;
166
+ if (terms.length !== 1) {
167
+ diagnostics.push({ code: 'goal', message: `${predicate} takes one argument`, position: rule.position });
168
+ } else if (predicate !== 'blocks' && argument.type !== 'constant') {
169
+ diagnostics.push({ code: 'goal', message: `${predicate} takes a constant argument`, position: rule.position });
170
+ } else if (
171
+ (predicate === 'achieved' || predicate === 'holds') &&
172
+ (argument.type !== 'constant' || argument.value !== 'goal')
173
+ ) {
174
+ diagnostics.push({
175
+ code: 'goal',
176
+ message: `${predicate} must be written ${predicate}(goal)`,
177
+ position: rule.position,
178
+ });
179
+ }
180
+ }
181
+
182
+ const label = terms[0];
183
+ if (predicate === 'wake' && terms.length === 1 && label.type === 'constant' && rule.body.length > 0) {
184
+ // One relation per wake rule, carrying its body bindings, so each new binding is a new tuple.
185
+ const relation = `wake#${index}`;
186
+ const variables = bodyVariables(rule.body).map((name) => Ast.variable(name));
187
+ wakes.set(relation, String(label.value));
188
+ rules.push({ ...rule, head: Ast.atom(relation, [label, ...variables]) });
189
+ rules.push({
190
+ head: rule.head,
191
+ body: [{ type: 'atom', negated: false, atom: Ast.atom(relation, [label, ...variables]) }],
192
+ position: rule.position,
193
+ });
194
+ } else {
195
+ rules.push(rule);
196
+ }
197
+ });
198
+
199
+ const program: Ast.Program = { rules };
200
+ if (diagnostics.length > 0) {
201
+ // Engine checks would repeat each vocabulary error as an undefined predicate.
202
+ return { diagnostics };
203
+ }
204
+ for (const diagnostic of Checker.check(program, { builtins, relations: RELATIONS })) {
205
+ diagnostics.push({ code: diagnostic.code, message: diagnostic.message, position: diagnostic.position });
206
+ }
207
+ return diagnostics.length > 0 ? { diagnostics } : { compilation: { source, program, wakes }, diagnostics };
208
+ };
209
+
210
+ /** Compiles goal rules, throwing on any diagnostic. */
211
+ export const compileOrThrow = (source: string, options: Options = {}): Compilation => {
212
+ const { compilation, diagnostics } = compile(source, options);
213
+ if (!compilation) {
214
+ throw new CompileError(diagnostics);
215
+ }
216
+ return compilation;
217
+ };
218
+
219
+ const isGoalHead = (predicate: string): boolean => GOAL_HEADS.some((head) => head === predicate);
220
+
221
+ /** Variables a safe body binds: those of positive literals, comparisons and aggregate results. */
222
+ const bodyVariables = (body: ReadonlyArray<Ast.Literal>): string[] => {
223
+ const names = new Set<string>();
224
+ for (const literal of body) {
225
+ if (literal.type === 'atom' && !literal.negated) {
226
+ Ast.variablesOf(literal.atom.terms).forEach((name) => names.add(name));
227
+ } else if (literal.type === 'comparison') {
228
+ Ast.variablesOf([literal.left, literal.right]).forEach((name) => names.add(name));
229
+ } else if (literal.type === 'aggregate') {
230
+ Ast.variablesOf([literal.result]).forEach((name) => names.add(name));
231
+ }
232
+ }
233
+ return [...names];
234
+ };
@@ -0,0 +1,99 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import type * as Engine from '@dxos/datalog/Engine';
8
+ import { RDF } from '@dxos/pipeline-rdf';
9
+
10
+ import type * as Vocabulary from './Vocabulary.ts';
11
+
12
+ /** Relations every fact contributes to, keyed by the fact id `F`. */
13
+ export const FACT_RELATIONS = {
14
+ fact: 4,
15
+ speaker: 2,
16
+ force: 2,
17
+ polarity: 2,
18
+ mood: 2,
19
+ factuality: 2,
20
+ addressee: 2,
21
+ quote: 2,
22
+ source: 2,
23
+ saidAt: 2,
24
+ surface: 2,
25
+ supersedes: 2,
26
+ validFrom: 2,
27
+ validTo: 2,
28
+ confidence: 2,
29
+ nature: 2,
30
+ recordedAt: 2,
31
+ pass: 2,
32
+ } as const;
33
+
34
+ /** Relations the goal runtime maintains: sub-goal status and proposed actions. */
35
+ export const GOAL_RELATIONS = {
36
+ subgoal: 2,
37
+ status: 2,
38
+ action: 2,
39
+ actionArg: 3,
40
+ } as const;
41
+
42
+ /** Every base relation a goal rule may read. */
43
+ export const RELATIONS: Readonly<Record<string, number>> = { ...FACT_RELATIONS, ...GOAL_RELATIONS };
44
+
45
+ /**
46
+ * Encodes a fact as `fact(F, S, P, O)` plus one metadata relation per present field. `P` is the
47
+ * canonical predicate when the vocabulary knows the surface form, which `surface(F, …)` keeps; a fact
48
+ * without an illocution is `assertive`, and `supersedes` lists `attribution.wasDerivedFrom`.
49
+ */
50
+ export const encode = (fact: RDF.Fact, vocabulary?: Vocabulary.Vocabulary): Engine.Entry[] => {
51
+ const { id, assertion, factuality, illocution, attribution } = fact;
52
+ const entries: Engine.Entry[] = [
53
+ {
54
+ relation: 'fact',
55
+ tuple: [
56
+ id,
57
+ RDF.termValue(assertion.subject),
58
+ vocabulary?.resolve(assertion.predicate) ?? assertion.predicate,
59
+ RDF.termValue(assertion.object),
60
+ ],
61
+ },
62
+ { relation: 'surface', tuple: [id, assertion.predicate] },
63
+ { relation: 'force', tuple: [id, illocution?.force ?? 'assertive'] },
64
+ { relation: 'polarity', tuple: [id, factuality.polarity] },
65
+ { relation: 'factuality', tuple: [id, factuality.value] },
66
+ { relation: 'source', tuple: [id, attribution.source] },
67
+ { relation: 'saidAt', tuple: [id, attribution.generatedAtTime] },
68
+ { relation: 'recordedAt', tuple: [id, fact.recordedAt] },
69
+ ];
70
+ const optional: ReadonlyArray<[string, string | number | undefined]> = [
71
+ ['speaker', attribution.agent],
72
+ ['mood', illocution?.mood],
73
+ ['addressee', illocution?.addressee],
74
+ ['quote', assertion.quote],
75
+ ['validFrom', assertion.validFrom],
76
+ ['validTo', assertion.validTo],
77
+ ['confidence', factuality.confidence],
78
+ ['nature', factuality.nature],
79
+ ['pass', fact.pass],
80
+ ];
81
+ for (const [relation, value] of optional) {
82
+ if (value !== undefined) {
83
+ entries.push({ relation, tuple: [id, value] });
84
+ }
85
+ }
86
+ for (const superseded of attribution.wasDerivedFrom ?? []) {
87
+ entries.push({ relation: 'supersedes', tuple: [id, superseded] });
88
+ }
89
+ return entries;
90
+ };
91
+
92
+ /** The fact ids among base entries (from provenance). */
93
+ export const factIds = (entries: ReadonlyArray<Engine.Entry>): string[] => [
94
+ ...new Set(
95
+ entries.flatMap(({ relation, tuple }) =>
96
+ relation in FACT_RELATIONS && typeof tuple[0] === 'string' ? [tuple[0]] : [],
97
+ ),
98
+ ),
99
+ ];
@@ -0,0 +1,96 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import * as GoalRules from './GoalRules.ts';
8
+ import { REFERENCE, SCENARIOS, WRONG, simulate, toFact } from './testing/index.ts';
9
+
10
+ describe('GoalRules', () => {
11
+ describe('example goals replay against their reference compilations', () => {
12
+ test.for(SCENARIOS.map((scenario) => [scenario.n, scenario.goal] as const))(
13
+ 'goal %i: %s',
14
+ ([number], { expect }) => {
15
+ const scenario = SCENARIOS.find((candidate) => candidate.n === number);
16
+ expect(scenario).toBeDefined();
17
+ if (scenario) {
18
+ const result = simulate(scenario, REFERENCE[number]);
19
+ expect(result.failures).toEqual([]);
20
+ }
21
+ },
22
+ );
23
+ });
24
+
25
+ describe('replay rejects wrong compilations', () => {
26
+ test.for(WRONG.map(({ scenario, note, source }) => [scenario, note, source] as const))(
27
+ 'goal %i: %s',
28
+ ([number, , source], { expect }) => {
29
+ const scenario = SCENARIOS.find((candidate) => candidate.n === number);
30
+ expect(scenario).toBeDefined();
31
+ if (scenario) {
32
+ const result = simulate(scenario, source);
33
+ expect(result.steps).toHaveLength(scenario.steps.length);
34
+ expect(result.failures.length).toBeGreaterThan(0);
35
+ }
36
+ },
37
+ );
38
+ });
39
+
40
+ test('wakes once per new binding and reports the facts behind it', ({ expect }) => {
41
+ const createdAt = Date.parse('2027-01-04T09:00:00Z');
42
+ const rules = GoalRules.make({ source: 'wake(reply) :- speaker(F, dima), about(F, "plugin").', createdAt });
43
+ const say = (id: string, quote: string, minutes: number) => {
44
+ const saidAt = new Date(createdAt + minutes * 60_000).toISOString();
45
+ return rules.update({
46
+ at: Date.parse(saidAt),
47
+ facts: [
48
+ toFact(
49
+ {
50
+ id,
51
+ speaker: 'dima',
52
+ quote,
53
+ s: 'dima',
54
+ p: 'says',
55
+ o: 'x',
56
+ force: 'assertive',
57
+ polarity: '+',
58
+ mood: 'declarative',
59
+ source: 'chat',
60
+ factuality: 'CT+',
61
+ },
62
+ saidAt,
63
+ ),
64
+ ],
65
+ });
66
+ };
67
+
68
+ expect(say('f1', 'the plugin is ready', 1).wakes).toEqual([{ label: 'reply', cause: 'rule', facts: ['f1'] }]);
69
+ expect(say('f2', 'lunch?', 2).wakes).toEqual([]);
70
+ expect(say('f3', 'plugin docs too', 3).wakes).toEqual([{ label: 'reply', cause: 'rule', facts: ['f3'] }]);
71
+ });
72
+
73
+ test('wakes when achieved first holds and when a sub-goal changes status', ({ expect }) => {
74
+ const rules = GoalRules.make({
75
+ source:
76
+ 'achieved(goal) :- subgoal(goal, G), status(G, done), not open.\nopen :- subgoal(goal, G), status(G, active).',
77
+ createdAt: 0,
78
+ });
79
+ expect(rules.update({ at: 1, subgoals: { first: 'active', second: 'done' } }).wakes).toEqual([]);
80
+ const evaluation = rules.update({ at: 2, subgoals: { first: 'done', second: 'done' } });
81
+ expect(evaluation.achieved).toBe(true);
82
+ expect(evaluation.wakes.map(({ label, cause }) => [label, cause])).toEqual([
83
+ ['first', 'subgoal'],
84
+ ['achieved', 'achieved'],
85
+ ]);
86
+ expect(rules.update({ at: 3 }).wakes).toEqual([]);
87
+ });
88
+
89
+ test('checks proposed actions without keeping them', ({ expect }) => {
90
+ const rules = GoalRules.make({ source: REFERENCE[7], createdAt: 0 });
91
+ const friday = { id: 'a1', kind: 'book_meeting', args: { start: '2027-01-08T15:00:00Z' } };
92
+ expect(rules.checkAction(friday).blocked).toBe(true);
93
+ expect(rules.checkAction({ ...friday, id: 'a2', args: { start: '2027-01-05T10:00:00Z' } }).blocked).toBe(false);
94
+ expect(rules.checkAction(friday).blocked).toBe(true);
95
+ });
96
+ });
@@ -0,0 +1,181 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import type * as Ast from '@dxos/datalog/Ast';
8
+ import * as Engine from '@dxos/datalog/Engine';
9
+ import { RDF } from '@dxos/pipeline-rdf';
10
+
11
+ import * as Builtins from './Builtins.ts';
12
+ import * as Compiler from './Compiler.ts';
13
+ import * as Encoding from './Encoding.ts';
14
+ import type * as Vocabulary from './Vocabulary.ts';
15
+
16
+ /** A reason to run judgment on the goal. */
17
+ export type Wake = {
18
+ /** The wake rule's label, `achieved`, or the sub-goal whose status changed. */
19
+ readonly label: string;
20
+ readonly cause: 'rule' | 'achieved' | 'subgoal';
21
+ /** Ids of the facts the waking derivation rests on. */
22
+ readonly facts: ReadonlyArray<string>;
23
+ };
24
+
25
+ export type Evaluation = {
26
+ readonly at: number;
27
+ readonly wakes: ReadonlyArray<Wake>;
28
+ readonly achieved: boolean;
29
+ readonly holds: boolean;
30
+ };
31
+
32
+ /** An action the agent proposes, checked against the goal's `blocks` rules before it runs. */
33
+ export type Action = {
34
+ readonly id: string;
35
+ readonly kind: string;
36
+ readonly args: Readonly<Record<string, string>>;
37
+ };
38
+
39
+ export type ActionCheck = {
40
+ readonly blocked: boolean;
41
+ /** Ids of the facts that contributed to the block (empty when only the action did). */
42
+ readonly facts: ReadonlyArray<string>;
43
+ };
44
+
45
+ export type Options = {
46
+ readonly source: string;
47
+ /** When the goal was created (epoch ms); also the clock's starting time. */
48
+ readonly createdAt: number;
49
+ readonly vocabulary?: Vocabulary.Vocabulary;
50
+ readonly text?: Builtins.TextIndex;
51
+ readonly entities?: Builtins.EntityIndex;
52
+ /** Entities a fact concerns; defaults to its subject. */
53
+ readonly concerns?: (fact: RDF.Fact) => ReadonlyArray<string>;
54
+ };
55
+
56
+ export type Input = {
57
+ /** Evaluation time (epoch ms); a change re-evaluates time built-ins. */
58
+ readonly at: number;
59
+ readonly facts?: ReadonlyArray<RDF.Fact>;
60
+ /** Current status of each sub-goal; a new id adds the sub-goal. */
61
+ readonly subgoals?: Readonly<Record<string, string>>;
62
+ };
63
+
64
+ /**
65
+ * Evaluates one goal's compiled rules over a growing fact stream and a clock. A goal wakes when a
66
+ * wake rule gains a new binding, when `achieved` first becomes true, and when a sub-goal's status
67
+ * changes.
68
+ */
69
+ export class GoalRules {
70
+ readonly compilation: Compiler.Compilation;
71
+ readonly #engine: Engine.Engine;
72
+ readonly #vocabulary: Vocabulary.Vocabulary;
73
+ readonly #text: Builtins.TextIndex;
74
+ readonly #entities: Builtins.EntityIndex;
75
+ readonly #concerns: (fact: RDF.Fact) => ReadonlyArray<string>;
76
+ readonly #saidAt = new Map<string, number>();
77
+ readonly #subgoals = new Map<string, string>();
78
+ #now: number;
79
+ #previous: number;
80
+ #achieved = false;
81
+
82
+ /** @throws Compiler.CompileError if the rules do not compile. */
83
+ constructor(options: Options) {
84
+ this.#now = options.createdAt;
85
+ this.#previous = options.createdAt;
86
+ this.#vocabulary = options.vocabulary ?? Compiler.defaultVocabulary();
87
+ this.#text = options.text ?? new Builtins.KeywordIndex();
88
+ this.#entities = options.entities ?? new Builtins.MemoryEntityIndex();
89
+ this.#concerns = options.concerns ?? ((fact) => [RDF.termValue(fact.assertion.subject)]);
90
+ const builtins = Builtins.make({
91
+ clock: {
92
+ now: () => this.#now,
93
+ previous: () => this.#previous,
94
+ createdAt: options.createdAt,
95
+ saidAt: (factId) => this.#saidAt.get(factId),
96
+ },
97
+ text: this.#text,
98
+ entities: this.#entities,
99
+ });
100
+ this.compilation = Compiler.compileOrThrow(options.source, { vocabulary: this.#vocabulary, builtins });
101
+ this.#engine = Engine.make({ program: this.compilation.program, builtins, relations: Compiler.RELATIONS });
102
+ this.#achieved = this.achieved;
103
+ }
104
+
105
+ get achieved(): boolean {
106
+ return this.#engine.has('achieved', ['goal']);
107
+ }
108
+
109
+ get holds(): boolean {
110
+ return this.#engine.has('holds', ['goal']);
111
+ }
112
+
113
+ /** Adds facts and sub-goal status at time `at`; returns the wakes and the goal's state. */
114
+ update({ at, facts = [], subgoals = {} }: Input): Evaluation {
115
+ this.#previous = this.#now;
116
+ this.#now = at;
117
+ const insert: Engine.Entry[] = [];
118
+ const retract: Engine.Entry[] = [];
119
+ for (const fact of facts) {
120
+ this.#saidAt.set(fact.id, Date.parse(fact.attribution.generatedAtTime));
121
+ this.#text.add(fact.id, factText(fact));
122
+ this.#entities.add(fact.id, this.#concerns(fact));
123
+ insert.push(...Encoding.encode(fact, this.#vocabulary));
124
+ }
125
+
126
+ const wakes: Wake[] = [];
127
+ for (const [subgoal, status] of Object.entries(subgoals)) {
128
+ const previous = this.#subgoals.get(subgoal);
129
+ if (previous === status) {
130
+ continue;
131
+ }
132
+ if (previous === undefined) {
133
+ insert.push({ relation: 'subgoal', tuple: ['goal', subgoal] });
134
+ } else {
135
+ retract.push({ relation: 'status', tuple: [subgoal, previous] });
136
+ wakes.push({ label: subgoal, cause: 'subgoal', facts: [] });
137
+ }
138
+ insert.push({ relation: 'status', tuple: [subgoal, status] });
139
+ this.#subgoals.set(subgoal, status);
140
+ }
141
+
142
+ const changes = this.#engine.update({ insert, retract, refresh: this.#now !== this.#previous });
143
+ for (const [relation, label] of this.compilation.wakes) {
144
+ for (const tuple of changes.added.get(relation) ?? []) {
145
+ wakes.push({ label, cause: 'rule', facts: Encoding.factIds(this.#engine.provenance(relation, tuple)) });
146
+ }
147
+ }
148
+
149
+ const achieved = this.achieved;
150
+ if (achieved && !this.#achieved) {
151
+ wakes.push({
152
+ label: 'achieved',
153
+ cause: 'achieved',
154
+ facts: Encoding.factIds(this.#engine.provenance('achieved', ['goal'])),
155
+ });
156
+ }
157
+ this.#achieved = achieved;
158
+ return { at, wakes, achieved, holds: this.holds };
159
+ }
160
+
161
+ /** Evaluates the `blocks` rules for a proposed action without keeping it. */
162
+ checkAction(action: Action): ActionCheck {
163
+ const entries: Engine.Entry[] = [
164
+ { relation: 'action', tuple: [action.id, action.kind] },
165
+ ...Object.entries(action.args).map(([key, value]) => ({ relation: 'actionArg', tuple: [action.id, key, value] })),
166
+ ];
167
+ this.#engine.update({ insert: entries });
168
+ const tuple: Ast.Tuple = [action.id];
169
+ const blocked = this.#engine.has('blocks', tuple);
170
+ const facts = blocked ? Encoding.factIds(this.#engine.provenance('blocks', tuple)) : [];
171
+ this.#engine.update({ retract: entries });
172
+ return { blocked, facts };
173
+ }
174
+ }
175
+
176
+ /** Creates a goal evaluator. */
177
+ export const make = (options: Options): GoalRules => new GoalRules(options);
178
+
179
+ /** The text `about` matches: what was said plus the triple. */
180
+ const factText = ({ assertion }: RDF.Fact): string =>
181
+ [assertion.quote ?? '', RDF.termValue(assertion.subject), assertion.predicate, RDF.termValue(assertion.object)].join(' ');
@@ -0,0 +1,48 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import { Predicate } from '@dxos/pipeline-rdf/types';
8
+
9
+ import * as Vocabulary from './Vocabulary.ts';
10
+
11
+ describe('Vocabulary', () => {
12
+ test('normalize applies the fact store relation key before joining words', ({ expect }) => {
13
+ for (const surface of ['works at', 'Works At', 'is working at', 'worked-at', 'works_at']) {
14
+ expect(Vocabulary.normalize(surface)).toBe(Predicate.normalize('works at').replace(/\s+/g, '_'));
15
+ }
16
+ expect(Vocabulary.normalize('Will-Work-On')).toBe(Vocabulary.normalize('working on'));
17
+ expect(Vocabulary.normalize(Vocabulary.normalize('is helping with'))).toBe(Vocabulary.normalize('is helping with'));
18
+ });
19
+
20
+ test('canonicalizes inflected and auxiliary surface forms', ({ expect }) => {
21
+ const vocabulary = Vocabulary.make(Vocabulary.DEFAULT_ENTRIES);
22
+ expect(vocabulary.canonical('works_on')).toBe('works_on');
23
+ expect(vocabulary.canonical('is working on')).toBe('works_on');
24
+ expect(vocabulary.canonical('worked on')).toBe('works_on');
25
+ expect(vocabulary.canonical('Helped-With')).toBe('helps_with');
26
+ expect(vocabulary.canonical('was finished')).toBe('completed');
27
+ expect(vocabulary.resolve('is waiting for')).toBe('awaiting');
28
+ expect(vocabulary.resolve('hates')).toBe('hates');
29
+ });
30
+
31
+ test('keeps synonyms that differ beyond inflection distinct', ({ expect }) => {
32
+ const vocabulary = Vocabulary.make([
33
+ { predicate: 'works_at', synonyms: ['employed by'] },
34
+ { predicate: 'works_for' },
35
+ ]);
36
+ expect(vocabulary.canonical('is employed by')).toBe('works_at');
37
+ expect(vocabulary.canonical('working for')).toBe('works_for');
38
+ });
39
+
40
+ test('rejects synonyms that collapse onto two canonical predicates', ({ expect }) => {
41
+ expect(() =>
42
+ Vocabulary.make([
43
+ { predicate: 'likes', synonyms: ['is fond of'] },
44
+ { predicate: 'loves', synonyms: ['fond of'] },
45
+ ]),
46
+ ).toThrow(/maps to both/);
47
+ });
48
+ });